code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
---
layout: post
title: "Welcome to Jekyll!"
date: 2016-09-15 12:25:26 +0100
categories: jekyll update
---
You’ll find this onion in your `_posts` directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different ways, but the most common way is to run `jekyll serve`, which launches a web server and auto-regenerates your site when a file is updated.
To add new posts, simply add a file in the `_posts` directory that follows the convention `YYYY-MM-DD-name-of-post.ext` and includes the necessary front matter. Take a look at the source for this post to get an idea about how it works.
Jekyll also offers powerful support for code snippets:
{% highlight ruby %}
def print_hi(name)
puts "Hi, #{name}"
end
print_hi('Tom')
#=> prints 'Hi, Tom' to STDOUT.
{% endhighlight %}
Check out the [Jekyll docs][jekyll-docs] for more info on how to get the most out of Jekyll. File all bugs/feature requests at [Jekyll’s GitHub repo][jekyll-gh]. If you have questions, you can ask them on [Jekyll Talk][jekyll-talk].
[jekyll-docs]: http://jekyllrb.com/docs/home
[jekyll-gh]: https://github.com/jekyll/jekyll
[jekyll-talk]: https://talk.jekyllrb.com/
|
Lovatt/lovatt.github.io
|
_posts/2016-09-15-welcome-to-jekyll.markdown
|
Markdown
|
mit
| 1,207
|
{% extends 'base.html' %}
{% load commentBox %}
{% block title %}Edit profile | {{ site.title | safe }}{% endblock title %}
{% block content %}
<div class="content-header padded">
<div class="row">
<div class="col-sm-12">
{% include 'breadcrumbs.html' %}
</div>
</div>
<a href="{% url 'updates-settings' %}" class="pull-right">Notification Settings →</a>
<h1>Edit Profile</h1>
<div class="clearfix"></div>
</div>
<div class="content-body">
<div class="row form-container">
<div class="col-lg-12">
<form id="profileform" role="form" action="{% url 'edit-profile' user.id %}" method="POST" enctype="multipart/form-data">
<div class="form-container-inner padded">
{% csrf_token %}
{{ form.id }}
{# username #}
<div class="form-group">
<div class="row">
<label class="col-sm-12" for="profileName">
{{ form.profileName.label }}
</label>
<div class="col-sm-12">
{% if form.errors.profileName %}
<div class="text-error">{{ form.errors.profileName.as_text }}</div>
{% endif %}
<input
type="text"
class="form-control"
id="edit_profile_name"
name="{{ form.profileName.name }}"
value="{{ form.profileName.value }}"
placeholder="Enter username..."
maxlength="{{ form.fields.profileName.max_length}}"
tabindex="1"
/>
</div>
</div>
</div> <!-- /form-group -->
{# profile picture #}
<div class="form-group">
<div class="row">
<label class="col-sm-12" for="avatar">{{ form.avatar.label }}</label>
<div class="col-sm-12">
<div class="form-file-upload">
<label
{% if 'files' in user.avatar %}
class="active"
style="background-image:url('https://{{site.subdomain_key}}.microco.sm{{user.avatar}}')"
{% endif %}
>
<span>Click here</span>
<input
name="{{ form.avatar.name }}"
type="file"
accept="image/*"
capture="camera"
tabindex="1"
/>
</label>
<div class="form-file-upload-text">
<h3>Click on or drag an image over the box on the left to change your picture</h3>
{% if avatar_error %}
<div class="has-error">
<div class="control-label">{{ avatar_error }}</div>
</div>
{% else %}
<p>Your avatar should be a jpg, png or gif file.</p>
{% endif %}
</div>
</div>
</div>
</div>
</div> <!-- /form-group -->
{# comment #}
<div class="form-group">
<div class="row">
<label class="col-sm-12" for="reply-box-textarea">Tell us about yourself</label>
<div class="col-sm-12">
{% commentBox as_component=True no_attachments=True value=form.markdown.value %}
</div>
</div>
</div> <!-- /form-group -->
</div> <!-- /form-container-inner -->
{# footer #}
<div class="form-group form-footer padded">
<div class="row">
<div class="col-sm-12">
<div class="form-footer-buttons">
<input type="submit" class="btn btn-lg btn-primary" value="Save Changes" id="submit" tabindex="1" />
<input type="reset" class="btn btn-lg btn-default" value="Cancel" />
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock content %}
{% block sidebar %}
<div class="metabar-module">
<h5>About</h5>
<div class="metabar-module-title">
<h3>
Edit Profile
</h3>
</div>
</div> <!-- / about -->
{% endblock %}
{% block js %}
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery.textcomplete.min.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}js/profilePicture.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}js/formValidator.js"></script>
<script type="text/javascript" src="{{STATIC_URL}}js/attachments.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}js/Markdown.Converter.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}js/Markdown.Editor.js?v20160728"></script>
<script type="text/javascript" src="{{STATIC_URL}}js/simpleEditor.js"></script>
<script type="text/javascript">
(function(){
var commentBox = new simpleEditor({
el : '.reply-box',
no_attachments : true
});
if (typeof ProfilePicture !== 'undefined'){
var profilePicture = new ProfilePicture({
el : '.form-file-upload'
});
}
/////////////////////
// form validation //
/////////////////////
var form = new FormValidator(
document.getElementById('profileform'),
{
rules : {
'{{ form.profileName.name }}' : ['not_empty', 'maxlength', 'validChars']
},
tests : {
'validChars': function(field){
var $field = $(field),
name = $field.val();
return (name.match(/^[^@+\s]+$/i));
},
'maxlength' : function(field){ var $field = $(field); return $field.val().length < parseInt($field.attr('maxlength'),10); }
},
error_messages : {
'{{ form.profileName.name }}:not_empty' : "* {{ form.fields.profileName.error_messages.required }}",
'{{ form.profileName.name }}:maxlength' : "* {{ form.fields.profileName.error_messages.max_length }}",
'{{ form.profileName.name }}:validChars': "* {{ form.fields.profileName.error_messages.valid_chars|safe }}"
}
}
);
})();
</script>
{% endblock js %}
|
microcosm-cc/microweb
|
core/templates/forms/profile.html
|
HTML
|
mit
| 5,621
|
# Get-Quote
## Overview
Python program to scrape brainyquote.com for quotes from a user entered author. Also contains a DataBase feature to store and search for previously viewed quotes
Will create a file in directory named .Quotes.db
## Requirements
* [BeautifulSoup4](https://pypi.python.org/pypi/beautifulsoup4)
* [Shelve](https://docs.python.org/2/library/shelve.html)
## Usage
```
./GetQuote.py AUTHOR
```
Returns 10 quotes from brainyquote.com that match author user provides
Prompts user if they want to save any quotes into DataBase
```
./GetQuote.py -d
```
DataBase Manager for storing previously searched quotes
```
./GetQuote.py -h [or -help]
```
Displays the different usages
## License
MIT license, see License
|
mariot/Get-Quote
|
README.md
|
Markdown
|
mit
| 734
|
---
byline: ''
description: ''
headline: ''
image_url: ''
pub_date: 2017-07-01 15:24:22.457557
published: false
show_in_feeds: false
---
|
datadesk/django-bigbuild
|
example/pages/foobar-561/metadata.md
|
Markdown
|
mit
| 136
|
---
layout: page
title: Julie Edwards's 75th Birthday
date: 2016-05-24
author: Sharon Shah
tags: weekly links, java
status: published
summary: Mauris tincidunt velit id magna mattis, et hendrerit magna facilisis.
banner: images/banner/leisure-01.jpg
booking:
startDate: 09/09/2018
endDate: 09/12/2018
ctyhocn: STLHLHX
groupCode: JE7B
published: true
---
Nullam sed tincidunt ligula, quis consectetur leo. Pellentesque pretium vulputate facilisis. Pellentesque sit amet ligula auctor, tristique justo sed, posuere lacus. Suspendisse iaculis gravida vulputate. Ut quis ipsum eros. Maecenas accumsan consequat mi, ac tempor sem faucibus et. Duis tristique nulla et est auctor, eget tincidunt libero auctor. Nunc elementum augue id interdum sollicitudin. Maecenas euismod ex urna, a lobortis odio pellentesque non.
* Cras eget ligula ac eros facilisis eleifend
* Vestibulum et erat non augue tincidunt ornare
* Curabitur euismod sapien vitae dui vestibulum, sodales accumsan mauris accumsan.
Nulla lectus sem, rhoncus nec dapibus eget, suscipit ut mauris. Vivamus ac libero a risus euismod placerat. Suspendisse at augue lorem. Suspendisse fermentum, risus sed varius vestibulum, est nisl tempus ex, sed consectetur diam nisl non dui. Etiam consequat porta augue, a vestibulum odio volutpat eu. Etiam luctus finibus lectus in pretium. Morbi ipsum mi, cursus vel nulla eu, aliquet mattis ante.
Quisque fermentum velit a leo pharetra, ac sollicitudin ligula pharetra. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vivamus maximus pretium ex, viverra volutpat augue mattis sed. Sed ac diam accumsan neque laoreet tempus. Morbi nisi nunc, sagittis nec facilisis ac, laoreet at nibh. Quisque at justo semper, porta nunc dignissim, maximus quam. Phasellus finibus at est quis gravida. Aliquam ornare fermentum risus non commodo. Vivamus sed nulla scelerisque, porta felis in, maximus nibh. Aenean quis dolor suscipit, finibus lorem eu, imperdiet metus. Nunc tortor lorem, laoreet nec est at, posuere mollis urna. Quisque eget mollis purus, at euismod nunc. Nulla accumsan metus lacus, vitae elementum lectus placerat id. Ut ultrices nisl vel massa luctus sagittis. Cras volutpat vel diam nec ultricies.
|
KlishGroup/prose-pogs
|
pogs/S/STLHLHX/JE7B/index.md
|
Markdown
|
mit
| 2,249
|
#region Copyright (c) 2002-2005, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net)
/*
Copyright (c) 2002-2005, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the names of Bas Geertsema or Xih Solutions nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE. */
#endregion
using System;
using System.Runtime.Serialization;
using XihSolutions.DotMSN.Core;
using XihSolutions.DotMSN.DataTransfer;
namespace XihSolutions.DotMSN
{
/// <summary>
/// Specifies an exception when a connection is setup.
/// </summary>
[Serializable()]
public class ConnectivityException : DotMSNException
{
/// <summary>
/// Basic constructor.
/// </summary>
public ConnectivityException()
{
}
/// <summary>
/// Specifies a ConnectivityException.
/// </summary>
/// <param name="message">A textual presentation of the exception message</param>
public ConnectivityException(string message)
: base(message)
{
}
/// <summary>
/// Specifies a ConnectivityException which originates from another exception.
/// </summary>
/// <param name="message">A textual presentation of the exception message</param>
/// <param name="innerException">The (inner)exception which caused this exception. For example a SocketException</param>
public ConnectivityException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Serialization constructor.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected ConnectivityException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
|
mt830813/code
|
Project/WebMSN/DotMSN/ConnectivityException.cs
|
C#
|
mit
| 3,019
|
//! \file ImageGGP.cs
//! \date Sun Jun 14 09:06:26 2015
//! \brief
//
// Copyright (C) 2014-2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.ComponentModel.Composition;
using System.IO;
using GameRes.Utility;
namespace GameRes.Formats.Ikura
{
internal class GgpMetaData : ImageMetaData
{
public byte[] Key = new byte[8];
public uint Offset;
public uint Length;
}
[Export(typeof(ImageFormat))]
public class GgpFormat : PngFormat
{
public override string Tag { get { return "GGP"; } }
public override string Description { get { return "Digital Romance System encrypted image format"; } }
public override uint Signature { get { return 0x46504747u; } } // 'GGPF'
public override bool CanWrite { get { return false; } }
public GgpFormat ()
{
Extensions = new string[] { "ggp", "gg" };
}
public override ImageMetaData ReadMetaData (IBinaryStream stream)
{
var header = stream.ReadHeader (0x24);
if (!header.AsciiEqual ("GGPFAIKE"))
return null;
var info = new GgpMetaData
{
Offset = header.ToUInt32 (0x14),
Length = header.ToUInt32 (0x18),
};
for (int i = 0; i < 8; ++i)
info.Key[i] = (byte)(header[i] ^ header[i+0xC]);
stream.Position = info.Offset;
using (var enc = new EncryptedStream (stream.AsStream, info.Key, true))
using (var png = new BinaryStream (enc, stream.Name))
{
var png_info = base.ReadMetaData (png);
info.Width = png_info.Width;
info.Height = png_info.Height;
info.BPP = png_info.BPP;
info.OffsetX = png_info.OffsetX;
info.OffsetY = png_info.OffsetY;
return info;
}
}
public override ImageData Read (IBinaryStream file, ImageMetaData info)
{
var meta = (GgpMetaData)info;
using (var input = new StreamRegion (file.AsStream, meta.Offset, meta.Length, true))
using (var enc = new EncryptedStream (input, meta.Key))
using (var png = new BinaryStream (enc, file.Name))
return base.Read (png, info);
}
public override void Write (Stream file, ImageData image)
{
throw new NotImplementedException ("GgpFormat.Write not implemented");
}
}
internal class EncryptedStream : InputProxyStream
{
private byte[] m_key;
private long m_position;
public EncryptedStream (Stream main, byte[] key, bool leave_open = false)
: base (main, leave_open)
{
if (null == key)
throw new ArgumentNullException ("key");
if (key.Length < 8)
throw new ArgumentException ("key");
m_key = key;
m_position = 0;
}
public override bool CanSeek { get { return false; } }
public override long Length { get { throw new NotSupportedException(); } }
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override long Seek (long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override int Read (byte[] buffer, int offset, int count)
{
int read = BaseStream.Read (buffer, offset, count);
if (read > 0)
{
for (int i = 0; i < read; ++i)
{
buffer[offset+i] ^= m_key[m_position++ & 7];
}
}
return read;
}
public override int ReadByte ()
{
int b = BaseStream.ReadByte();
if (-1 != b)
{
b ^= m_key[m_position++ & 7];
}
return b;
}
}
}
|
morkt/GARbro
|
ArcFormats/Ikura/ImageGGP.cs
|
C#
|
mit
| 5,214
|
const removeMigratorDir = require('./removeMigratorDir');
module.exports = ({migrator}) => {
return Promise.resolve()
.then(() => migrator.disconnect())
.then(() => removeMigratorDir(migrator))
.then(() => migrator);
};
|
okv/east
|
testUtils/destroyMigrator.js
|
JavaScript
|
mit
| 228
|
<?php
/**
* This file is part of the OpenTrans php library
*
* (c) Sven Eisenschmidt <sven.eisenschmidt@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Doctrine\Common\Annotations\AnnotationRegistry;
call_user_func(function() {
if ( ! is_file($autoloadFile = __DIR__.'/../vendor/autoload.php')) {
throw new \RuntimeException('Did not find vendor/autoload.php. Did you run "composer install --dev"?');
}
$loader = require $autoloadFile;
AnnotationRegistry::registerLoader('class_exists');
});
|
sveneisenschmidt/opentrans
|
tests/bootstrap.php
|
PHP
|
mit
| 622
|
'use strict'
module.exports = function () {
this.When(/^preencher as características do produto$/, {timeout: 60 * 1000}, function (callback) {
})
this.When(/^selecionar alguma categoria$/, {timeout: 60 * 1000}, function (callback) {
})
this.Then(/^devo visualizar o campo de foto do produto$/, {timeout: 60 * 1000}, function (callback) {
})
}
|
leonardosal/cucumber-gotostep
|
example/step_definitions/sample_steps.js
|
JavaScript
|
mit
| 362
|
package de.saarland.hamming;
import de.saarland.util.Logger;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @author Almer Bolatov
* Date: 11/13/13
* Time: 9:10 PM
*/
public class TestHammingDistanceSimple extends TestCase {
private static final String TAG = TestHammingDistanceSimple.class.getSimpleName();
public void test0() {
Logger.log(TAG, "test0()");
final int K = 1;
List<String> s = new ArrayList<>();
s.add("far"); // 0
s.add("fat"); // 1
s.add("fit"); // 2
s.add("pay"); // 3
s.add("pin"); // 4
s.add("sat"); // 5
s.add("fax"); // 6
s.add("par"); // 7
Trie t = new Trie(s);
t.buildMismatchesIndex(K);
System.out.println("START queries");
// exact matching
Set<Integer> r1 = t.search("fat", K);
assertTrue(r1.contains(0));
assertTrue(r1.contains(1)); // exact matching
assertTrue(r1.contains(2));
assertTrue(r1.contains(5));
assertTrue(r1.contains(6));
assertEquals(5, r1.size());
r1 = t.search("far", K);
assertTrue(r1.contains(0)); // far$ exact
assertTrue(r1.contains(1)); // fat$ approximate matching
assertTrue(r1.contains(6)); // fat$ approximate matching
assertTrue(r1.contains(7)); // par$ approximate matching
assertEquals(4, r1.size());
// continue on heavy path
Set<Integer> r2 = t.search("for", K);
assertTrue(r2.contains(0));
assertEquals(1, r2.size());
// type 2
Set<Integer> r3 = t.search("lit", K);
assertTrue(r3.contains(2));
assertEquals(1, r3.size());
Set<Integer> r4 = t.search("pax", K);
assertTrue(r4.contains(3));
assertTrue(r4.contains(6));
assertTrue(r4.contains(7));
assertEquals(3, r4.size());
Set<Integer> r5 = t.search("pan", K);
assertTrue(r5.contains(7));
assertTrue(r5.contains(3));
assertTrue(r5.contains(4));
assertEquals(3, r5.size());
Set<Integer> r6 = t.search("faz", K);
assertTrue(r6.contains(1));
assertTrue(r6.contains(0));
assertTrue(r6.contains(6));
assertEquals(3, r6.size());
Set<Integer> r7 = t.search("zar", K);
assertTrue(r7.contains(0));
assertTrue(r7.contains(7));
assertEquals(2, r7.size());
Set<Integer> r8 = t.search("zat", K);
assertTrue(r8.contains(1));
assertTrue(r8.contains(5));
assertEquals(2, r8.size());
assertTrue(true);
}
public void test1() {
final int K = 2;
List<String> s = new ArrayList<>();
s.add("far"); // 0
s.add("fat"); // 1
s.add("fit"); // 2
s.add("pay"); // 3
s.add("pin"); // 4
s.add("sat"); // 5
s.add("fax"); // 6
s.add("par"); // 7
Trie t = new Trie(s);
t.buildMismatchesIndex(K);
System.out.println("START queries");
Set<Integer> r0 = t.search("fXX", K);
assertEquals(4, r0.size());
assertTrue(r0.contains(0));
assertTrue(r0.contains(1));
assertTrue(r0.contains(2));
assertTrue(r0.contains(6));
r0 = t.search("Xar", K);
assertEquals(6, r0.size());
assertTrue(r0.contains(0)); // far
assertTrue(r0.contains(1)); // fat
assertTrue(r0.contains(3)); // pay .
assertTrue(r0.contains(5)); // sat
assertTrue(r0.contains(6)); // fax .
assertTrue(r0.contains(7)); // par
r0 = t.search("XXX", K);
assertEquals(0, r0.size());
r0 = t.search("XXr", K);
assertTrue(r0.contains(0));
assertTrue(r0.contains(7));
assertEquals(2, r0.size());
r0 = t.search("XiX", K);
assertTrue(r0.contains(2));
assertTrue(r0.contains(4));
assertEquals(2, r0.size());
r0 = t.search("X", K);
assertEquals(0, r0.size());
r0 = t.search("s", K);
assertEquals(0, r0.size());
r0 = t.search("p", K);
assertEquals(0, r0.size());
r0 = t.search("f", K);
assertEquals(0, r0.size());
r0 = t.search("XXx", K);
assertTrue(r0.contains(6));
assertEquals(1, r0.size());
r0 = t.search("XXt", K);
assertTrue(r0.contains(1));
assertTrue(r0.contains(2));
assertTrue(r0.contains(5));
assertEquals(3, r0.size());
r0 = t.search("faX", K-1);
assertTrue(r0.contains(0));
assertTrue(r0.contains(1));
assertTrue(r0.contains(6));
assertEquals(3, r0.size());
assertTrue(true);
}
}
|
bolatov/string-matching
|
test/de/saarland/hamming/TestHammingDistanceSimple.java
|
Java
|
mit
| 4,140
|
version https://git-lfs.github.com/spec/v1
oid sha256:b0478c6949985585d1cbadad447cd75680baa15e4f0fab56943993d2f24afe67
size 4569
|
yogeshsaroya/new-cdnjs
|
ajax/libs/minitranslate/1.0.2/minitranslate.js
|
JavaScript
|
mit
| 129
|
<?php
function themezee_get_colors_sections() {
$themezee_sections = array();
$themezee_sections[] = array("id" => "themeZee_colors_schemes",
"name" => __('Predefined Color Schemes', 'themezee_lang'));
$themezee_sections[] = array("id" => "themeZee_colors_custom",
"name" => __('Custom Colors', 'themezee_lang'));
return $themezee_sections;
}
function themezee_get_colors_settings() {
$color_styles = array(
'blue.css' => __('Blue', 'themezee_lang'),
'darkblue.css' => __('Darkblue', 'themezee_lang'),
'darkgreen.css' => __('Darkgreen', 'themezee_lang'),
'green.css' => __('Green', 'themezee_lang'),
'grey.css' => __('Grey', 'themezee_lang'),
'orange.css' => __('Orange', 'themezee_lang'),
'purple.css' => __('Purple', 'themezee_lang'),
'red.css' => __('Red', 'themezee_lang'),
'standard.css' => __('Standard', 'themezee_lang'));
$themezee_settings = array();
### COLOR SETTINGS
#######################################################################################
$themezee_settings[] = array("name" => "Set Color Scheme",
"desc" => __('Please select your color scheme here.', 'themezee_lang'),
"id" => "themeZee_stylesheet",
"std" => "standard.css",
"type" => "select",
'choices' => $color_styles,
"section" => "themeZee_colors_schemes"
);
$themezee_settings[] = array("name" => __('Active Custom Colors?', 'themezee_lang'),
"desc" => __('Check this to activate the Custom Color Function.', 'themezee_lang'),
"id" => "themeZee_color_activate",
"std" => "false",
"type" => "checkbox",
"section" => "themeZee_colors_custom");
$themezee_settings[] = array("name" => __('Color', 'themezee_lang'),
"desc" => __("Select the color of your theme here.", 'themezee_lang'),
"id" => "themeZee_colors_full",
"std" => "dd2222",
"type" => "colorpicker",
"section" => "themeZee_colors_custom");
return $themezee_settings;
}
?>
|
CodeForKids/websitesByKids
|
subdomains/thedjgamer/wp-content/themes/zeesynergie/includes/admin/options/options-colors.php
|
PHP
|
mit
| 2,089
|
## MarkdownTextView
### Rich Markdown Editing for iOS
**MarkdownTextView** is an iOS framework for adding rich Markdown editing capabilities. Support for Markdown syntax is implemented inside an easily extensible `NSTextStorage` subclass, with a `UITextView` subclass being provided for convenience.
### Screenshot
<img src='screenshot.png' width='374px'>
### Example App
Check out the includeded Example app to try out the text view and to see how **MarkdownTextView** is integrated into the project.
### Installation
###### With [CocoaPods](https://cocoapods.org/):
```ruby
pod "MarkdownTextView"
```
###### With [Carthage](https://github.com/Carthage/Carthage):
```swift
github "indragiek/MarkdownTextView"
```
### Getting Started
The simplest possible usage is as follows:
```swift
let textView = MarkdownTextView(frame: CGRectZero)
view.addSubview(textView)
```
This gives you a text view with support for most of the features defined in the original Markdown implementation (strong, emphasis, inline code, code blocks, block quotes, headers) with the default styling provided by the framework.
### Customizing Appearance
All of the styling can be customized using standard `NSAttributedString` attributes. For example, if you wanted to customize bold text such that it appeared red, you would do this:
```swift
var attributes = MarkdownTextAttributes()
attributes.strongAttributes = [
NSForegroundColorAttributeName: UIColor.redColor()
]
let textStorage = MarkdownTextStorage(attributes: attributes)
let textView = MarkdownTextView(frame: CGRectZero, textStorage: textStorage)
view.addSubview(textView)
```
### Extensions Support
Extension classes conforming to the `HighlighterType` protocol can be used to add support for unofficial Markdown extensions. The framework comes with the following extensions already implemented:
From [Github Flavored Markdown](https://help.github.com/articles/github-flavored-markdown/):
* `MarkdownStrikethroughHighlighter` - Support for `~~strikethrough~~`
* `MarkdownFencedCodeHighlighter` - Support for fenced code blocks
* `LinkHighlighter` - Support for auto-linking
Other:
* `MarkdownSuperscriptHighlighter` - Support for `super^scripted^text`
These extensions do not come activated by default. They must manually be added to an instance of `MarkdownTextStorage` as follows:
```swift
let textStorage = MarkdownTextStorage()
var error: NSError?
if let linkHighlighter = LinkHighlighter(errorPtr: &error) {
textStorage.addHighlighter(linkHighlighter)
} else {
assertionFailure("Error initializing LinkHighlighter: \(error)")
}
textStorage.addHighlighter(MarkdownStrikethroughHighlighter())
textStorage.addHighlighter(MarkdownSuperscriptHighlighter())
if let codeBlockAttributes = attributes.codeBlockAttributes {
textStorage.addHighlighter(MarkdownFencedCodeHighlighter(attributes: codeBlockAttributes))
}
let textView = MarkdownTextView(frame: CGRectZero, textStorage: textStorage)
view.addSubview(textView)
```
### Credits
* John Gruber's [original Markdown implementation](http://daringfireball.net/projects/markdown/) for most of the regular expressions used in this project.
* [RFMarkdownTextView](https://github.com/ruddfawcett/RFMarkdownTextView) for the idea to implement this as an `NSTextStorage` subclass
### Contact
* Indragie Karunaratne
* [@indragie](http://twitter.com/indragie)
* [http://indragie.com](http://indragie.com)
### License
MarkdownTextView is licensed under the MIT License. See `LICENSE` for more information.
|
indragiek/MarkdownTextView
|
README.md
|
Markdown
|
mit
| 3,526
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/><!-- using block title in layout.dt--><!-- using block ddox.defs in ddox.layout.dt--><!-- using block ddox.title in ddox.layout.dt-->
<title>Module graphics.shaders.glsl.directionallight</title>
<link rel="stylesheet" type="text/css" href="../../../styles/ddox.css"/>
<link rel="stylesheet" href="../../../prettify/prettify.css" type="text/css"/>
<script type="text/javascript" src="../../../scripts/jquery.js">/**/</script>
<script type="text/javascript" src="../../../prettify/prettify.js">/**/</script>
<script type="text/javascript" src="../../../scripts/ddox.js">/**/</script>
</head>
<body onload="prettyPrint(); setupDdox();">
<nav id="main-nav"><!-- using block navigation in layout.dt-->
<ul class="tree-view">
<li class="collapsed tree-view">
<a href="#" class="package">components</a>
<ul class="tree-view">
<li>
<a href="../../../components/animation.html" class=" module">animation</a>
</li>
<li>
<a href="../../../components/assets.html" class=" module">assets</a>
</li>
<li>
<a href="../../../components/camera.html" class=" module">camera</a>
</li>
<li>
<a href="../../../components/component.html" class=" module">component</a>
</li>
<li>
<a href="../../../components/lights.html" class=" module">lights</a>
</li>
<li>
<a href="../../../components/material.html" class=" module">material</a>
</li>
<li>
<a href="../../../components/mesh.html" class=" module">mesh</a>
</li>
<li>
<a href="../../../components/userinterface.html" class=" module">userinterface</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">core</a>
<ul class="tree-view">
<li>
<a href="../../../core/dgame.html" class=" module">dgame</a>
</li>
<li>
<a href="../../../core/gameobject.html" class=" module">gameobject</a>
</li>
<li>
<a href="../../../core/prefabs.html" class=" module">prefabs</a>
</li>
<li>
<a href="../../../core/properties.html" class=" module">properties</a>
</li>
<li>
<a href="../../../core/reflection.html" class=" module">reflection</a>
</li>
<li>
<a href="../../../core/scene.html" class=" module">scene</a>
</li>
</ul>
</li>
<li class=" tree-view">
<a href="#" class="package">graphics</a>
<ul class="tree-view">
<li class="collapsed tree-view">
<a href="#" class="package">adapters</a>
<ul class="tree-view">
<li>
<a href="../../../graphics/adapters/adapter.html" class=" module">adapter</a>
</li>
<li>
<a href="../../../graphics/adapters/linux.html" class=" module">linux</a>
</li>
<li>
<a href="../../../graphics/adapters/mac.html" class=" module">mac</a>
</li>
<li>
<a href="../../../graphics/adapters/win32.html" class=" module">win32</a>
</li>
</ul>
</li>
<li class=" tree-view">
<a href="#" class="package">shaders</a>
<ul class="tree-view">
<li class=" tree-view">
<a href="#" class="package">glsl</a>
<ul class="tree-view">
<li>
<a href="../../../graphics/shaders/glsl/ambientlight.html" class=" module">ambientlight</a>
</li>
<li>
<a href="../../../graphics/shaders/glsl/animatedgeometry.html" class=" module">animatedgeometry</a>
</li>
<li>
<a href="../../../graphics/shaders/glsl/directionallight.html" class="selected module">directionallight</a>
</li>
<li>
<a href="../../../graphics/shaders/glsl/geometry.html" class=" module">geometry</a>
</li>
<li>
<a href="../../../graphics/shaders/glsl/pointlight.html" class=" module">pointlight</a>
</li>
<li>
<a href="../../../graphics/shaders/glsl/shadowmap.html" class=" module">shadowmap</a>
</li>
<li>
<a href="../../../graphics/shaders/glsl/userinterface.html" class=" module">userinterface</a>
</li>
</ul>
</li>
<li>
<a href="../../../graphics/shaders/glsl.html" class=" module">glsl</a>
</li>
<li>
<a href="../../../graphics/shaders/shaders.html" class=" module">shaders</a>
</li>
</ul>
</li>
<li>
<a href="../../../graphics/adapters.html" class=" module">adapters</a>
</li>
<li>
<a href="../../../graphics/graphics.html" class=" module">graphics</a>
</li>
<li>
<a href="../../../graphics/shaders.html" class=" module">shaders</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">utility</a>
<ul class="tree-view">
<li>
<a href="../../../utility/awesomium.html" class=" module">awesomium</a>
</li>
<li>
<a href="../../../utility/concurrency.html" class=" module">concurrency</a>
</li>
<li>
<a href="../../../utility/config.html" class=" module">config</a>
</li>
<li>
<a href="../../../utility/filepath.html" class=" module">filepath</a>
</li>
<li>
<a href="../../../utility/input.html" class=" module">input</a>
</li>
<li>
<a href="../../../utility/output.html" class=" module">output</a>
</li>
<li>
<a href="../../../utility/resources.html" class=" module">resources</a>
</li>
<li>
<a href="../../../utility/string.html" class=" module">string</a>
</li>
<li>
<a href="../../../utility/tasks.html" class=" module">tasks</a>
</li>
<li>
<a href="../../../utility/time.html" class=" module">time</a>
</li>
</ul>
</li>
<li>
<a href="../../../components.html" class=" module">components</a>
</li>
<li>
<a href="../../../core.html" class=" module">core</a>
</li>
<li>
<a href="../../../graphics.html" class=" module">graphics</a>
</li>
<li>
<a href="../../../utility.html" class=" module">utility</a>
</li>
</ul>
<noscript>
<p style="color: red">The search functionality needs JavaScript enabled</p>
</noscript>
<div id="symbolSearchPane" style="display: none">
<p>
<input id="symbolSearch" type="text" placeholder="Search for symbols" onchange="performSymbolSearch(24);" onkeypress="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"/>
</p>
<ul id="symbolSearchResults" style="display: none"></ul>
<script type="application/javascript" src="../../../symbols.js"></script>
<script type="application/javascript">
//<![CDATA[
var symbolSearchRootDir = "../../../"; $('#symbolSearchPane').show();
//]]>
</script>
</div>
</nav>
<div id="main-contents">
<h1>Module graphics.shaders.glsl.directionallight</h1><!-- using block body in layout.dt--><!-- using block ddox.description in ddox.layout.dt-->
<p> Lighting pass shader for Directional Lights
</p>
<!-- using block ddox.sections in ddox.layout.dt-->
<section></section><!-- using block ddox.members in ddox.layout.dt-->
<section>
<h2>Authors</h2><!-- using block ddox.authors in ddox.layout.dt-->
</section>
<section>
<h2>Copyright</h2><!-- using block ddox.copyright in ddox.layout.dt-->
</section>
<section>
<h2>License</h2><!-- using block ddox.license in ddox.layout.dt-->
</section>
</div>
</body>
</html>
|
Circular-Studios/Dash-Docs
|
api/v0.9.0/graphics/shaders/glsl/directionallight.html
|
HTML
|
mit
| 7,799
|
---
layout: page
title: Pearl Software Executive Retreat
date: 2016-05-24
author: Stephanie Barrera
tags: weekly links, java
status: published
summary: Maecenas quam purus, elementum ac gravida a, pulvinar eget.
banner: images/banner/office-01.jpg
booking:
startDate: 02/14/2018
endDate: 02/15/2018
ctyhocn: MKLHSHX
groupCode: PSER
published: true
---
Etiam id eros eros. Cras eleifend ipsum orci, in mattis diam tempor et. Donec pellentesque posuere imperdiet. Nullam sed risus varius, scelerisque lectus a, commodo turpis. Maecenas aliquet suscipit nunc ac elementum. Nulla ultricies efficitur tortor sed facilisis. Vestibulum tincidunt scelerisque massa, et luctus sapien semper a. Suspendisse potenti. Morbi ligula ex, dapibus eu accumsan quis, condimentum vel sem. Proin eget neque non ex fermentum tristique. Aliquam sed elit lobortis, tempor enim quis, convallis tellus.
1 Duis eget massa consequat, placerat justo nec, auctor turpis
1 Nulla non sem tempus, sollicitudin ligula quis, condimentum mauris.
Mauris turpis libero, egestas sed condimentum laoreet, dignissim sed enim. Donec sit amet mauris tempus, commodo mauris in, condimentum orci. Aliquam erat volutpat. Sed eget rhoncus dui. Sed vitae purus mi. Aliquam iaculis augue ut semper sollicitudin. Aliquam eleifend iaculis efficitur. Cras augue mauris, accumsan vitae tincidunt sit amet, imperdiet ut urna. Donec lacinia scelerisque erat at elementum. Maecenas in sem eu diam eleifend mollis at nec felis. Sed porta non ante ac aliquam. Pellentesque mollis iaculis mattis.
Donec consequat quam vel tincidunt luctus. Mauris eget mauris magna. Nulla suscipit auctor congue. Cras risus urna, porta quis lectus sed, commodo auctor ex. Proin dolor libero, posuere eget feugiat quis, pharetra nec leo. Nullam sit amet ultrices turpis, a maximus nulla. Duis vestibulum, ante non bibendum auctor, erat lorem euismod leo, et aliquam ante ante at ante.
|
KlishGroup/prose-pogs
|
pogs/M/MKLHSHX/PSER/index.md
|
Markdown
|
mit
| 1,919
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>schroeder: 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.10.0 / schroeder - 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>
schroeder
<small>
8.9.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2021-11-03 02:25:39 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-11-03 02:25:39 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
coq 8.10.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.08.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.08.1 Official release 4.08.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/schroeder"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Schroeder"]
depends: [
"ocaml"
"coq" {>= "8.9" & < "8.10~"}
]
tags: [
"keyword: Schroeder-Bernstein"
"keyword: set theory"
"category: Mathematics/Logic/Set theory"
]
authors: [
"Hugo herbelin"
]
bug-reports: "https://github.com/coq-contribs/schroeder/issues"
dev-repo: "git+https://github.com/coq-contribs/schroeder.git"
synopsis: "The Theorem of Schroeder-Bernstein"
description: """
Fraenkel's proof of Schroeder-Bernstein theorem on decidable sets
is formalized in a constructive variant of set theory based on
stratified universes (the one defined in the Ensemble library).
The informal proof can be found for instance in "Axiomatic Set Theory"
from P. Suppes."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/schroeder/archive/v8.9.0.tar.gz"
checksum: "md5=df101200f9232b0135b7ee345705e6ef"
}
</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-schroeder.8.9.0 coq.8.10.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.10.0).
The following dependencies couldn't be met:
- coq-schroeder -> coq < 8.10~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
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-schroeder.8.9.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://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</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>
|
coq-bench/coq-bench.github.io
|
clean/Linux-x86_64-4.08.1-2.0.5/released/8.10.0/schroeder/8.9.0.html
|
HTML
|
mit
| 6,995
|
/*!
Grape JavaScript game engine
(c) 2012-<%= grunt.template.today('yyyy') %> Zoltan Mihalyi.
https://github.com/zoltan-mihalyi/grape/blob/master/MIT-LICENSE.txt
*/
|
zoltan-mihalyi/grape
|
js/grape/banner.js
|
JavaScript
|
mit
| 168
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
def function():
return "pineapple"
def function2():
return "tractor"
class Class(object):
def method(self):
return "parrot"
class AboutMethodBindings(Koan):
def test_methods_are_bound_to_an_object(self):
obj = Class()
self.assertEqual(True, obj.method.im_self == obj)
def test_methods_are_also_bound_to_a_function(self):
obj = Class()
self.assertEqual('parrot', obj.method())
self.assertEqual('parrot', obj.method.im_func(obj))
def test_functions_have_attributes(self):
self.assertEqual(31, len(dir(function)))
self.assertEqual(True, dir(function) == dir(Class.method.im_func))
def test_bound_methods_have_different_attributes(self):
obj = Class()
self.assertEqual(23, len(dir(obj.method)))
def test_setting_attributes_on_an_unbound_function(self):
function.cherries = 3
self.assertEqual(3, function.cherries)
def test_setting_attributes_on_a_bound_method_directly(self):
obj = Class()
try:
obj.method.cherries = 3
except AttributeError as ex:
self.assertMatch('object has no attribute', ex[0])
def test_setting_attributes_on_methods_by_accessing_the_inner_function(self):
obj = Class()
obj.method.im_func.cherries = 3
self.assertEqual(3, obj.method.cherries)
def test_functions_can_have_inner_functions(self):
function2.get_fruit = function
self.assertEqual('pineapple', function2.get_fruit())
def test_inner_functions_are_unbound(self):
function2.get_fruit = function
try:
cls = function2.get_fruit.im_self
except AttributeError as ex:
self.assertMatch('object has no attribute', ex[0])
# ------------------------------------------------------------------
class BoundClass(object):
def __get__(self, obj, cls):
return (self, obj, cls)
binding = BoundClass()
def test_get_descriptor_resolves_attribute_binding(self):
bound_obj, binding_owner, owner_type = self.binding
# Look at BoundClass.__get__():
# bound_obj = self
# binding_owner = obj
# owner_type = cls
self.assertEqual('BoundClass', bound_obj.__class__.__name__)
self.assertEqual('AboutMethodBindings', binding_owner.__class__.__name__)
self.assertEqual(AboutMethodBindings, owner_type)
# ------------------------------------------------------------------
class SuperColor(object):
def __init__(self):
self.choice = None
def __set__(self, obj, val):
self.choice = val
color = SuperColor()
def test_set_descriptor_changes_behavior_of_attribute_assignment(self):
self.assertEqual(None, self.color.choice)
self.color = 'purple'
self.assertEqual('purple', self.color.choice)
|
jpvantuyl/python_koans
|
python2/koans/about_method_bindings.py
|
Python
|
mit
| 2,996
|
<?php
use Legionth\React\Http\LengthLimitedStream;
use React\Stream\ReadableStream;
class LengthLimitedStreamTest extends TestCase
{
private $input;
public function setUp()
{
$loop = $this->getMockBuilder('React\EventLoop\LoopInterface')
->getMock();
$this->input = new \React\Stream\ReadableResourceStream(
fopen('php://temp', 'r+'),
$loop
);
}
public function testSimpleChunk()
{
$stream = new LengthLimitedStream($this->input, 5);
$stream->on('data', $this->expectCallableOnceWith('hello'));
$stream->on('end', $this->expectCallableOnce());
$this->input->emit('data', array("hello world"));
}
public function testInputStreamKeepsEmitting()
{
$stream = new LengthLimitedStream($this->input, 5);
$stream->on('data', $this->expectCallableOnceWith('hello'));
$stream->on('end', $this->expectCallableOnce());
$this->input->emit('data', array("hello world"));
$this->input->emit('data', array("world"));
$this->input->emit('data', array("world"));
}
public function testZeroLengthInContentLengthWillIgnoreEmittedDataEvents()
{
$stream = new LengthLimitedStream($this->input, 0);
$stream->on('data', $this->expectCallableNever());
$stream->on('end', $this->expectCallableOnce());
$this->input->emit('data', array("hello world"));
}
public function testHandleError()
{
$stream = new LengthLimitedStream($this->input, 0);
$stream->on('error', $this->expectCallableOnce());
$stream->on('close', $this->expectCallableOnce());
$this->input->emit('error', array(new \RuntimeException()));
$this->assertFalse($stream->isReadable());
}
public function testPauseStream()
{
$input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')
->getMock();
$input->expects($this->once())->method('pause');
$stream = new LengthLimitedStream($input, 0);
$stream->pause();
}
public function testResumeStream()
{
$input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')
->getMock();
$input->expects($this->once())->method('pause');
$stream = new LengthLimitedStream($input, 0);
$stream->pause();
$stream->resume();
}
public function testPipeStream()
{
$stream = new LengthLimitedStream($this->input, 0);
$dest = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock();
$ret = $stream->pipe($dest);
$this->assertSame($dest, $ret);
}
public function testHandleClose()
{
$stream = new LengthLimitedStream($this->input, 0);
$stream->on('close', $this->expectCallableOnce());
$this->input->close();
$this->input->emit('end', array());
$this->assertFalse($stream->isReadable());
}
public function testOutputStreamCanCloseInputStream()
{
$this->input->on('close', $this->expectCallableOnce());
$stream = new LengthLimitedStream($this->input, 0);
$stream->on('close', $this->expectCallableOnce());
$stream->close();
$this->assertFalse($this->input->isReadable());
}
public function testHandleUnexpectedEnd()
{
$stream = new LengthLimitedStream($this->input, 5);
$stream->on('data', $this->expectCallableNever());
$stream->on('close', $this->expectCallableOnce());
$stream->on('end', $this->expectCallableNever());
$stream->on('error', $this->expectCallableOnce());
$this->input->emit('end');
}
}
|
legionth/php-http-client-react
|
tests/LengthLimitedStreamTest.php
|
PHP
|
mit
| 3,735
|
/* ==================================================================
AngularJS Datatype Editor - Stock Price
A directive to see and edit a price of a stock in place.
Usage:
<div ade-stock ade-id='1234' adeProvider="yahoo" ade-class="myClass" ng-model="data"></div>
Config:
ade-id:
If this id is set, it will be used in messages broadcast to the app on state changes.
ade-class:
A custom class to give to the input
ade-readonly:
If you don't want the stock ticker to be editable
ade-provider:
By default, stock prices provided by google API. This could be set to yahoo.
Messages:
name: ADE-start
data: id from config
name: ADE-finish
data: {id from config, old value, new value, exit value}
------------------------------------------------------------------*/
angular.module('ADE').directive('adeStock', ['ADE', '$compile', '$filter', '$http',
function(ADE, $compile, $filter, $http) {
return {
require: '?ngModel', //optional dependency for ngModel
restrict: 'A', //Attribute declaration eg: <div ade-url=""></div>
scope: {
adeUrl: "@",
adeId: "@",
adeClass: "@",
adeReadonly: "@",
adeProvider: "@",
adeMovement: "@",
ngModel: "="
},
//The link step (after compile)
link: function(scope, element, attrs) {
var editing = false;
var input = null;
var invisibleInput = null;
var exit = 0; //0=click, 1=tab, -1= shift tab, 2=return, -2=shift return, 3=esc. controls if you exited the field so you can focus the next field if appropriate
var readonly = false;
var inputClass = "";
var stopObserving = null;
var adeId = scope.adeId;
var cache = {};
if(scope.adeClass!==undefined) inputClass = scope.adeClass;
if(scope.adeReadonly!==undefined && scope.adeReadonly=="1") readonly = true;
var makeHTML = function() {
var url, request, html = "";
var value = scope.ngModel;
var cssClasses = "ade-stock-price";
var timestamp = new Date().getTime();
var cache = JSON.parse(localStorage.getItem("adeCache") || "{}");
if (value!==undefined && value!=="") {
if(angular.isArray(value)) value = value[0];
if(value===null || value===undefined) value="";
if(!angular.isString(value)) value = value.toString();
if (scope.adeMovement === "0") {
cssClasses += " ade-stock-price-only";
}
if (scope.adeMovement === "2") {
cssClasses += " ade-stock-popup";
}
element.html("<p class='"+ cssClasses +"'><b>"+ encodeURIComponent(value).toUpperCase() + "</b></p>");
if (cache && cache[value] && cache[value].expires > timestamp) {
handleSuccess(null, cache[value]);
return;
}
if (scope.adeProvider === 'yahoo') {
url = "https://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quotes where " +
"symbol in (\""+ value +"\")&format=json&env=http://datatables.org/alltables.env";
request = $http.get(url);
} else {
url = "http://www.google.com/finance/info?q="+value+"&callback=JSON_CALLBACK";
request = $http.jsonp(url);
}
return( request.then( handleSuccess, handleError ) );
} else {
return element.html("");
}
};
;
var handleError = function(data) {
element.find('.ade-stock-price').append("<span class='ade-stock-no-data'>no price available</span></p>");
};
var handleSuccess = function(resp, cachedPrice) {
var arrowIcon = '<svg xmlns="http://www.w3.org/2000/svg" class="ade-stock-arrow" fill="#000000" ' +
'height="24" viewBox="0 0 24 24" width="24"><path d="M20 12l-1.41-1.41L13 16.17V4h-2v12.17' +
'l-5.58-5.59L4 12l8 8 8-8z" class="ade-arrow-down" /><path ' +
'd="M4 12l1.41 1.41L11 7.83V20h2V7.83l5.58 5.59L20 12 l-8-8-8 8z" class="ade-arrow-up"/></svg>';
var adeCache = JSON.parse(localStorage.getItem("adeCache") || "{}");
var $stockEl = element.find(".ade-stock-price"), period = 900000,
change = "", price = "", ticker = "", quote = "";
if (resp) {
if (scope.adeProvider === 'yahoo') {
if (resp.data.query.results === null) {
handleError();
return;
}
quote = resp.data.query.results.quote;
change = quote.Change;
price = quote.LastTradePriceOnly;
ticker = quote.Symbol;
if (price === null) {
handleError();
return;
}
} else {
change = resp.data[0].c;
price = resp.data[0].l_cur;
ticker = resp.data[0].t;
}
//save to localStorage
adeCache[ticker] = {
"expires": new Date().getTime() + period,
"price": price,
"change": change
};
localStorage.setItem("adeCache", JSON.stringify(adeCache));
} else {
//cached data displayed;
price = cachedPrice.price;
change = cachedPrice.change;
}
$stockEl.append(" " + price + '<span class="ade-price-movement">' + arrowIcon +
' <span>$' + change.substring(1) + '</span></span></p>');
if ($stockEl.hasClass("ade-stock-popup")) {
var $movementEl = $stockEl.find(".ade-price-movement");
$movementEl.addClass("ade-popup").addClass("dropdown-menu");
$stockEl.on("mouseenter", function() {
$movementEl.addClass("open");
}).on("mouseleave", function() {
$movementEl.removeClass("open");
});
}
if (change.indexOf("+") !== -1) {
// stock up
element.addClass("ade-stock-up").removeClass("ade-stock-down");
} else if (change.indexOf("-") !== -1) {
element.addClass("ade-stock-down").removeClass("ade-stock-up");
}
};
//called once the edit is done, so we can save the new data and remove edit mode
var saveEdit = function(exited) {
var oldValue = scope.ngModel;
exit = exited;
if (exit !== 3) {
//don't save value on esc
if (input) {
scope.ngModel = input.val();
}
}
element.show();
destroy();
editing = false;
ADE.done(adeId, oldValue, scope.ngModel, exit);
ADE.teardownBlur(input);
ADE.teardownKeys(input);
if(invisibleInput) {
invisibleInput.off('blur.ADE');
ADE.teardownKeys(invisibleInput);
}
};
//place the popup in the proper place on the screen
var place = function() {
ADE.place('.'+ADE.popupClass,element,0,-5);
};
var clickHandler = function(e) {
if (editing) return;
editing = true;
adeId = scope.adeId;
ADE.begin(adeId);
var value = (typeof scope.ngModel === "undefined") ? "" : scope.ngModel;
element.hide();
$compile('<input type="text" class="ade-input '+inputClass+'" value="'+value+'" />')(scope).insertAfter(element);
input = element.next('input');
input.focus();
//put cursor at end
input[0].selectionStart = input[0].selectionEnd = input.val().length;
ADE.setupBlur(input,saveEdit,scope);
ADE.setupKeys(input,saveEdit,false,scope);
};
//setup events
if(!readonly) {
element.on('click.ADE', function(e) {
scope.$apply(function() {
clickHandler(e);
});
});
}
//A callback to observe for changes to the id and save edit
//The model will still be connected, so it is safe, but don't want to cause problems
var observeID = function(value) {
//this gets called even when the value hasn't changed,
//so we need to check for changes ourselves
if(editing && adeId!==value) saveEdit(3);
else if(adeId!==value) ADE.hidePopup(element);
};
//If ID changes during edit, something bad happened. No longer editing the right thing. Cancel
stopObserving = attrs.$observe('adeId', observeID);
var destroy = function() {
ADE.teardownScrollEvents(element);
ADE.hidePopup(element);
ADE.teardownBlur();
if(input) {
input.off();
input.remove();
}
$(document).off('ADE_hidepops.ADE');
};
scope.$on('$destroy', function() { //need to clean up the event watchers when the scope is destroyed
destroy();
if(element) element.off('.ADE');
if(stopObserving && stopObserving!=observeID) { //Angualar <=1.2 returns callback, not deregister fn
stopObserving();
stopObserving = null;
} else {
delete attrs.$$observers['adeId'];
}
});
//need to watch the model for changes
scope.$watch(function(scope) {
return scope.ngModel;
}, function () {
makeHTML();
});
}
};
}]);
|
Toodledo/ADE
|
app/stock/stock_directive.js
|
JavaScript
|
mit
| 8,322
|
/*!
* heap.js - example.js
* Author: dead_horse <dead_horse@qq.com>
*/
/**
* Module dependencies.
*/
var heaps = require('./');
var bHeap = heaps.binaryHeap(function (a, b) {
return a.value - b.value;
});
for (var i = 0; i < 10; i++) {
bHeap.push({
value: Math.random()
});
}
var result = [];
while(!bHeap.empty()) {
result.push(bHeap.pop());
}
console.log('%j', result);
|
dead-horse/heap.js
|
example.js
|
JavaScript
|
mit
| 395
|
#include <stdint.h>
void wrReg(uint8_t reg,uint8_t dat);
uint8_t rdReg(uint8_t reg);
#define vga 0
#define qvga 1
#define qqvga 2
#define yuv422 0
#define rgb565 1
#define bayerRGB 2
struct regval_list{
uint8_t reg_num;
uint16_t value;
};
void setColor(uint8_t color);
void setRes(uint8_t res);
void camInit(void);
#define camAddr_WR 0x42
#define camAddr_RD 0x43
/* Registers */
#define REG_GAIN 0x00 /* Gain lower 8 bits (rest in vref) */
#define REG_BLUE 0x01 /* blue gain */
#define REG_RED 0x02 /* red gain */
#define REG_VREF 0x03 /* Pieces of GAIN, VSTART, VSTOP */
#define REG_COM1 0x04 /* Control 1 */
#define COM1_CCIR656 0x40/* CCIR656 enable */
#define REG_BAVE 0x05 /* U/B Average level */
#define REG_GbAVE 0x06 /* Y/Gb Average level */
#define REG_AECHH 0x07 /* AEC MS 5 bits */
#define REG_RAVE 0x08 /* V/R Average level */
#define REG_COM2 0x09 /* Control 2 */
#define COM2_SSLEEP 0x10 /* Soft sleep mode */
#define REG_PID 0x0a /* Product ID MSB */
#define REG_VER 0x0b /* Product ID LSB */
#define REG_COM3 0x0c /* Control 3 */
#define COM3_SWAP 0x40 /* Byte swap */
#define COM3_SCALEEN 0x08 /* Enable scaling */
#define COM3_DCWEN 0x04 /* Enable downsamp/crop/window */
#define REG_COM4 0x0d /* Control 4 */
#define REG_COM5 0x0e /* All "reserved" */
#define REG_COM6 0x0f /* Control 6 */
#define REG_AECH 0x10 /* More bits of AEC value */
#define REG_CLKRC 0x11 /* Clocl control */
#define CLK_EXT 0x40 /* Use external clock directly */
#define CLK_SCALE 0x3f /* Mask for internal clock scale */
#define REG_COM7 0x12 /* Control 7 */
#define COM7_RESET 0x80 /* Register reset */
#define COM7_FMT_MASK 0x38
#define COM7_FMT_VGA 0x00
#define COM7_FMT_CIF 0x20 /* CIF format */
#define COM7_FMT_QVGA 0x10 /* QVGA format */
#define COM7_FMT_QCIF 0x08 /* QCIF format */
#define COM7_RGB 0x04 /* bits 0 and 2 - RGB format */
#define COM7_YUV 0x00 /* YUV */
#define COM7_BAYER 0x01 /* Bayer format */
#define COM7_PBAYER 0x05 /* "Processed bayer" */
#define REG_COM8 0x13 /* Control 8 */
#define COM8_FASTAEC 0x80 /* Enable fast AGC/AEC */
#define COM8_AECSTEP 0x40 /* Unlimited AEC step size */
#define COM8_BFILT 0x20 /* Band filter enable */
#define COM8_AGC 0x04 /* Auto gain enable */
#define COM8_AWB 0x02 /* White balance enable */
#define COM8_AEC 0x01 /* Auto exposure enable */
#define REG_COM9 0x14 /* Control 9- gain ceiling */
#define REG_COM10 0x15 /* Control 10 */
#define COM10_HSYNC 0x40 /* HSYNC instead of HREF */
#define COM10_PCLK_HB 0x20 /* Suppress PCLK on horiz blank */
#define COM10_HREF_REV 0x08 /* Reverse HREF */
#define COM10_VS_LEAD 0x04 /* VSYNC on clock leading edge */
#define COM10_VS_NEG 0x02 /* VSYNC negative */
#define COM10_HS_NEG 0x01 /* HSYNC negative */
#define REG_HSTART 0x17 /* Horiz start high bits */
#define REG_HSTOP 0x18 /* Horiz stop high bits */
#define REG_VSTART 0x19 /* Vert start high bits */
#define REG_VSTOP 0x1a /* Vert stop high bits */
#define REG_PSHFT 0x1b /* Pixel delay after HREF */
#define REG_MIDH 0x1c /* Manuf. ID high */
#define REG_MIDL 0x1d /* Manuf. ID low */
#define REG_MVFP 0x1e /* Mirror / vflip */
#define MVFP_MIRROR 0x20 /* Mirror image */
#define MVFP_FLIP 0x10 /* Vertical flip */
#define REG_AEW 0x24 /* AGC upper limit */
#define REG_AEB 0x25 /* AGC lower limit */
#define REG_VPT 0x26 /* AGC/AEC fast mode op region */
#define REG_HSYST 0x30 /* HSYNC rising edge delay */
#define REG_HSYEN 0x31 /* HSYNC falling edge delay */
#define REG_HREF 0x32 /* HREF pieces */
#define REG_TSLB 0x3a /* lots of stuff */
#define TSLB_YLAST 0x04 /* UYVY or VYUY - see com13 */
#define REG_COM11 0x3b /* Control 11 */
#define COM11_NIGHT 0x80 /* NIght mode enable */
#define COM11_NMFR 0x60 /* Two bit NM frame rate */
#define COM11_HZAUTO 0x10 /* Auto detect 50/60 Hz */
#define COM11_50HZ 0x08 /* Manual 50Hz select */
#define COM11_EXP 0x02
#define REG_COM12 0x3c /* Control 12 */
#define COM12_HREF 0x80 /* HREF always */
#define REG_COM13 0x3d /* Control 13 */
#define COM13_GAMMA 0x80 /* Gamma enable */
#define COM13_UVSAT 0x40 /* UV saturation auto adjustment */
#define COM13_UVSWAP 0x01 /* V before U - w/TSLB */
#define REG_COM14 0x3e /* Control 14 */
#define COM14_DCWEN 0x10 /* DCW/PCLK-scale enable */
#define REG_EDGE 0x3f /* Edge enhancement factor */
#define REG_COM15 0x40 /* Control 15 */
#define COM15_R10F0 0x00 /* Data range 10 to F0 */
#define COM15_R01FE 0x80 /* 01 to FE */
#define COM15_R00FF 0xc0 /* 00 to FF */
#define COM15_RGB565 0x10 /* RGB565 output */
#define COM15_RGB555 0x30 /* RGB555 output */
#define REG_COM16 0x41 /* Control 16 */
#define COM16_AWBGAIN 0x08 /* AWB gain enable */
#define REG_COM17 0x42 /* Control 17 */
#define COM17_AECWIN 0xc0 /* AEC window - must match COM4 */
#define COM17_CBAR 0x08 /* DSP Color bar */
/*
* This matrix defines how the colors are generated, must be
* tweaked to adjust hue and saturation.
*
* Order: v-red, v-green, v-blue, u-red, u-green, u-blue
*
* They are nine-bit signed quantities, with the sign bit
* stored in0x58.Sign for v-red is bit 0, and up from there.
*/
#define REG_CMATRIX_BASE0x4f
#define CMATRIX_LEN 6
#define REG_CMATRIX_SIGN0x58
#define REG_BRIGHT 0x55 /* Brightness */
#define REG_CONTRAS 0x56 /* Contrast control */
#define REG_GFIX 0x69 /* Fix gain control */
#define REG_REG76 0x76 /* OV's name */
#define R76_BLKPCOR 0x80 /* Black pixel correction enable */
#define R76_WHTPCOR 0x40 /* White pixel correction enable */
#define REG_RGB444 0x8c /* RGB 444 control */
#define R444_ENABLE 0x02 /* Turn on RGB444, overrides 5x5 */
#define R444_RGBX 0x01 /* Empty nibble at end */
#define REG_HAECC1 0x9f /* Hist AEC/AGC control 1 */
#define REG_HAECC2 0xa0 /* Hist AEC/AGC control 2 */
#define REG_BD50MAX 0xa5 /* 50hz banding step limit */
#define REG_HAECC3 0xa6 /* Hist AEC/AGC control 3 */
#define REG_HAECC4 0xa7 /* Hist AEC/AGC control 4 */
#define REG_HAECC5 0xa8 /* Hist AEC/AGC control 5 */
#define REG_HAECC6 0xa9 /* Hist AEC/AGC control 6 */
#define REG_HAECC7 0xaa /* Hist AEC/AGC control 7 */
#define REG_BD60MAX 0xab /* 60hz banding step limit */
#define REG_GAIN 0x00 /* Gain lower 8 bits (rest in vref) */
#define REG_BLUE 0x01 /* blue gain */
#define REG_RED 0x02 /* red gain */
#define REG_VREF 0x03 /* Pieces of GAIN, VSTART, VSTOP */
#define REG_COM1 0x04 /* Control 1 */
#define COM1_CCIR656 0x40 /* CCIR656 enable */
#define REG_BAVE 0x05 /* U/B Average level */
#define REG_GbAVE 0x06 /* Y/Gb Average level */
#define REG_AECHH 0x07 /* AEC MS 5 bits */
#define REG_RAVE 0x08 /* V/R Average level */
#define REG_COM2 0x09 /* Control 2 */
#define COM2_SSLEEP 0x10 /* Soft sleep mode */
#define REG_PID 0x0a /* Product ID MSB */
#define REG_VER 0x0b /* Product ID LSB */
#define REG_COM3 0x0c /* Control 3 */
#define COM3_SWAP 0x40 /* Byte swap */
#define COM3_SCALEEN 0x08 /* Enable scaling */
#define COM3_DCWEN 0x04 /* Enable downsamp/crop/window */
#define REG_COM4 0x0d /* Control 4 */
#define REG_COM5 0x0e /* All "reserved" */
#define REG_COM6 0x0f /* Control 6 */
#define REG_AECH 0x10 /* More bits of AEC value */
#define REG_CLKRC 0x11 /* Clocl control */
#define CLK_EXT 0x40 /* Use external clock directly */
#define CLK_SCALE 0x3f /* Mask for internal clock scale */
#define REG_COM7 0x12 /* Control 7 */
#define COM7_RESET 0x80 /* Register reset */
#define COM7_FMT_MASK 0x38
#define COM7_FMT_VGA 0x00
#define COM7_FMT_CIF 0x20 /* CIF format */
#define COM7_FMT_QVGA 0x10 /* QVGA format */
#define COM7_FMT_QCIF 0x08 /* QCIF format */
#define COM7_RGB 0x04 /* bits 0 and 2 - RGB format */
#define COM7_YUV 0x00 /* YUV */
#define COM7_BAYER 0x01 /* Bayer format */
#define COM7_PBAYER 0x05 /* "Processed bayer" */
#define REG_COM8 0x13 /* Control 8 */
#define COM8_FASTAEC 0x80 /* Enable fast AGC/AEC */
#define COM8_AECSTEP 0x40 /* Unlimited AEC step size */
#define COM8_BFILT 0x20 /* Band filter enable */
#define COM8_AGC 0x04 /* Auto gain enable */
#define COM8_AWB 0x02 /* White balance enable */
#define COM8_AEC 0x01 /* Auto exposure enable */
#define REG_COM9 0x14 /* Control 9- gain ceiling */
#define REG_COM10 0x15 /* Control 10 */
#define COM10_HSYNC 0x40 /* HSYNC instead of HREF */
#define COM10_PCLK_HB 0x20 /* Suppress PCLK on horiz blank */
#define COM10_HREF_REV 0x08 /* Reverse HREF */
#define COM10_VS_LEAD 0x04 /* VSYNC on clock leading edge */
#define COM10_VS_NEG 0x02 /* VSYNC negative */
#define COM10_HS_NEG 0x01 /* HSYNC negative */
#define REG_HSTART 0x17 /* Horiz start high bits */
#define REG_HSTOP 0x18 /* Horiz stop high bits */
#define REG_VSTART 0x19 /* Vert start high bits */
#define REG_VSTOP 0x1a /* Vert stop high bits */
#define REG_PSHFT 0x1b /* Pixel delay after HREF */
#define REG_MIDH 0x1c /* Manuf. ID high */
#define REG_MIDL 0x1d /* Manuf. ID low */
#define REG_MVFP 0x1e /* Mirror / vflip */
#define MVFP_MIRROR 0x20 /* Mirror image */
#define MVFP_FLIP 0x10 /* Vertical flip */
#define REG_AEW 0x24 /* AGC upper limit */
#define REG_AEB 0x25 /* AGC lower limit */
#define REG_VPT 0x26 /* AGC/AEC fast mode op region */
#define REG_HSYST 0x30 /* HSYNC rising edge delay */
#define REG_HSYEN 0x31 /* HSYNC falling edge delay */
#define REG_HREF 0x32 /* HREF pieces */
#define REG_TSLB 0x3a /* lots of stuff */
#define TSLB_YLAST 0x04 /* UYVY or VYUY - see com13 */
#define REG_COM11 0x3b /* Control 11 */
#define COM11_NIGHT 0x80 /* NIght mode enable */
#define COM11_NMFR 0x60 /* Two bit NM frame rate */
#define COM11_HZAUTO 0x10 /* Auto detect 50/60 Hz */
#define COM11_50HZ 0x08 /* Manual 50Hz select */
#define COM11_EXP 0x02
#define REG_COM12 0x3c /* Control 12 */
#define COM12_HREF 0x80 /* HREF always */
#define REG_COM13 0x3d /* Control 13 */
#define COM13_GAMMA 0x80 /* Gamma enable */
#define COM13_UVSAT 0x40 /* UV saturation auto adjustment */
#define COM13_UVSWAP 0x01 /* V before U - w/TSLB */
#define REG_COM14 0x3e /* Control 14 */
#define COM14_DCWEN 0x10 /* DCW/PCLK-scale enable */
#define REG_EDGE 0x3f /* Edge enhancement factor */
#define REG_COM15 0x40 /* Control 15 */
#define COM15_R10F0 0x00 /* Data range 10 to F0 */
#define COM15_R01FE 0x80 /* 01 to FE */
#define COM15_R00FF 0xc0 /* 00 to FF */
#define COM15_RGB565 0x10 /* RGB565 output */
#define COM15_RGB555 0x30 /* RGB555 output */
#define REG_COM16 0x41 /* Control 16 */
#define COM16_AWBGAIN 0x08 /* AWB gain enable */
#define REG_COM17 0x42 /* Control 17 */
#define COM17_AECWIN 0xc0 /* AEC window - must match COM4 */
#define COM17_CBAR 0x08 /* DSP Color bar */
#define CMATRIX_LEN 6
#define REG_BRIGHT 0x55 /* Brightness */
#define REG_REG76 0x76 /* OV's name */
#define R76_BLKPCOR 0x80 /* Black pixel correction enable */
#define R76_WHTPCOR 0x40 /* White pixel correction enable */
#define REG_RGB444 0x8c /* RGB 444 control */
#define R444_ENABLE 0x02 /* Turn on RGB444, overrides 5x5 */
#define R444_RGBX 0x01 /* Empty nibble at end */
#define REG_HAECC1 0x9f /* Hist AEC/AGC control 1 */
#define REG_HAECC2 0xa0 /* Hist AEC/AGC control 2 */
#define REG_BD50MAX 0xa5 /* 50hz banding step limit */
#define REG_HAECC3 0xa6 /* Hist AEC/AGC control 3 */
#define REG_HAECC4 0xa7 /* Hist AEC/AGC control 4 */
#define REG_HAECC5 0xa8 /* Hist AEC/AGC control 5 */
#define REG_HAECC6 0xa9 /* Hist AEC/AGC control 6 */
#define REG_HAECC7 0xaa /* Hist AEC/AGC control 7 */
#define REG_BD60MAX 0xab /* 60hz banding step limit */
#define MTX1 0x4f /* Matrix Coefficient 1 */
#define MTX2 0x50 /* Matrix Coefficient 2 */
#define MTX3 0x51 /* Matrix Coefficient 3 */
#define MTX4 0x52 /* Matrix Coefficient 4 */
#define MTX5 0x53 /* Matrix Coefficient 5 */
#define MTX6 0x54 /* Matrix Coefficient 6 */
#define REG_CONTRAS 0x56 /* Contrast control */
#define MTXS 0x58 /* Matrix Coefficient Sign */
#define AWBC7 0x59 /* AWB Control 7 */
#define AWBC8 0x5a /* AWB Control 8 */
#define AWBC9 0x5b /* AWB Control 9 */
#define AWBC10 0x5c /* AWB Control 10 */
#define AWBC11 0x5d /* AWB Control 11 */
#define AWBC12 0x5e /* AWB Control 12 */
#define REG_GFI 0x69 /* Fix gain control */
#define GGAIN 0x6a /* G Channel AWB Gain */
#define DBLV 0x6b
#define AWBCTR3 0x6c /* AWB Control 3 */
#define AWBCTR2 0x6d /* AWB Control 2 */
#define AWBCTR1 0x6e /* AWB Control 1 */
#define AWBCTR0 0x6f /* AWB Control 0 */
|
AntonLH/Arduino
|
libraries/ov7670/ov7670.h
|
C
|
mit
| 12,226
|
<div class="ui menu">
<div class="header item">{{title || modelType}}</div>
<!-- Links/Events -->
<a class="ui item" [class.active]="state.searching" (click)="search()">Find</a>
<a class="ui item" [class.active]="state.adding" (click)="add()">Create</a>
<a class="ui item" [class.active]="!state.adding && !state.editing" (click)="list()">List</a>
<!-- Search/Lookup Options -->
<div tabindex="0" class="ui right dropdown item disabled">
Search Options <i class="dropdown icon"></i>
<div tabindex="-1" class="menu">
<div class="item">Action</div>
</div>
</div>
<!-- Model Search/Lookup -->
<div class="right menu disabled">
<div class="item disabled">
<div class="ui action icon input disabled">
<i class="search icon"></i>
<input placeholder="Search" type="text" disabled>
</div>
</div>
</div>
</div>
|
crimsonskyfalling/ocean-seed
|
src/app/common/directives/templates/model-manager-menu.component.html
|
HTML
|
mit
| 866
|
#
# (c) Simon Marlow 2002
#
import sys
import os
import string
import getopt
import platform
import time
import re
from testutil import *
from testglobals import *
# Readline sometimes spews out ANSI escapes for some values of TERM,
# which result in test failures. Thus set TERM to a nice, simple, safe
# value.
os.environ['TERM'] = 'vt100'
if sys.platform == "cygwin":
cygwin = True
else:
cygwin = False
global config
config = getConfig() # get it from testglobals
# -----------------------------------------------------------------------------
# cmd-line options
long_options = [
"config=", # config file
"rootdir=", # root of tree containing tests (default: .)
"output-summary=", # file in which to save the (human-readable) summary
"only=", # just this test (can be give multiple --only= flags)
"way=", # just this way
"skipway=", # skip this way
"threads=", # threads to run simultaneously
]
opts, args = getopt.getopt(sys.argv[1:], "e:", long_options)
for opt,arg in opts:
if opt == '--config':
execfile(arg)
# -e is a string to execute from the command line. For example:
# testframe -e 'config.compiler=ghc-5.04'
if opt == '-e':
exec arg
if opt == '--rootdir':
config.rootdirs.append(arg)
if opt == '--output-summary':
config.output_summary = arg
if opt == '--only':
config.only.append(arg)
if opt == '--way':
if (arg not in config.run_ways and arg not in config.compile_ways and arg not in config.other_ways):
sys.stderr.write("ERROR: requested way \'" +
arg + "\' does not exist\n")
sys.exit(1)
config.cmdline_ways = [arg] + config.cmdline_ways
if (arg in config.other_ways):
config.run_ways = [arg] + config.run_ways
config.compile_ways = [arg] + config.compile_ways
if opt == '--skipway':
if (arg not in config.run_ways and arg not in config.compile_ways and arg not in config.other_ways):
sys.stderr.write("ERROR: requested way \'" +
arg + "\' does not exist\n")
sys.exit(1)
config.other_ways = filter(neq(arg), config.other_ways)
config.run_ways = filter(neq(arg), config.run_ways)
config.compile_ways = filter(neq(arg), config.compile_ways)
if opt == '--threads':
config.threads = int(arg)
config.use_threads = 1
if config.use_threads == 1:
# Trac #1558 says threads don't work in python 2.4.4, but do
# in 2.5.2. Probably >= 2.5 is sufficient, but let's be
# conservative here.
# Some versions of python have things like '1c1' for some of
# these components (see trac #3091), but int() chokes on the
# 'c1', so we drop it.
(maj, min, pat) = platform.python_version_tuple()
# We wrap maj, min, and pat in str() to work around a bug in python
# 2.6.1
maj = int(re.sub('[^0-9].*', '', str(maj)))
min = int(re.sub('[^0-9].*', '', str(min)))
pat = int(re.sub('[^0-9].*', '', str(pat)))
if (maj, min, pat) < (2, 5, 2):
print "Warning: Ignoring request to use threads as python version < 2.5.2"
config.use_threads = 0
if windows:
print "Warning: Ignoring request to use threads as running on Windows"
config.use_threads = 0
# Try to use UTF8
if windows:
import ctypes
if cygwin:
# Is this actually right? Which calling convention does it use?
# As of the time of writing, ctypes.windll doesn't exist in the
# cygwin python, anyway.
mydll = ctypes.cdll
else:
mydll = ctypes.windll
# This actually leaves the terminal in codepage 65001 (UTF8) even
# after python terminates. We ought really remember the old codepage
# and set it back.
if mydll.kernel32.SetConsoleCP(65001) == 0:
raise Exception("Failure calling SetConsoleCP(65001)")
if mydll.kernel32.SetConsoleOutputCP(65001) == 0:
raise Exception("Failure calling SetConsoleOutputCP(65001)")
else:
# Try and find a utf8 locale to use
# First see if we already have a UTF8 locale
h = os.popen('locale | grep LC_CTYPE | grep -i utf', 'r')
v = h.read()
h.close()
if v == '':
# We don't, so now see if 'locale -a' works
h = os.popen('locale -a', 'r')
v = h.read()
h.close()
if v != '':
# If it does then use the first utf8 locale that is available
h = os.popen('locale -a | grep -i "utf8\|utf-8" 2>/dev/null', 'r')
v = h.readline().strip()
h.close()
if v != '':
os.environ['LC_ALL'] = v
print "setting LC_ALL to", v
else:
print 'WARNING: No UTF8 locale found.'
print 'You may get some spurious test failures.'
# This has to come after arg parsing as the args can change the compiler
get_compiler_info()
# Can't import this earlier as we need to know if threading will be
# enabled or not
from testlib import *
# On Windows we need to set $PATH to include the paths to all the DLLs
# in order for the dynamic library tests to work.
if windows or darwin:
pkginfo = getStdout([config.ghc_pkg, 'dump'])
topdir = re.sub('\\\\','/',getStdout([config.compiler, '--print-libdir'])).rstrip()
for line in pkginfo.split('\n'):
if line.startswith('library-dirs:'):
path = line.rstrip()
path = re.sub('^library-dirs: ', '', path)
path = re.sub('\\$topdir', topdir, path)
if path.startswith('"'):
path = re.sub('^"(.*)"$', '\\1', path)
path = re.sub('\\\\(.)', '\\1', path)
if windows:
if cygwin:
# On cygwin we can't put "c:\foo" in $PATH, as : is a
# field separator. So convert to /cygdrive/c/foo instead.
# Other pythons use ; as the separator, so no problem.
path = re.sub('([a-zA-Z]):', '/cygdrive/\\1', path)
path = re.sub('\\\\', '/', path)
os.environ['PATH'] = os.pathsep.join([path, os.environ.get("PATH", "")])
else:
# darwin
os.environ['DYLD_LIBRARY_PATH'] = os.pathsep.join([path, os.environ.get("DYLD_LIBRARY_PATH", "")])
global testopts_local
testopts_local.x = TestOptions()
global thisdir_testopts
thisdir_testopts = getThisDirTestOpts()
if config.use_threads:
t.lock = threading.Lock()
t.thread_pool = threading.Condition(t.lock)
t.running_threads = 0
# if timeout == -1 then we try to calculate a sensible value
if config.timeout == -1:
config.timeout = int(read_no_crs(config.top + '/timeout/calibrate.out'))
print 'Timeout is ' + str(config.timeout)
# -----------------------------------------------------------------------------
# The main dude
if config.rootdirs == []:
config.rootdirs = ['.']
t_files = findTFiles(config.rootdirs)
print 'Found', len(t_files), '.T files...'
t = getTestRun()
# Avoid cmd.exe built-in 'date' command on Windows
if not windows:
t.start_time = chop(os.popen('date').read())
else:
t.start_time = 'now'
print 'Beginning test run at', t.start_time
# set stdout to unbuffered (is this the best way to do it?)
sys.stdout.flush()
sys.stdout = os.fdopen(sys.__stdout__.fileno(), "w", 0)
# First collect all the tests to be run
for file in t_files:
print '====> Scanning', file
newTestDir(os.path.dirname(file))
try:
execfile(file)
except:
print '*** framework failure: found an error while executing ', file, ':'
t.n_framework_failures = t.n_framework_failures + 1
traceback.print_exc()
# Now run all the tests
if config.use_threads:
t.running_threads=0
for oneTest in allTests:
oneTest()
if config.use_threads:
t.thread_pool.acquire()
while t.running_threads>0:
t.thread_pool.wait()
t.thread_pool.release()
summary(t, sys.stdout)
if config.output_summary != '':
summary(t, open(config.output_summary, 'w'))
sys.exit(0)
|
iliastsi/gac
|
testsuite/driver/runtests.py
|
Python
|
mit
| 8,165
|
var pkg = require('../package.json'); //Application Settings
var fs = require('fs');
var db;
var collection; //Twitter Collection
var summaryLength = 2;
var summary = {}; //Tweets by country, total tweets, total smiley face matches
summary.name="World Text";
var countries;
//Heat map coloring
//Provide a range minimum and maximum along with the target value
//Returns a CSS ready RGB value
var rgb = function(heats, value) {
var index = Math.floor(heats.length/9);
var colors = ['rgb(247,244,249)','rgb(231,225,239)','rgb(212,185,218)',
'rgb(201,148,199)','rgb(223,101,176)','rgb(231,41,138)',
'rgb(206,18,86)','rgb(152,0,67)','rgb(103,0,31)'];
if( value < heats[index]){
return colors[0];
}else if ( value <= heats[index*2]){
return colors[1];
}else if ( value <= heats[index*3]){
return colors[2];
}else if ( value <= heats[index*4]){
return colors[3];
}else if ( value <= heats[index*5]){
return colors[4];
}else if ( value <= heats[index*6]){
return colors[5];
}else if ( value <= heats[index*7]){
return colors[6];
}else if ( value <= heats[index*8]){
return colors[7];
}else{
return colors[8];
}
};
var createSummary = function() {
console.log("Starting createSummary");
collection.distinct("properties.country", function(err, docs) {
if (err) {
console.error("Error - distinct countries: " + err.message);
} else {
countries = docs;
summaryLength += (countries.length * 2);
for (var x = 0; x < countries.length; x++) {
countries[x] = countries[x].replace(/\./g,'_');
countrySum(countries[x]);
}
}
wrapIt();
});
};
var countrySum = function(country) {
summary[country] = {};
collection.count({
"properties.country": country
}, {}, function(err, count) {
if (err) {
console.error("Error - summary[" + country + "].total: " + err.message);
} else {
summary[country].total = count;
}
wrapIt();
});
//Regular expression matching for the following smiley faces:
//:) :D :-D ;) :-) :P :p :-P :-p =) ;-) =D =] :] =P :-D ^_^ (^^) (: (8 (;
collection.count({
"properties.country": country,
$or:[
{"properties.text":{$regex:/\:\)/}},
{"properties.text":{$regex:/\:D/}},
{"properties.text":{$regex:/\:\-D/}},
{"properties.text":{$regex:/\(\^\^\)/}},
{"properties.text":{$regex:/\;\)/}},
{"properties.text":{$regex:/\:\-\)/}},
{"properties.text":{$regex:/\:p/}},
{"properties.text":{$regex:/\=\)/}},
{"properties.text":{$regex:/\=D/}},
{"properties.text":{$regex:/\=\]/}},
{"properties.text":{$regex:/\:\]/}},
{"properties.text":{$regex:/\:\-D/}},
{"properties.text":{$regex:/\^\_\^/}},
{"properties.text":{$regex:/\(\:/}},
{"properties.text":{$regex:/\(8/}},
{"properties.text":{$regex:/\(\;/}},
{"properties.text":{$regex:/\:\-P/}},
{"properties.text":{$regex:/\:\-p/}},
{"properties.text":{$regex:/\:p/}},
{'properties.text':/😄|😃|😀|😊|☺|😉|😍|😘|😚|😗|😙|😜|😝|😛|😁|😇|😏|👮|👷|👶|👦|👧|👨|👩|👴|👵|👱|👼|👸|😺|😸|👹|👽|💩/}
]
}, {}, function(err, count) {
if (err) {
console.error("Error - summary[" + country + "].textMatch: " + err.message);
} else {
summary[country].textMatch = count;
}
wrapIt();
});
};
var countryCode = function() {
console.log("Starting countryCode");
var heats = [];
for (var x = 0; x < countries.length; x++) {
summary[countries[x]].percent = summary[countries[x]].textMatch / summary[countries[x]].total;
heats.push(summary[countries[x]].percent);
}
heats.sort(function(a,b){return a-b;});
console.log("Creating HeatMap");
for (var x = 0; x < countries.length; x++) {
if (summary[countries[x]].total) {
summary[countries[x]].heat = rgb(heats, summary[countries[x]].percent);
}
};
wrapIt();
};
var wrapIt = function() {
summaryLength -= 1;
if (summaryLength == 1) {
//DB queries done
countryCode();
} else if (summaryLength == 0) {
console.log('Saving World Text Summary');
db.collection('summary').update({"name": "World Text"}, summary, {upsert: true, w:1, safe:true},function(err) { if(err) { console.error(err.message); } db.close(); });
}
};
var dbLoaded = function(err, database) {
if (err) {
console.error(err.message);
}
db = database;
collection = db.collection('twitter');
console.log("Database Connected");
createSummary();
};
require('mongodb').MongoClient.connect(pkg.config.db_url, dbLoaded);
|
bshouse/geotweeter
|
bin/createWorldTextSummary.js
|
JavaScript
|
mit
| 4,440
|
#ifndef _ROS_SERVICE_AssignTask_h
#define _ROS_SERVICE_AssignTask_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
namespace auto_warehousing
{
static const char ASSIGNTASK[] = "auto_warehousing/AssignTask";
class AssignTaskRequest : public ros::Msg
{
public:
typedef uint32_t _task_id_type;
_task_id_type task_id;
AssignTaskRequest():
task_id(0)
{
}
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
*(outbuffer + offset + 0) = (this->task_id >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (this->task_id >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (this->task_id >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (this->task_id >> (8 * 3)) & 0xFF;
offset += sizeof(this->task_id);
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
this->task_id = ((uint32_t) (*(inbuffer + offset)));
this->task_id |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
this->task_id |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
this->task_id |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
offset += sizeof(this->task_id);
return offset;
}
const char * getType(){ return ASSIGNTASK; };
const char * getMD5(){ return "01f8cf8853582efbb17391a60263fd03"; };
};
class AssignTaskResponse : public ros::Msg
{
public:
typedef bool _success_type;
_success_type success;
AssignTaskResponse():
success(0)
{
}
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
union {
bool real;
uint8_t base;
} u_success;
u_success.real = this->success;
*(outbuffer + offset + 0) = (u_success.base >> (8 * 0)) & 0xFF;
offset += sizeof(this->success);
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
union {
bool real;
uint8_t base;
} u_success;
u_success.base = 0;
u_success.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0);
this->success = u_success.real;
offset += sizeof(this->success);
return offset;
}
const char * getType(){ return ASSIGNTASK; };
const char * getMD5(){ return "358e233cde0c8a8bcfea4ce193f8fc15"; };
};
class AssignTask {
public:
typedef AssignTaskRequest Request;
typedef AssignTaskResponse Response;
};
}
#endif
|
Roboterbastler/roseau
|
embedded/libraries/ros_lib/auto_warehousing/AssignTask.h
|
C
|
mit
| 2,553
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.Media.VideoAnalyzer.Edge.Models
{
public partial class RemoteDeviceAdapterSetRequest : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("remoteDeviceAdapter");
writer.WriteObjectValue(RemoteDeviceAdapter);
if (Optional.IsDefined(ApiVersion))
{
writer.WritePropertyName("@apiVersion");
writer.WriteStringValue(ApiVersion);
}
writer.WriteEndObject();
}
internal static RemoteDeviceAdapterSetRequest DeserializeRemoteDeviceAdapterSetRequest(JsonElement element)
{
RemoteDeviceAdapter remoteDeviceAdapter = default;
string methodName = default;
Optional<string> apiVersion = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("remoteDeviceAdapter"))
{
remoteDeviceAdapter = RemoteDeviceAdapter.DeserializeRemoteDeviceAdapter(property.Value);
continue;
}
if (property.NameEquals("methodName"))
{
methodName = property.Value.GetString();
continue;
}
if (property.NameEquals("@apiVersion"))
{
apiVersion = property.Value.GetString();
continue;
}
}
return new RemoteDeviceAdapterSetRequest(methodName, apiVersion.Value, remoteDeviceAdapter);
}
}
}
|
Azure/azure-sdk-for-net
|
sdk/videoanalyzer/Azure.Media.VideoAnalyzer.Edge/src/Generated/Models/RemoteDeviceAdapterSetRequest.Serialization.cs
|
C#
|
mit
| 1,883
|
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.RecoveryServices.Backup.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Container for the workloads running inside Azure Compute or Classic
/// Compute.
/// </summary>
public partial class AzureWorkloadContainer : ProtectionContainer
{
/// <summary>
/// Initializes a new instance of the AzureWorkloadContainer class.
/// </summary>
public AzureWorkloadContainer()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the AzureWorkloadContainer class.
/// </summary>
/// <param name="friendlyName">Friendly name of the container.</param>
/// <param name="backupManagementType">Type of backup management for
/// the container. Possible values include: 'Invalid', 'AzureIaasVM',
/// 'MAB', 'DPM', 'AzureBackupServer', 'AzureSql', 'AzureStorage',
/// 'AzureWorkload', 'DefaultBackup'</param>
/// <param name="registrationStatus">Status of registration of the
/// container with the Recovery Services Vault.</param>
/// <param name="healthStatus">Status of health of the
/// container.</param>
/// <param name="protectableObjectType">Type of the protectable object
/// associated with this container</param>
/// <param name="sourceResourceId">ARM ID of the virtual machine
/// represented by this Azure Workload Container</param>
/// <param name="lastUpdatedTime">Time stamp when this container was
/// updated.</param>
/// <param name="extendedInfo">Additional details of a workload
/// container.</param>
/// <param name="workloadType">Workload type for which registration was
/// sent. Possible values include: 'Invalid', 'VM', 'FileFolder',
/// 'AzureSqlDb', 'SQLDB', 'Exchange', 'Sharepoint', 'VMwareVM',
/// 'SystemState', 'Client', 'GenericDataSource', 'SQLDataBase',
/// 'AzureFileShare', 'SAPHanaDatabase', 'SAPAseDatabase'</param>
/// <param name="operationType">Re-Do Operation. Possible values
/// include: 'Invalid', 'Register', 'Reregister'</param>
public AzureWorkloadContainer(string friendlyName = default(string), string backupManagementType = default(string), string registrationStatus = default(string), string healthStatus = default(string), string protectableObjectType = default(string), string sourceResourceId = default(string), System.DateTime? lastUpdatedTime = default(System.DateTime?), AzureWorkloadContainerExtendedInfo extendedInfo = default(AzureWorkloadContainerExtendedInfo), string workloadType = default(string), string operationType = default(string))
: base(friendlyName, backupManagementType, registrationStatus, healthStatus, protectableObjectType)
{
SourceResourceId = sourceResourceId;
LastUpdatedTime = lastUpdatedTime;
ExtendedInfo = extendedInfo;
WorkloadType = workloadType;
OperationType = operationType;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets ARM ID of the virtual machine represented by this
/// Azure Workload Container
/// </summary>
[JsonProperty(PropertyName = "sourceResourceId")]
public string SourceResourceId { get; set; }
/// <summary>
/// Gets or sets time stamp when this container was updated.
/// </summary>
[JsonProperty(PropertyName = "lastUpdatedTime")]
public System.DateTime? LastUpdatedTime { get; set; }
/// <summary>
/// Gets or sets additional details of a workload container.
/// </summary>
[JsonProperty(PropertyName = "extendedInfo")]
public AzureWorkloadContainerExtendedInfo ExtendedInfo { get; set; }
/// <summary>
/// Gets or sets workload type for which registration was sent.
/// Possible values include: 'Invalid', 'VM', 'FileFolder',
/// 'AzureSqlDb', 'SQLDB', 'Exchange', 'Sharepoint', 'VMwareVM',
/// 'SystemState', 'Client', 'GenericDataSource', 'SQLDataBase',
/// 'AzureFileShare', 'SAPHanaDatabase', 'SAPAseDatabase'
/// </summary>
[JsonProperty(PropertyName = "workloadType")]
public string WorkloadType { get; set; }
/// <summary>
/// Gets or sets re-Do Operation. Possible values include: 'Invalid',
/// 'Register', 'Reregister'
/// </summary>
[JsonProperty(PropertyName = "operationType")]
public string OperationType { get; set; }
}
}
|
Azure/azure-sdk-for-net
|
sdk/recoveryservices-backup/Microsoft.Azure.Management.RecoveryServices.Backup/src/recoveryservicesbackup/Generated/Models/AzureWorkloadContainer.cs
|
C#
|
mit
| 5,204
|
# Dir check
> Check if a path is a directory
## Installation
```bash
npm install --save dir-check
```
## Usage
```javascript
const check = require('dir-check');
if (check('my-dir')) {
console.log('is a dir');
}
```
> Working example in [test.js](https://github.com/tobihrbr/dir-check/blob/master/test.js)
## License
MIT
|
Poornakiruthika/Test
|
node_modules/dir-check/README.md
|
Markdown
|
mit
| 327
|
const util = require('../util/httpUtil.js')
function createTask (name, content, creatorId, memberId, progressId, file, ddl) {
return util.httpPost(util.baseURL + 'task', {
name: name,
content: content,
creatorId: creatorId,
memberIds: memberIds,
progressId: progressId,
file: file,
ddl: ddl
})
}
function deleteTask (projectId, taskId, userId) {
return util.httpDel(util.baseURL + 'task', {projectId: projectId, taskId: taskId, userId: userId})
}
function getTaskList (projectId, userId) {
return util.httpGet(util.baseURL + 'task/list?projectId=” + = projectId “&userId=“ + userId')
}
function updateInfo (taskId, executorId, userId) {
return util.httpPut(util.baseURL + 'task/item', {
taskId: taskId,
executorId: executorId,
userId: userId
})
}
function getInfo (projectId, taskId) {
return util.httpGet(util.baseURL + 'task/item?projectId=” + = projectId “&taskId” += taskId')
}
function updateState (taskId, userId) {
return util.httpPut(util.baseURL + 'task/state', {
taskId: taskId,
userId: userId
})
}
function createSubTask (subtaskContent, taskId, userId) {
return util.httpPost(util.baseURL + 'subtask', {
subtaskContent: subtaskContent,
taskId: taskId,
userId: userId
})
}
function deleteSubTask (subtaskId, userId) {
return util.httpDel(util.baseURL + 'subtask', {subtaskId: subtaskId, userId: userId})
}
function getSubtaskList (subtaskId) {
return util.httpGet(util.baseURL + 'subtask/list/?subtaskId=” += subtaskId')
}
function updateSubtaskInfo (subtaskId, subtaskExecutorId) {
return util.httpPut(util.baseURL + 'subtask', {
subtaskId: subtaskId,
subtaskExecutorId: subtaskExecutorId
})
}
function updateSubtaskState (subtaskId, userId) {
return util.httpPut(util.baseURL + 'subtask/state', {
subtaskId: subtaskId,
userId: userId
})
}
function addMember (taskId, participatorIds) {
return util.httpDel(util.baseURL + 'task/participator', {
taskId: taskId,
participatorIds: participatorIds
})
}
function deleteMember (taskId, participatorIds) {
return util.httpDel(util.baseURL + 'task/participator', {
taskId: taskId,
participatorIds: participatorIds
})
}
function getMemberList (taskId) {
return util.httpGet(util.httpGet + 'task/participator/list?taskId=“ + taskId')
}
module.exports = {
createTask,
deleteTask,
getTaskList,
updateInfo,
getInfo,
updateState,
createSubTask,
deleteSubTask,
getSubtaskList,
updateSubtaskInfo,
updateSubtaskState,
addMember,
deleteMember,
getMemberList
}
|
cool-db/front-end
|
src/webApi/taskApi.js
|
JavaScript
|
mit
| 2,599
|
<?php
use Doctrine\DBAL\DriverManager;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
$console = new Application('SilexExcel', '0.1');
$app->boot();
$console
->register('assetic:dump')
->setDescription('Dumps all assets to the filesystem')
->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {
if (!$app['assetic.enabled']) {
return false;
}
$dumper = $app['assetic.dumper'];
if (isset($app['twig'])) {
$dumper->addTwigAssets();
}
$dumper->dumpAssets();
$output->writeln('<info>Dump finished</info>');
})
;
if (isset($app['cache.path'])) {
$console
->register('cache:clear')
->setDescription('Clears the cache')
->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {
$cacheDir = $app['cache.path'];
$finder = Finder::create()->in($cacheDir)->notName('.gitkeep');
$filesystem = new Filesystem();
$filesystem->remove($finder);
$output->writeln(sprintf("%s <info>success</info>", 'cache:clear'));
});
}
$console
->register('doctrine:schema:show')
->setDescription('Output schema declaration')
->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {
$schema = require __DIR__.'/../resources/db/schema.php';
foreach ($schema->toSql($app['db']->getDatabasePlatform()) as $sql) {
$output->writeln($sql.';');
}
})
;
$console
->register('doctrine:schema:load')
->setDescription('Load schema')
->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {
$schema = require __DIR__.'/../resources/db/schema.php';
foreach ($schema->toSql($app['db']->getDatabasePlatform()) as $sql) {
$app['db']->exec($sql.';');
}
})
;
$console
->register('doctrine:database:drop')
->setName('doctrine:database:drop')
->setDescription('Drops the configured databases')
->addOption('connection', null, InputOption::VALUE_OPTIONAL, 'The connection to use for this command')
->addOption('force', null, InputOption::VALUE_NONE, 'Set this parameter to execute this action')
->setHelp(
<<<EOT
The <info>doctrine:database:drop</info> command drops the default connections
database:
<info>php app/console doctrine:database:drop</info>
The --force parameter has to be used to actually drop the database.
You can also optionally specify the name of a connection to drop the database
for:
<info>php app/console doctrine:database:drop --connection=default</info>
<error>Be careful: All data in a given database will be lost when executing
this command.</error>
EOT
)
->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {
$connection = $app['db'];
$params = $connection->getParams();
$name = isset($params['path']) ? $params['path'] : (isset($params['dbname']) ? $params['dbname'] : false);
if (!$name) {
throw new \InvalidArgumentException("Connection does not contain a 'path' or 'dbname' parameter and cannot be dropped.");
}
if ($input->getOption('force')) {
// Only quote if we don't have a path
if (!isset($params['path'])) {
$name = $connection->getDatabasePlatform()->quoteSingleIdentifier($name);
}
try {
$connection->getSchemaManager()->dropDatabase($name);
$output->writeln(sprintf('<info>Dropped database for connection named <comment>%s</comment></info>', $name));
} catch (\Exception $e) {
$output->writeln(sprintf('<error>Could not drop database for connection named <comment>%s</comment></error>', $name));
$output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
return 1;
}
} else {
$output->writeln('<error>ATTENTION:</error> This operation should not be executed in a production environment.');
$output->writeln('');
$output->writeln(sprintf('<info>Would drop the database named <comment>%s</comment>.</info>', $name));
$output->writeln('Please run the operation with --force to execute');
$output->writeln('<error>All data will be lost!</error>');
return 2;
}
})
;
$console
->register('doctrine:database:create')
->setDescription('Creates the configured databases')
->addOption('connection', null, InputOption::VALUE_OPTIONAL, 'The connection to use for this command')
->setHelp(
<<<EOT
The <info>doctrine:database:create</info> command creates the default
connections database:
<info>php app/console doctrine:database:create</info>
You can also optionally specify the name of a connection to create the
database for:
<info>php app/console doctrine:database:create --connection=default</info>
EOT
)
->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {
$connection = $app['db'];
$params = $connection->getParams();
$name = isset($params['path']) ? $params['path'] : $params['dbname'];
unset($params['dbname']);
$tmpConnection = DriverManager::getConnection($params);
// Only quote if we don't have a path
if (!isset($params['path'])) {
$name = $tmpConnection->getDatabasePlatform()->quoteSingleIdentifier($name);
}
$error = false;
try {
$tmpConnection->getSchemaManager()->createDatabase($name);
$output->writeln(sprintf('<info>Created database for connection named <comment>%s</comment></info>', $name));
} catch (\Exception $e) {
$output->writeln(sprintf('<error>Could not create database for connection named <comment>%s</comment></error>', $name));
$output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
$error = true;
}
$tmpConnection->close();
return $error ? 1 : 0;
})
;
return $console;
|
EquisoftDev/Silex-Excel
|
src/console.php
|
PHP
|
mit
| 6,393
|
"""
These settings are used by the ``manage.py`` command.
With normal tests we want to use the fastest possible way which is an
in-memory sqlite database but if you want to create South migrations you
need a persistant database.
Unfortunately there seems to be an issue with either South or syncdb so that
defining two routers ("default" and "south") does not work.
"""
from cmsplugin_redirect.tests.test_settings import * # NOQA
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite',
}
}
INSTALLED_APPS.append('south', )
|
bitmazk/cmsplugin-redirect
|
cmsplugin_redirect/tests/south_settings.py
|
Python
|
mit
| 586
|
class TeamsController < ApplicationController
before_filter :authenticate_user!
def new
@team = Team.create_default_team("Rename", current_user, params[:version_name])
if @team
session[:team_id] = @team.id
redirect_to(edit_team_path(@team), :notice => 'Team was successfully created.')
else
redirect_to(root_path, :error => 'Unable to add a new team.')
end
end
def edit
@team = Team.find(params[:id].to_i)
authorize! :update, @team
@members = @team.members
end
#def create
# @team = Team.new(params[:team])
#
# respond_to do |format|
# if @team.save
# format.html { redirect_to(teams_path, :notice => 'Team was successfully created.') }
# else
# format.html { render :action => "new" }
# end
# end
#end
# def update
# @team = Team.find(params[:id])
## authorize! :update, @team
#
# respond_to do |format|
# if @team.update_attributes(params[:team])
# format.html { redirect_to(teams_path, :notice => notice_msg || 'Team was successfully updated.') }
# else
# format.html { render :action => "edit" }
# end
# end
# end
def show
@team = Team.find(params[:id].to_i)
authorize! :read, @team
@snapshot = @team.find_latest_or_create_first_snapshot
end
def mass_invite
team = Team.find(params[:team_id].to_i)
authorize! :update, team
mass_invite = params[:mass_invite]
mass_invite.split(",").each do |email|
team.add_member_or_invite(email, current_user) if email.present?
end
redirect_to team_path(team)
end
def checklists
@team = Team.find(params[:id].to_i)
authorize! :read, @team
@checked_checklists = @team.checklists
end
def snapshot_history_first
@team = Team.find(params[:id].to_i)
authorize! :read, @team
@essence_version = @team.essence_version
@snapshots = []
@snapshot_history = []
@team.snapshots.reverse_each do |snapshot|
@snapshots << snapshot
@snapshot_history = snapshot.snapshot_alphas_hash
end
end
def snapshot_history
@team = Team.find(params[:id].to_i)
authorize! :read, @team
@snapshot_history = Snapshot.history(@team)
@snapshots = @team.snapshots.reverse
end
def snapshot_export
@team = Team.find(params[:id].to_i)
authorize! :read, @team
temp_file_path = File.expand_path("#{Rails.root}/tmp/#{Process.pid}_") + "export.xls"
Snapshot.export_history_to_spreadsheet(@team, temp_file_path)
flash[:notice] = "snapshot history was exported to " + temp_file_path
send_file(temp_file_path, :filename => "Snapshots_#{@team.name.parameterize}.xls")
end
end
|
professor/semat
|
app/controllers/teams_controller.rb
|
Ruby
|
mit
| 2,686
|
require "admin/import"
require "admin/view"
module Admin
module Views
module Pages
module Home
class Edit < Admin::View
include Admin::Import[
"persistence.repositories.home_page_featured_items",
"pages.home.forms.edit_form",
]
configure do |config|
config.template = "pages/home/edit"
end
def locals(options = {})
featured_items = {
home_page_featured_items: home_page_featured_items.listing.map(&:to_h)
}
super.merge(
page_form: form_data(featured_items, options[:validation])
)
end
private
def form_data(featured_items, validation)
if validation
edit_form.build(validation, validation.messages)
else
edit_form.build(featured_items)
end
end
end
end
end
end
end
|
icelab/berg
|
apps/admin/lib/admin/views/pages/home/edit.rb
|
Ruby
|
mit
| 975
|
extern crate snap;
use std::io::{self, Read, Write};
pub fn compress(uncompressed: &[u8], compressed: &mut Vec<u8>) -> io::Result<()> {
compressed.clear();
let mut encoder = snap::Writer::new(compressed);
encoder.write_all(&uncompressed)?;
encoder.flush()?;
Ok(())
}
pub fn decompress(compressed: &[u8], decompressed: &mut Vec<u8>) -> io::Result<()> {
decompressed.clear();
snap::Reader::new(compressed).read_to_end(decompressed)?;
Ok(())
}
|
fulmicoton/tantivy
|
src/store/compression_snap.rs
|
Rust
|
mit
| 476
|
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app';
platformBrowserDynamic().bootstrapModule(AppModule).catch((error) => console.log("An error occured in bootsrap :", error));
|
sirajc/angular2-bs4-navbar
|
src/main.ts
|
TypeScript
|
mit
| 236
|
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Array renderer.
*
* Produces an array that contains class names and content pairs.
* The array can be enumerated or associative. Associative means
* <code>class => content</code> pairs.
* Based on the HTML renderer by Andrey Demenev.
*
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
*
* @category Text
* @package Text_Highlighter
* @author Stoyan Stefanov <ssttoo@gmail.com>
* @copyright 2006 Stoyan Stefanov
* @license http://www.php.net/license/3_0.txt PHP License
* @version CVS: $Id: Array.php,v 1.1 2007/06/03 02:37:08 ssttoo Exp $
* @link http://pear.php.net/package/Text_Highlighter
*/
/**
* @ignore
*/
require_once dirname(__FILE__) . '/../Renderer.php';
/**
* Array renderer, based on Andrey Demenev's HTML renderer.
*
* In addition to the options supported by the HTML renderer,
* the following options were also introduced:
* <ul><li>htmlspecialchars - whether or not htmlspecialchars() will
* be called on the content, default TRUE</li>
* <li>enumerated - type of array produced, default FALSE,
* meaning associative array</li>
* </ul>
*
*
* @author Stoyan Stefanov <ssttoo@gmail.com>
* @category Text
* @package Text_Highlighter
* @copyright 2006 Stoyan Stefanov
* @license http://www.php.net/license/3_0.txt PHP License
* @version Release: 0.5.0
* @link http://pear.php.net/package/Text_Highlighter
*/
class Text_Highlighter_Renderer_Array extends Text_Highlighter_Renderer
{
/**#@+
* @access private
*/
/**
* Tab size
*
* @var integer
*/
var $_tabsize = 4;
/**
* Should htmlentities() will be called
*
* @var boolean
*/
var $_htmlspecialchars = true;
/**
* Enumerated or associative array
*
* @var integer
*/
var $_enumerated = false;
/**
* Array containing highlighting rules
*
* @var array
*/
var $_output = array();
/**#@-*/
/**
* Preprocesses code
*
* @access public
*
* @param string $str Code to preprocess
*
* @return string Preprocessed code
*/
function preprocess($str)
{
// normalize whitespace and tabs
$str = str_replace("\r\n", "\n", $str);
// some browsers refuse to display empty lines
$str = preg_replace('~^$~m', " ", $str);
$str = str_replace("\t", str_repeat(' ', $this->_tabsize), $str);
return rtrim($str);
}
/**
* Resets renderer state
*
* Descendents of Text_Highlighter call this method from the constructor,
* passing $options they get as parameter.
*
* @access protected
*/
function reset()
{
$this->_output = array();
$this->_lastClass = 'default';
if (isset($this->_options['tabsize'])) {
$this->_tabsize = $this->_options['tabsize'];
}
if (isset($this->_options['htmlspecialchars'])) {
$this->_htmlspecialchars = $this->_options['htmlspecialchars'];
}
if (isset($this->_options['enumerated'])) {
$this->_enumerated = $this->_options['enumerated'];
}
}
/**
* Accepts next token
*
* @abstract
* @access public
*
* @param string $class Token class
* @param string $content Token content
*/
function acceptToken($class, $content)
{
$theClass = $this->_getFullClassName($class);
if ($this->_htmlspecialchars) {
$content = htmlspecialchars($content);
}
if ($this->_enumerated) {
$this->_output[] = array($class, $content);
} else {
$this->_output[][$class] = $content;
}
$this->_lastClass = $class;
}
/**
* Given a CSS class name, returns the class name
* with language name prepended, if necessary
*
* @access private
*
* @param string $class Token class
*/
function _getFullClassName($class)
{
if (!empty($this->_options['use_language'])) {
$theClass = $this->_language . '-' . $class;
} else {
$theClass = $class;
}
return $theClass;
}
/**
* Get generated output
*
* @abstract
* @return array Highlighted code as an array
* @access public
*/
function getOutput()
{
return $this->_output;
}
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* c-hanging-comment-ender-p: nil
* End:
*/
?>
|
neowutran/Nuitinfo
|
nuitinfo/protected/common/lib/vendor/yiisoft/yii/framework/vendors/TextHighlighter/Text/Highlighter/Renderer/Array.php
|
PHP
|
mit
| 5,000
|
import * as sudoku from './lib/SudokuSolver';
export interface SudokuCell extends sudoku.Sudoku.SolvedCell {
initial?: boolean;
};
export interface Message {
messageString: string;
messageType: string;
}
export interface SudokuState {
initialCells: SudokuCell[];
resultCells: SudokuCell[];
selectedCell: SudokuCell | undefined;
hint: boolean;
teacher: boolean;
hintResult: number[];
solved: boolean;
messages: Message[];
};
|
wednesdaydeveloper/sudoku
|
src/State.ts
|
TypeScript
|
mit
| 450
|
/**
* @file
* @brief Contains the TPZConsLawTest class for test. Material as conservation law
*/
#ifndef CONSLAWTESTHPP
#define CONSLAWTESTHPP
#include <iostream>
#include "pzmaterial.h"
#include "pzfmatrix.h"
#include "pzvec.h"
#include "pzconslaw.h"
/**
* @brief Only to test a material as conservation law. It was used for testing purposes
* @ingroup material
*/
class TPZConsLawTest : public TPZConservationLaw {
TPZFMatrix<REAL> fXf;//fonte
TPZVec<REAL> fB;
int fArtificialDiffusion;
/// Integer for integration degree of the initial solution
int fTest;
REAL fDelta;
public :
TPZConsLawTest(int nummat, TPZVec<REAL> B,int artdiff,REAL delta_t,int dim,REAL delta,int test=0);
virtual ~TPZConsLawTest();
void SetMaterial(TPZFMatrix<REAL> &xfin) {
fXf = xfin;
}
REAL DeltaOtimo();
REAL CFL(int degree);
REAL B(int i,TPZVec<REAL> &x);
REAL Delta();
REAL T(int jn,TPZVec<REAL> &x);
int NStateVariables();
virtual void Print(std::ostream & out);
virtual std::string Name() { return "TPZConsLawTest"; }
virtual void Contribute(TPZMaterialData &data,REAL weight,
TPZFMatrix<REAL> &ek,TPZFMatrix<REAL> &ef);
virtual void Contribute(TPZMaterialData &data,REAL weight,
TPZFMatrix<REAL> &ef) {
TPZConservationLaw::Contribute(data,weight,ef);
}
virtual void ContributeInterface(TPZMaterialData &data, TPZMaterialData &dataleft, TPZMaterialData &dataright,
REAL weight,
TPZFMatrix<REAL> &ek,
TPZFMatrix<REAL> &ef);
virtual void ContributeBC(TPZMaterialData &data,
REAL weight,
TPZFMatrix<REAL> &ek,
TPZFMatrix<REAL> &ef,
TPZBndCond &bc);
virtual void ContributeBC(TPZMaterialData &data,
REAL weight,
TPZFMatrix<REAL> &ef,
TPZBndCond &bc)
{
TPZConservationLaw::ContributeBC(data,weight,ef,bc);
}
virtual int VariableIndex(const std::string &name);
virtual int NSolutionVariables(int var);
virtual int NFluxes(){ return 1;}
protected:
virtual void Solution(TPZVec<REAL> &Sol,TPZFMatrix<REAL> &DSol,TPZFMatrix<REAL> &axes,int var,TPZVec<REAL> &Solout);
public:
virtual void Solution(TPZMaterialData &data,int var,TPZVec<REAL> &Solout)
{
int numbersol = data.sol.size();
if (numbersol != 1) {
DebugStop();
}
Solution(data.sol[0],data.dsol[0],data.axes,var,Solout);
}
/** @brief Compute the value of the flux function to be used by ZZ error estimator */
virtual void Flux(TPZVec<REAL> &x, TPZVec<REAL> &Sol, TPZFMatrix<REAL> &DSol, TPZFMatrix<REAL> &axes, TPZVec<REAL> &flux);
void Errors(TPZVec<REAL> &x,TPZVec<REAL> &u,
TPZFMatrix<REAL> &dudx, TPZFMatrix<REAL> &axes, TPZVec<REAL> &flux,
TPZVec<REAL> &u_exact,TPZFMatrix<REAL> &du_exact,TPZVec<REAL> &values);
void ComputeSolRight(TPZVec<REAL> &solr,TPZVec<REAL> &soll,TPZVec<REAL> &normal,TPZBndCond *bcright);
void ComputeSolLeft(TPZVec<REAL> &solr,TPZVec<REAL> &soll,TPZVec<REAL> &normal,TPZBndCond *bcleft);
};
#endif
|
gems-uff/oceano
|
core/src/test/resources/CPP/neopz/Material/TPZConsLawTest.h
|
C
|
mit
| 3,234
|
package org.codehaus.modello.plugin.stax;
import org.codehaus.modello.model.ModelAssociation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/*
* Copyright (c) 2006, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
class GeneratorNode
{
private final String to;
private boolean referencableChildren;
private List<GeneratorNode> children = new LinkedList<GeneratorNode>();
private ModelAssociation association;
private boolean referencable;
private Map<String, GeneratorNode> nodesWithReferencableChildren = new HashMap<String, GeneratorNode>();
private List<String> chain;
GeneratorNode( String to, GeneratorNode parent )
{
this( to, parent, null );
}
GeneratorNode( ModelAssociation association, GeneratorNode parent )
{
this( association.getTo(), parent, association );
}
private GeneratorNode( String to, GeneratorNode parent, ModelAssociation association )
{
this.to = to;
this.association = association;
this.chain = parent != null ? new ArrayList<String>( parent.getChain() ) : new ArrayList<String>();
this.chain.add( to );
}
public boolean isReferencableChildren()
{
return referencableChildren;
}
public void setReferencableChildren( boolean referencableChildren )
{
this.referencableChildren = referencableChildren;
}
public void addChild( GeneratorNode child )
{
children.add( child );
if ( child.referencableChildren )
{
nodesWithReferencableChildren.put( child.to, child );
}
}
public List<GeneratorNode> getChildren()
{
return children;
}
public String toString()
{
return "to = " + to + "; referencableChildren = " + referencableChildren + "; children = " + children;
}
public String getTo()
{
return to;
}
public ModelAssociation getAssociation()
{
return association;
}
public void setAssociation( ModelAssociation association )
{
this.association = association;
}
public void setReferencable( boolean referencable )
{
this.referencable = referencable;
}
public boolean isReferencable()
{
return referencable;
}
public Map<String, GeneratorNode> getNodesWithReferencableChildren()
{
return nodesWithReferencableChildren;
}
public void addNodesWithReferencableChildren( Map<String, GeneratorNode> allChildNodes )
{
this.nodesWithReferencableChildren.putAll( allChildNodes );
}
public List<String> getChain()
{
return chain;
}
}
|
codehaus-plexus/modello
|
modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/GeneratorNode.java
|
Java
|
mit
| 3,803
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
#include BLIK_OPENCV_U_opencv2__photo_hpp //original-code:"opencv2/photo.hpp"
#include <iostream>
#include <stdlib.h>
#include "npr.hpp"
using namespace std;
using namespace cv;
void cv::edgePreservingFilter(InputArray _src, OutputArray _dst, int flags, float sigma_s, float sigma_r)
{
Mat I = _src.getMat();
_dst.create(I.size(), CV_8UC3);
Mat dst = _dst.getMat();
int h = I.size().height;
int w = I.size().width;
Mat res = Mat(h,w,CV_32FC3);
dst.convertTo(res,CV_32FC3,1.0/255.0);
Domain_Filter obj;
Mat img = Mat(I.size(),CV_32FC3);
I.convertTo(img,CV_32FC3,1.0/255.0);
obj.filter(img, res, sigma_s, sigma_r, flags);
convertScaleAbs(res, dst, 255,0);
}
void cv::detailEnhance(InputArray _src, OutputArray _dst, float sigma_s, float sigma_r)
{
Mat I = _src.getMat();
_dst.create(I.size(), CV_8UC3);
Mat dst = _dst.getMat();
int h = I.size().height;
int w = I.size().width;
float factor = 3.0f;
Mat img = Mat(I.size(),CV_32FC3);
I.convertTo(img,CV_32FC3,1.0/255.0);
Mat res = Mat(h,w,CV_32FC1);
dst.convertTo(res,CV_32FC3,1.0/255.0);
Mat result = Mat(img.size(),CV_32FC3);
Mat lab = Mat(img.size(),CV_32FC3);
vector <Mat> lab_channel;
cvtColor(img,lab,COLOR_BGR2Lab);
split(lab,lab_channel);
Mat L = Mat(img.size(),CV_32FC1);
lab_channel[0].convertTo(L,CV_32FC1,1.0/255.0);
Domain_Filter obj;
obj.filter(L, res, sigma_s, sigma_r, 1);
Mat detail = Mat(h,w,CV_32FC1);
detail = L - res;
multiply(detail,factor,detail);
L = res + detail;
L.convertTo(lab_channel[0],CV_32FC1,255);
merge(lab_channel,lab);
cvtColor(lab,result,COLOR_Lab2BGR);
result.convertTo(dst,CV_8UC3,255);
}
void cv::pencilSketch(InputArray _src, OutputArray _dst1, OutputArray _dst2, float sigma_s, float sigma_r, float shade_factor)
{
Mat I = _src.getMat();
_dst1.create(I.size(), CV_8UC1);
Mat dst1 = _dst1.getMat();
_dst2.create(I.size(), CV_8UC3);
Mat dst2 = _dst2.getMat();
Mat img = Mat(I.size(),CV_32FC3);
I.convertTo(img,CV_32FC3,1.0/255.0);
Domain_Filter obj;
Mat sketch = Mat(I.size(),CV_32FC1);
Mat color_sketch = Mat(I.size(),CV_32FC3);
obj.pencil_sketch(img, sketch, color_sketch, sigma_s, sigma_r, shade_factor);
sketch.convertTo(dst1,CV_8UC1,255);
color_sketch.convertTo(dst2,CV_8UC3,255);
}
void cv::stylization(InputArray _src, OutputArray _dst, float sigma_s, float sigma_r)
{
Mat I = _src.getMat();
_dst.create(I.size(), CV_8UC3);
Mat dst = _dst.getMat();
Mat img = Mat(I.size(),CV_32FC3);
I.convertTo(img,CV_32FC3,1.0/255.0);
int h = img.size().height;
int w = img.size().width;
Mat res = Mat(h,w,CV_32FC3);
Mat magnitude = Mat(h,w,CV_32FC1);
Domain_Filter obj;
obj.filter(img, res, sigma_s, sigma_r, NORMCONV_FILTER);
obj.find_magnitude(res,magnitude);
Mat stylized = Mat(h,w,CV_32FC3);
vector <Mat> temp;
split(res,temp);
multiply(temp[0],magnitude,temp[0]);
multiply(temp[1],magnitude,temp[1]);
multiply(temp[2],magnitude,temp[2]);
merge(temp,stylized);
stylized.convertTo(dst,CV_8UC3,255);
}
|
BonexGu/Blik2D-SDK
|
Blik2D/addon/opencv-3.1.0_for_blik/modules/photo/src/npr.cpp
|
C++
|
mit
| 5,323
|
import re
from .base import EventBuilder
from .._misc import utils
from .. import _tl
from ..types import _custom
class NewMessage(EventBuilder, _custom.Message):
"""
Represents the event of a new message. This event can be treated
to all effects as a `Message <telethon.tl.custom.message.Message>`,
so please **refer to its documentation** to know what you can do
with this event.
Members:
message (`Message <telethon.tl.custom.message.Message>`):
This is the only difference with the received
`Message <telethon.tl.custom.message.Message>`, and will
return the `telethon.tl.custom.message.Message` itself,
not the text.
See `Message <telethon.tl.custom.message.Message>` for
the rest of available members and methods.
pattern_match (`obj`):
The resulting object from calling the passed ``pattern`` function.
Here's an example using a string (defaults to regex match):
>>> from telethon import TelegramClient, events
>>> client = TelegramClient(...)
>>>
>>> @client.on(events.NewMessage(pattern=r'hi (\\w+)!'))
... async def handler(event):
... # In this case, the result is a ``Match`` object
... # since the `str` pattern was converted into
... # the ``re.compile(pattern).match`` function.
... print('Welcomed', event.pattern_match.group(1))
...
>>>
Example
.. code-block:: python
import asyncio
from telethon import events
@client.on(events.NewMessage(pattern='(?i)hello.+'))
async def handler(event):
# Respond whenever someone says "Hello" and something else
await event.reply('Hey!')
@client.on(events.NewMessage(outgoing=True, pattern='!ping'))
async def handler(event):
# Say "!pong" whenever you send "!ping", then delete both messages
m = await event.respond('!pong')
await asyncio.sleep(5)
await client.delete_messages(event.chat_id, [event.id, m.id])
"""
@classmethod
def _build(cls, client, update, entities):
if isinstance(update,
(_tl.UpdateNewMessage, _tl.UpdateNewChannelMessage)):
if not isinstance(update.message, _tl.Message):
return # We don't care about MessageService's here
msg = update.message
elif isinstance(update, _tl.UpdateShortMessage):
msg = _tl.Message(
out=update.out,
mentioned=update.mentioned,
media_unread=update.media_unread,
silent=update.silent,
id=update.id,
peer_id=_tl.PeerUser(update.user_id),
from_id=_tl.PeerUser(self_id if update.out else update.user_id),
message=update.message,
date=update.date,
fwd_from=update.fwd_from,
via_bot_id=update.via_bot_id,
reply_to=update.reply_to,
entities=update.entities,
ttl_period=update.ttl_period
)
elif isinstance(update, _tl.UpdateShortChatMessage):
msg = _tl.Message(
out=update.out,
mentioned=update.mentioned,
media_unread=update.media_unread,
silent=update.silent,
id=update.id,
from_id=_tl.PeerUser(self_id if update.out else update.from_id),
peer_id=_tl.PeerChat(update.chat_id),
message=update.message,
date=update.date,
fwd_from=update.fwd_from,
via_bot_id=update.via_bot_id,
reply_to=update.reply_to,
entities=update.entities,
ttl_period=update.ttl_period
)
else:
return
return cls._new(client, msg, entities, None)
|
LonamiWebs/Telethon
|
telethon/_events/newmessage.py
|
Python
|
mit
| 4,114
|
<html>
<head>
<style type='text/css'>
html, body, div, span, p, blockquote, pre {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-weight: inherit;
font-style: inherit;
font-size: 100%;
font-family: inherit;
vertical-align: baseline;
}
body{
line-height: 1;
color: black;
background: white;
margin-left: 20px;
}
.src {
border: 1px solid #dddddd;
padding-top: 10px;
padding-right: 5px;
padding-left: 5px;
}
.covered {background-color: #ddffdd}
.uncovered {background-color: #ffdddd}
.killed {background-color: #aaffaa}
.survived {background-color: #ffaaaa}
.uncertain {background-color: #dde7ef}
.run_error {background-color: #dde7ef}
.na {background-color: #eeeeee}
.timed_out {background-color: #dde7ef}
.non_viable {background-color: #aaffaa}
.memory_error {background-color: #dde7ef}
.not_started {background-color: #dde7ef; color : red}
.no_coverage {background-color: #ffaaaa}
</style>
</head>
<body>
<h1>RotateCommand.java</h1>
<table class="src">
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_1'/>
1
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_1'></a>
</td>
<td class=''><pre><span class=''></span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_2'/>
2
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_2'></a>
</td>
<td class=''><pre><span class=''>package com.github.tilastokeskus.matertis.core.command;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_3'/>
3
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_3'></a>
</td>
<td class=''><pre><span class=''></span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_4'/>
4
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_4'></a>
</td>
<td class=''><pre><span class=''>import com.github.tilastokeskus.matertis.core.GameHandler;</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_5'/>
5
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_5'></a>
</td>
<td class=''><pre><span class=''></span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_6'/>
6
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_6'></a>
</td>
<td class=''><pre><span class=''>/**</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_7'/>
7
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_7'></a>
</td>
<td class=''><pre><span class=''> * Command to rotate a tetromino. Command is not executed if game is not</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_8'/>
8
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_8'></a>
</td>
<td class=''><pre><span class=''> * running.</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_9'/>
9
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_9'></a>
</td>
<td class=''><pre><span class=''> * </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_10'/>
10
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_10'></a>
</td>
<td class=''><pre><span class=''> * @author tilastokeskus</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_11'/>
11
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_11'></a>
</td>
<td class=''><pre><span class=''> * @see com.github.tilastokeskus.matertis.core.Tetromino</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_12'/>
12
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_12'></a>
</td>
<td class=''><pre><span class=''> * @see com.github.tilastokeskus.matertis.core.Game</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_13'/>
13
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_13'></a>
</td>
<td class=''><pre><span class=''> */</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_14'/>
14
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_14'></a>
</td>
<td class=''><pre><span class=''>public class RotateCommand implements Command {</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_15'/>
15
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_15'></a>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_16'/>
16
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_16'></a>
</td>
<td class=''><pre><span class=''> private final GameHandler gameHandler; </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_17'/>
17
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_17'></a>
</td>
<td class=''><pre><span class=''> </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_18'/>
18
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_18'></a>
</td>
<td class=''><pre><span class=''> /**</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_19'/>
19
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_19'></a>
</td>
<td class=''><pre><span class=''> * Constructs a rotate command with the given game handler.</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_20'/>
20
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_20'></a>
</td>
<td class=''><pre><span class=''> * </span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_21'/>
21
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_21'></a>
</td>
<td class=''><pre><span class=''> * @param gameHandler game handler to be informed.</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_22'/>
22
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_22'></a>
</td>
<td class=''><pre><span class=''> */</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_23'/>
23
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_23'></a>
</td>
<td class='covered'><pre><span class=''> public RotateCommand(GameHandler gameHandler) {</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_24'/>
24
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_24'></a>
</td>
<td class='covered'><pre><span class=''> this.gameHandler = gameHandler;</span></pre></td></tr>
<tr>
<td class='covered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_25'/>
25
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_25'></a>
</td>
<td class='covered'><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_26'/>
26
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_26'></a>
</td>
<td class=''><pre><span class=''></span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_27'/>
27
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_27'></a>
</td>
<td class=''><pre><span class=''> /**</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_28'/>
28
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_28'></a>
</td>
<td class=''><pre><span class=''> * {@inheritDoc Command}</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_29'/>
29
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_29'></a>
</td>
<td class=''><pre><span class=''> * <p></span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_30'/>
30
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_30'></a>
</td>
<td class=''><pre><span class=''> * Rotates the game's falling tetromino.</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_31'/>
31
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_31'></a>
</td>
<td class=''><pre><span class=''> */</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_32'/>
32
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_32'></a>
</td>
<td class=''><pre><span class=''> @Override</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_33'/>
33
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_33'></a>
</td>
<td class=''><pre><span class=''> public void execute() {</span></pre></td></tr>
<tr>
<td class='uncovered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_34'/>
34
</td>
<td class='survived'>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_34'>1</a>
</td>
<td class='uncovered'><pre><span class='survived'> if (gameHandler.isRunning()) {</span></pre></td></tr>
<tr>
<td class='uncovered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_35'/>
35
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_35'></a>
</td>
<td class='uncovered'><pre><span class=''> gameHandler.getGame().rotateFallingTetromino();</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_36'/>
36
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_36'></a>
</td>
<td class=''><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='uncovered'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_37'/>
37
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_37'></a>
</td>
<td class='uncovered'><pre><span class=''> }</span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_38'/>
38
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_38'></a>
</td>
<td class=''><pre><span class=''></span></pre></td></tr>
<tr>
<td class='na'>
<a name='org.pitest.mutationtest.report.html.SourceFile@4444ad54_39'/>
39
</td>
<td class=''>
<a href='#grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_39'></a>
</td>
<td class=''><pre><span class=''>}</span></pre></td></tr>
<tr><td></td><td></td><td><h2>Mutations</h2></td></tr>
<tr>
<td><a href='#org.pitest.mutationtest.report.html.SourceFile@4444ad54_34'>34</a></td>
<td></td>
<td>
<a name='grouporg.pitest.mutationtest.report.html.SourceFile@4444ad54_34'/>
<p class='NO_COVERAGE'>negated conditional : NO_COVERAGE</p>
</td>
</tr>
</table>
<h2>Active mutators</h2>
<ul>
<li class='mutator'>INCREMENTS_MUTATOR</li>
<li class='mutator'>CONDITIONALS_BOUNDARY_MUTATOR</li>
<li class='mutator'>RETURN_VALS_MUTATOR</li>
<li class='mutator'>VOID_METHOD_CALL_MUTATOR</li>
<li class='mutator'>INVERT_NEGS_MUTATOR</li>
<li class='mutator'>MATH_MUTATOR</li>
<li class='mutator'>NEGATE_CONDITIONALS_MUTATOR</li>
</ul>
<h2>Tests examined</h2>
<ul>
</ul>
<br/>
Report generated by <a href='http://pitest.org'>PIT</a> 0.30
</body>
</html>
|
tilastokeskus/Matertis
|
dist/pit/com.github.tilastokeskus.matertis.core.command/RotateCommand.java.html
|
HTML
|
mit
| 13,035
|
package com.alternative.bank.gui.login;
import com.alternative.bank.api.oauth2.OAuth2TokenService;
import com.alternative.bank.api.usagers.UsagersApiService;
import com.alternative.bank.objets.Usager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.Set;
/**
* Created by yannic on 16/03/17.
*/
@Component
public class CustomUserDetailsService implements UserDetailsService {
private static Logger log = LoggerFactory.getLogger(CustomUserDetailsService.class);
@Autowired
UsagersApiService usagersApiService;
@Autowired
OAuth2TokenService oAuth2TokenService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// check username against rules (regex)
Usager usager = usagersApiService.findUsagerByUsername(username);
if (usager != null) {
log.info("Successful login for " + usager.getUsername());
return new User(usager.getUsername(), usager.getPassword(), createUserAuthority());
} else {
log.warn("Login failed for " + username);
throw new UsernameNotFoundException("invalid user");
}
}
private Set<GrantedAuthority> createUserAuthority(){
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("USER");
authorities.add(grantedAuthority);
return authorities;
}
}
|
yannicl/alternative-bank
|
gui/src/main/java/com/alternative/bank/gui/login/CustomUserDetailsService.java
|
Java
|
mit
| 2,042
|
<?php
/* admin/edit.html.twig */
class __TwigTemplate_00fc34ea50d14d9f63a20625a3cb2f47676a6678f50f1beeb92201f047383a01 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
// line 1
$this->parent = $this->loadTemplate("base.html.twig", "admin/edit.html.twig", 1);
$this->blocks = array(
'body' => array($this, 'block_body'),
);
}
protected function doGetParent(array $context)
{
return "base.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$__internal_52033eb8ace8553380bccf8bcaa1edc10af51d5114d19b07f8ef5cf33a9b638b = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension");
$__internal_52033eb8ace8553380bccf8bcaa1edc10af51d5114d19b07f8ef5cf33a9b638b->enter($__internal_52033eb8ace8553380bccf8bcaa1edc10af51d5114d19b07f8ef5cf33a9b638b_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "admin/edit.html.twig"));
$__internal_0bce8eeaeb5e708ef91c062defe888a5e47bf21fa3d2a49260ac30d727e96609 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
$__internal_0bce8eeaeb5e708ef91c062defe888a5e47bf21fa3d2a49260ac30d727e96609->enter($__internal_0bce8eeaeb5e708ef91c062defe888a5e47bf21fa3d2a49260ac30d727e96609_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "admin/edit.html.twig"));
$this->parent->display($context, array_merge($this->blocks, $blocks));
$__internal_52033eb8ace8553380bccf8bcaa1edc10af51d5114d19b07f8ef5cf33a9b638b->leave($__internal_52033eb8ace8553380bccf8bcaa1edc10af51d5114d19b07f8ef5cf33a9b638b_prof);
$__internal_0bce8eeaeb5e708ef91c062defe888a5e47bf21fa3d2a49260ac30d727e96609->leave($__internal_0bce8eeaeb5e708ef91c062defe888a5e47bf21fa3d2a49260ac30d727e96609_prof);
}
// line 3
public function block_body($context, array $blocks = array())
{
$__internal_bf5129d6a47cc4df945da9865602d5f9d158e96d4068df8df9487672e9fdf3c5 = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension");
$__internal_bf5129d6a47cc4df945da9865602d5f9d158e96d4068df8df9487672e9fdf3c5->enter($__internal_bf5129d6a47cc4df945da9865602d5f9d158e96d4068df8df9487672e9fdf3c5_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "body"));
$__internal_a958414f3324bba1552b63381f5ea4586cd7165c9b001c8a8f85496231059159 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
$__internal_a958414f3324bba1552b63381f5ea4586cd7165c9b001c8a8f85496231059159->enter($__internal_a958414f3324bba1552b63381f5ea4586cd7165c9b001c8a8f85496231059159_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "body"));
// line 4
echo " <section class=\"main_content\">
<table>
<tr>
<th>Update a User</th>
</tr>
";
// line 10
echo $this->env->getRuntime('Symfony\Bridge\Twig\Form\TwigRenderer')->renderBlock(($context["edit_form"] ?? $this->getContext($context, "edit_form")), 'form_start');
echo "
<tr>
<td> ";
// line 12
echo $this->env->getRuntime('Symfony\Bridge\Twig\Form\TwigRenderer')->searchAndRenderBlock($this->getAttribute(($context["edit_form"] ?? $this->getContext($context, "edit_form")), "email", array()), 'row');
echo "</td>
</tr>
<tr>
<td> ";
// line 15
echo $this->env->getRuntime('Symfony\Bridge\Twig\Form\TwigRenderer')->searchAndRenderBlock($this->getAttribute($this->getAttribute(($context["edit_form"] ?? $this->getContext($context, "edit_form")), "plainPassword", array()), "first", array()), 'row', array("label" => "Password"));
// line 17
echo "</td>
</tr>
<tr>
<td> ";
// line 20
echo $this->env->getRuntime('Symfony\Bridge\Twig\Form\TwigRenderer')->searchAndRenderBlock($this->getAttribute($this->getAttribute(($context["edit_form"] ?? $this->getContext($context, "edit_form")), "plainPassword", array()), "second", array()), 'row', array("label" => "Repeat Password"));
// line 22
echo "</td>
</tr>
<tr>
<td> ";
// line 25
echo $this->env->getRuntime('Symfony\Bridge\Twig\Form\TwigRenderer')->searchAndRenderBlock($this->getAttribute(($context["edit_form"] ?? $this->getContext($context, "edit_form")), "roles", array()), 'row');
echo "</td>
</tr>
<tr>
<td> <button type=\"submit\" formnovalidate>Update User</button></td>
</tr>
";
// line 30
echo $this->env->getRuntime('Symfony\Bridge\Twig\Form\TwigRenderer')->renderBlock(($context["edit_form"] ?? $this->getContext($context, "edit_form")), 'form_end');
echo "
</table>
</section>
";
$__internal_a958414f3324bba1552b63381f5ea4586cd7165c9b001c8a8f85496231059159->leave($__internal_a958414f3324bba1552b63381f5ea4586cd7165c9b001c8a8f85496231059159_prof);
$__internal_bf5129d6a47cc4df945da9865602d5f9d158e96d4068df8df9487672e9fdf3c5->leave($__internal_bf5129d6a47cc4df945da9865602d5f9d158e96d4068df8df9487672e9fdf3c5_prof);
}
public function getTemplateName()
{
return "admin/edit.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 90 => 30, 82 => 25, 77 => 22, 75 => 20, 70 => 17, 68 => 15, 62 => 12, 57 => 10, 49 => 4, 40 => 3, 11 => 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("{% extends 'base.html.twig' %}
{% block body %}
<section class=\"main_content\">
<table>
<tr>
<th>Update a User</th>
</tr>
{{ form_start(edit_form) }}
<tr>
<td> {{ form_row(edit_form.email) }}</td>
</tr>
<tr>
<td> {{ form_row(edit_form.plainPassword.first, {
'label': 'Password'
}) }}</td>
</tr>
<tr>
<td> {{ form_row(edit_form.plainPassword.second, {
'label': 'Repeat Password'
}) }}</td>
</tr>
<tr>
<td> {{ form_row(edit_form.roles) }}</td>
</tr>
<tr>
<td> <button type=\"submit\" formnovalidate>Update User</button></td>
</tr>
{{ form_end(edit_form) }}
</table>
</section>
{% endblock %}", "admin/edit.html.twig", "C:\\laragon\\www\\web3_project\\app\\Resources\\views\\admin\\edit.html.twig");
}
}
|
lauramcloughlin/web3_project
|
var/cache/dev/twig/74/746281667de1798ac309c057d9e3e130c99f3971c9dce2f42a6cd2890508bcb6.php
|
PHP
|
mit
| 7,019
|
#!/bin/sh
COUNT=$1
/Users/jmarkert/ParallelTSP/dep/openmpi/bin/mpiexec --hostfile /Users/jmarkert/ParallelTSP/hostfile.txt -map-by node -np $COUNT /Users/jmarkert/ParallelTSP/build/src/simplega/simplega -c graph/cfg.json -n -q
|
AvS2016/ParallelTSP
|
start_tsp.sh
|
Shell
|
mit
| 229
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <iostream>
#include <atomic/UseCntPtr.h>
#include <sockets/Socket.h>
#include <sockets/LocalAddress.h>
#include <sockets/EndPoint.h>
#include <servers/MultiProcessMultiServiceServer.h>
using namespace ombt;
class MyHandler:
public MultiProcMSStreamServer::Handler
{
public:
MyHandler() { }
virtual ~MyHandler() { }
virtual int operator()(EndPoint &clientep)
{
char buf[BUFSIZ+1];
size_t count = BUFSIZ;
count = clientep.read(buf, count);
if (count > 0)
{
if (clientep.write(buf, count) > 0)
return(0);
else
{
DUMP(errno);
return(-1);
}
}
else if (count == 0)
return(1);
else
{
DUMP(errno);
return(-1);
}
}
};
int
main(int argc, char *argv[])
{
std::string filepath1("/tmp/xxxx");
std::string filepath2("/tmp/yyyy");
std::cout << "Creating Stream Socket 1 ..." << std::endl;
StreamSocket *stream_socket1 = new StreamSocket();
assert(stream_socket1->isOk());
std::cout << "Creating Local Address 1 ..." << filepath1 << std::endl;
::unlink(filepath1.c_str());
LocalAddress *my_address1 = new LocalAddress(filepath1);
assert(my_address1->isOk());
std::cout << "Creating Stream EndPoint 1 ..." << std::endl;
UseCntPtr<EndPoint> server_ep1(new EndPoint(stream_socket1, my_address1));
assert(server_ep1->isOk());
std::cout << "Creating Stream Socket 2 ..." << std::endl;
StreamSocket *stream_socket2 = new StreamSocket();
assert(stream_socket2->isOk());
std::cout << "Creating Local Address 2 ..." << filepath2 << std::endl;
::unlink(filepath2.c_str());
LocalAddress *my_address2 = new LocalAddress(filepath2);
assert(my_address2->isOk());
std::cout << "Creating Stream EndPoint 2 ..." << std::endl;
UseCntPtr<EndPoint> server_ep2(new EndPoint(stream_socket2, my_address2));
assert(server_ep2->isOk());
MyHandler handler1;
MyHandler handler2;
MultiProcMSStreamServer idg;
assert(idg.isOk());
idg.registerHandler(*server_ep1, handler1);
idg.registerHandler(*server_ep2, handler2);
idg.init();
idg.run();
idg.finish();
return(0);
}
|
ombt/ombt
|
old/testsrc/servers/streammpmsechoserver.cpp
|
C++
|
mit
| 2,375
|
// Copyright © 2018 Wave Engine S.L. All rights reserved. Use is subject to license terms.
#region Using Statements
using System;
using System.Runtime.InteropServices;
using WaveEngine.Common.Graphics;
using WaveEngine.Common.Graphics.VertexFormats;
using WaveEngine.Common.Math;
using WaveEngine.Framework.Graphics;
#endregion
namespace WaveEngine.ImageEffects
{
/// <summary>
/// Depth of field effect.
/// </summary>
public class DepthOfFieldMaterial : Material
{
/// <summary>
/// Effect's steps
/// </summary>
public enum Passes
{
/// <summary>
/// Down sampler
/// </summary>
DownSampler,
/// <summary>
/// The blur
/// </summary>
Blur,
/// <summary>
/// Combine
/// </summary>
Combine,
}
/// <summary>
/// Steps of this effects
/// </summary>
public Passes Pass;
/// <summary>
/// The pixel offset
/// </summary>
public Vector2 TexcoordOffset;
/// <summary>
/// The blur scale
/// </summary>
public float BlurScale;
/// <summary>
/// The texture
/// </summary>
private Texture texture;
/// <summary>
/// The texture1
/// </summary>
private Texture texture1;
/// <summary>
/// The depth texture
/// </summary>
private Texture depthTexture;
/// <summary>
/// The techniques
/// </summary>
private static ShaderTechnique[] techniques =
{
new ShaderTechnique("DownSampler", "ImageEffectMaterial", "ImageEffectvsImageEffect", string.Empty, "psDown", VertexPositionTexture.VertexFormat),
new ShaderTechnique("Blur", "vsBlur", "psBlur", VertexPositionTexture.VertexFormat),
new ShaderTechnique("Combine", "ImageEffectMaterial", "ImageEffectvsImageEffect", string.Empty, "psCombine", VertexPositionTexture.VertexFormat),
};
#region Struct
/// <summary>
/// Shader parameters.
/// </summary>
[StructLayout(LayoutKind.Explicit, Size = 32)]
private struct DOFEffectParameters
{
[FieldOffset(0)]
public Vector2 TexcoordOffset;
[FieldOffset(8)]
public float FocusDistance;
[FieldOffset(12)]
public float FocusRange;
[FieldOffset(16)]
public float NearPlane;
[FieldOffset(20)]
public float FarParam;
[FieldOffset(24)]
public float BlurScale;
}
#endregion
/// <summary>
/// Handle the shader parameters struct.
/// </summary>
private DOFEffectParameters shaderParameters;
#region Properties
/// <summary>
/// Gets or sets focus Distance
/// </summary>
public float FocusDistance { get; set; }
/// <summary>
/// Gets or sets focus range
/// </summary>
public float FocusRange { get; set; }
/// <summary>
/// Gets or sets the texture.
/// </summary>
/// <value>
/// The texture.
/// </value>
public Texture Texture
{
get
{
return this.texture;
}
set
{
if (value == null)
{
throw new NullReferenceException("Texture cannot be null.");
}
this.texture = value;
}
}
/// <summary>
/// Gets or sets the texture1.
/// </summary>
/// <value>
/// The texture1.
/// </value>
/// <exception cref="System.NullReferenceException">Texture cannot be null.</exception>
public Texture Texture1
{
get
{
return this.texture1;
}
set
{
this.texture1 = value;
}
}
/// <summary>
/// Gets the current technique.
/// </summary>
/// <value>
/// The current technique.
/// </value>
public override string CurrentTechnique
{
get
{
int index = (int)this.Pass;
return techniques[index].Name;
}
}
/// <summary>
/// Gets or sets the Depth Texture.
/// </summary>
public Texture DepthTexture
{
get
{
return this.depthTexture;
}
set
{
this.depthTexture = value;
}
}
#endregion
#region Initialize
/// <summary>
/// Initializes a new instance of the <see cref="DepthOfFieldMaterial"/> class.
/// </summary>
public DepthOfFieldMaterial()
: base(DefaultLayers.Opaque)
{
}
/// <summary>
/// Initialize default values for this instance.
/// </summary>
protected override void DefaultValues()
{
base.DefaultValues();
this.BlurScale = 4.0f;
this.FocusRange = 2;
this.FocusDistance = 4;
this.TexcoordOffset = Vector2.Zero;
this.shaderParameters = new DOFEffectParameters();
this.shaderParameters.TexcoordOffset = this.TexcoordOffset;
this.Parameters = this.shaderParameters;
this.InitializeTechniques(techniques);
}
/// <summary>
/// Initializes the specified assets.
/// </summary>
/// <param name="assets">The assets.</param>
public override void Initialize(WaveEngine.Framework.Services.AssetsContainer assets)
{
base.Initialize(assets);
}
#endregion
#region Public Methods
/// <summary>
/// Applies the pass.
/// </summary>
/// <param name="cached">The efect is cached.</param>
public override void SetParameters(bool cached)
{
if (!cached)
{
this.shaderParameters.TexcoordOffset = this.TexcoordOffset;
if (this.Pass == Passes.Combine)
{
Camera camera = this.renderManager.CurrentDrawingCamera;
this.shaderParameters.FocusDistance = this.FocusDistance;
this.shaderParameters.FocusRange = this.FocusRange;
this.shaderParameters.NearPlane = camera.NearPlane;
this.shaderParameters.FarParam = camera.FarPlane / (camera.FarPlane - camera.NearPlane);
this.shaderParameters.BlurScale = this.BlurScale;
this.Parameters = this.shaderParameters;
this.depthTexture = this.renderManager.GraphicsDevice.RenderTargets.DefaultDepthTexture;
if (this.depthTexture != null)
{
this.graphicsDevice.SetTexture(this.depthTexture, 2);
}
}
if (this.texture != null)
{
this.graphicsDevice.SetTexture(this.texture, 0);
}
if (this.texture1 != null)
{
this.graphicsDevice.SetTexture(this.texture1, 1);
}
}
}
#endregion
}
}
|
WaveEngine/Extensions
|
WaveEngine.ImageEffects/Shared/DepthOfField/DepthOfFieldMaterial.cs
|
C#
|
mit
| 7,688
|
<?php
namespace Admin\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* UsuarioCatalogo
*
* @ORM\Table(name="usuario_catalogo", indexes={@ORM\Index(name="Id_catalogo", columns={"Id_catalogo"}), @ORM\Index(name="Id_Usuario", columns={"Id_Usuario"})})
* @ORM\Entity
*/
class UsuarioCatalogo
{
/**
* @var integer
*
* @ORM\Column(name="Id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var \Catalogo
*
* @ORM\ManyToOne(targetEntity="Catalogo")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="Id_catalogo", referencedColumnName="Id_Cata")
* })
*/
private $idCatalogo;
/**
* @var \FosUser
*
* @ORM\ManyToOne(targetEntity="User")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="Id_Usuario", referencedColumnName="id")
* })
*/
private $idUsuario;
}
|
luisk262/mainevent
|
src/Admin/AdminBundle/Entity/UsuarioCatalogo.php
|
PHP
|
mit
| 948
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#pragma once
#include "CodeHeap.h"
#include <list>
#include <vector>
#include <unordered_map>
#include <mutex>
#if defined(_TARGET_AMD64_)
//
// ToDo - this should eventually come from windows header file.
//
// Define unwind code structure.
//
typedef union _UNWIND_CODE {
struct {
UCHAR CodeOffset;
UCHAR UnwindOp : 4;
UCHAR OpInfo : 4;
};
USHORT FrameOffset;
} UNWIND_CODE, *PUNWIND_CODE;
//
// Define unwind information flags.
//
#define UNW_FLAG_NHANDLER 0x0
#define UNW_FLAG_EHANDLER 0x1
#define UNW_FLAG_UHANDLER 0x2
#define UNW_FLAG_CHAININFO 0x4
typedef struct _UNWIND_INFO {
UCHAR Version : 3;
UCHAR Flags : 5;
UCHAR SizeOfProlog;
UCHAR CountOfUnwindCodes;
UCHAR FrameRegister : 4;
UCHAR FrameOffset : 4;
UNWIND_CODE UnwindCode[1];
} UNWIND_INFO, *PUNWIND_INFO;
typedef DPTR(struct _UNWIND_INFO) PTR_UNWIND_INFO;
typedef DPTR(union _UNWIND_CODE) PTR_UNWIND_CODE;
#endif // target_amd64
class ReaderWriterLock : private SRWLOCK
{
public:
ReaderWriterLock()
{
::InitializeSRWLock(this);
}
class ReadHolder
{
ReaderWriterLock * m_pLock;
public:
ReadHolder(ReaderWriterLock * pLock)
: m_pLock(pLock)
{
::AcquireSRWLockShared(m_pLock);
}
~ReadHolder()
{
::ReleaseSRWLockShared(m_pLock);
}
};
class WriteHolder
{
ReaderWriterLock * m_pLock;
public:
WriteHolder(ReaderWriterLock * pLock)
: m_pLock(pLock)
{
::AcquireSRWLockExclusive(m_pLock);
}
~WriteHolder()
{
::ReleaseSRWLockExclusive(m_pLock);
}
};
};
typedef DPTR(RUNTIME_FUNCTION) PTR_RUNTIME_FUNCTION;
// TODO: Not compatible with Windows 7
// #ifdef _TARGET_AMD64_
// #define USE_GROWABLE_FUNCTION_TABLE 1
// #endif
class CodeHeader
{
public:
CodeHeader(void *m_heapBase, DWORD codeOffs);
~CodeHeader();
void *operator new (size_t sz, void *mem)
{
return mem;
}
inline void *GetCode() const
{
return m_heapBase + m_codeOffset;
}
inline DWORD GetCodeOffset() const
{
return m_codeOffset;
}
inline void *GetHeapBase() const
{
return m_heapBase;
}
inline void SetEHInfo(void *ehInfo)
{
m_ehInfo = ehInfo;
}
inline void *GetEHInfo() const
{
return m_ehInfo;
}
inline size_t GetEHCount() const
{
size_t *ptr = (size_t*)GetEHInfo();
assert(ptr != NULL);
return *(ptr - 1);
}
inline EHClause *GetEHClause(unsigned i)
{
assert(i < GetEHCount());
EHClause *ehInfo = (EHClause*)GetEHInfo();
return &ehInfo[i];
}
private:
BYTE *m_heapBase;
DWORD m_codeOffset;
// Exception handling clauses
// Storage layout: <Number of EH clauses><Clause1>...<ClauseN>
// m_ehInfo will be pointing to the first clause.
// Number of EH clauses = *((size_t*)((byte*) m_ehInfo - sizeof(size_t)))
void *m_ehInfo;
};
class JITCodeManager : ICodeManager
{
PTR_VOID m_pvStartRange;
UInt32 m_cbRange;
// lock to protect m_runtimeFunctions and m_FuncletToMainMethodMap
ReaderWriterLock m_lock;
std::vector<RUNTIME_FUNCTION> m_runtimeFunctions;
PTR_RUNTIME_FUNCTION m_pRuntimeFunctionTable;
UInt32 m_nRuntimeFunctionTable;
#ifdef USE_GROWABLE_FUNCTION_TABLE
PTR_VOID m_hGrowableFunctionTable;
#endif
// Given BeginAddress of a funclet, this data structure maps to
// BeginAddress of its main method.
std::unordered_map<DWORD, DWORD> m_FuncletToMainMethodMap;
// For now we are using the desktop concept of multiple CodeManagers for multiple ranges
// of JIT'ed code. The current implementation is meant to be the simplest possible so
// that it will be easy to refactor into a better/more permanent version later.
ExecutableCodeHeap m_codeHeap;
static std::list<JITCodeManager*> s_instances;
static JITCodeManager * volatile s_pLastCodeManager;
static std::mutex s_instanceLock;
typedef std::lock_guard<std::mutex> MutexHolder;
// Get the code header given method's start address
static inline CodeHeader* GetCodeHeader(void *methodStart)
{
return (CodeHeader*)((BYTE*)methodStart - sizeof(CodeHeader));
}
public:
// Finds the code manager associated with a particular address.
static JITCodeManager *FindCodeManager(PTR_VOID addr);
// Finds a JITCodeManager instance with free space and allocates executable memory.
// This function throws on failure, and passes out the code address and JIT manager used.
static void AllocCode(size_t size, DWORD align, void **ppCode, JITCodeManager **ppManager);
public:
JITCodeManager();
~JITCodeManager();
bool Initialize();
void *AllocPData(size_t size)
{
return m_codeHeap.AllocPData(size);
}
void *AllocEHInfo(CodeHeader *hdr, unsigned cEH)
{
size_t size = sizeof(size_t)+sizeof(struct EHClause) * cEH;
size_t *ehInfo = (size_t *)m_codeHeap.AllocEHInfoRaw(size);
*ehInfo = cEH;
hdr->SetEHInfo(ehInfo + 1);
return ehInfo;
}
PTR_RUNTIME_FUNCTION AllocRuntimeFunction(PTR_RUNTIME_FUNCTION mainMethod, DWORD beginAddr, DWORD endAddr, DWORD unwindData);
inline bool Contains(void *pCode) const
{
return m_pvStartRange <= pCode && pCode < (void*)((BYTE*)m_pvStartRange + m_cbRange);
}
void UpdateRuntimeFunctionTable();
//
// Code manager methods
//
bool FindMethodInfo(PTR_VOID ControlPC,
MethodInfo * pMethodInfoOut);
bool IsFunclet(MethodInfo * pMethodInfo);
PTR_VOID GetFramePointer(MethodInfo * pMethodInfo,
REGDISPLAY * pRegisterSet);
void EnumGcRefs(MethodInfo * pMethodInfo,
PTR_VOID safePointAddress,
REGDISPLAY * pRegisterSet,
GCEnumContext * hCallback);
bool UnwindStackFrame(MethodInfo * pMethodInfo,
REGDISPLAY * pRegisterSet, // in/out
PTR_VOID * ppPreviousTransitionFrame); // out
bool GetReturnAddressHijackInfo(MethodInfo * pMethodInfo,
REGDISPLAY * pRegisterSet, // in
PTR_PTR_VOID * ppvRetAddrLocation, // out
GCRefKind * pRetValueKind); // out
void UnsynchronizedHijackMethodLoops(MethodInfo * pMethodInfo);
PTR_VOID RemapHardwareFaultToGCSafePoint(MethodInfo * pMethodInfo, PTR_VOID controlPC);
bool EHEnumInit(MethodInfo * pMethodInfo, PTR_VOID * pMethodStartAddress, EHEnumState * pEHEnumState);
bool EHEnumNext(EHEnumState * pEHEnumState, EHClause * pEHClause);
UIntNative GetConservativeUpperBoundForOutgoingArgs(MethodInfo * pMethodInfo,
REGDISPLAY * pRegisterSet);
PTR_VOID GetMethodStartAddress(MethodInfo * pMethodInfo);
void * GetClasslibFunction(ClasslibFunctionId functionId);
PTR_VOID GetAssociatedData(PTR_VOID ControlPC);
};
|
shrah/corert
|
src/Native/jitinterface/JITCodeManager.h
|
C
|
mit
| 7,550
|
use std::env;
use std::io::Read;
use std::fs::File;
use std::path::Path;
use std::path::PathBuf;
use std::collections::HashMap;
use std::collections::HashSet;
fn main() {
let mut data_path: PathBuf = env::current_dir().unwrap();
data_path.push("data");
data_path.push("input.txt");
let directions: Vec<String> = data_from_file(&data_path).unwrap();
let longest_distance: i32 = longest_block_distance(&directions).unwrap();
let distance_to_reoccurance: i32 =
first_reoccuring_block_distance(&directions).unwrap();
println!("Answer 1: {}", longest_distance);
println!("Answer 2: {}", distance_to_reoccurance);
}
pub fn data_from_file<P>(file_name: &P) -> Result<Vec<String>, std::io::Error>
where P: AsRef<Path> {
let mut data_file: File = File::open(file_name)?;
let mut data_line: String = String::new();
data_file.read_to_string(&mut data_line)?;
let data: Vec<String> = data_line.trim()
.split(", ")
.map(|str_literal| str_literal.to_owned())
.collect();
Ok(data)
}
pub fn longest_block_distance(directions: &Vec<String>) -> Result<i32, String> {
let mut index: i32 = 0;
let mut ew_parity: i32 = 1;
let mut ns_parity: i32 = 1;
let mut direction_parity_table: HashMap<char, i32> = HashMap::new();
direction_parity_table.insert('R', 1);
direction_parity_table.insert('L', -1);
let mut travel_location: [i32; 2] = [0, 0];
for direction in directions {
let direction_char: char =
direction
.chars().nth(0).ok_or("Direction is empty!".to_owned())?;
let direction_parity: &i32 =
direction_parity_table
.get(&direction_char)
.ok_or("Direction not in parity table!".to_owned())?;
let distance: i32 =
(&direction[1..]).parse::<i32>().map_err(|e| e.to_string())?;
if index % 2 == 0 {
if ns_parity == 1 {
ew_parity = *direction_parity;
} else {
ew_parity = -1 * (*direction_parity);
}
travel_location[1] += ew_parity * distance;
} else {
if ew_parity == 1 {
ns_parity = -1 * (*direction_parity);
} else {
ns_parity = *direction_parity;
}
travel_location[0] += ns_parity * distance;
}
index += 1;
}
Ok(travel_location[0].abs() + travel_location[1].abs())
}
pub fn first_reoccuring_block_distance(directions: &Vec<String>)
-> Result<i32, String> {
let mut index: i32 = 0;
let mut ew_parity: i32 = 1;
let mut ns_parity: i32 = 1;
let mut direction_parity_table: HashMap<char, i32> = HashMap::new();
direction_parity_table.insert('R', 1);
direction_parity_table.insert('L', -1);
let mut travel_location: [i32; 2] = [0, 0];
let mut locations_visited: HashSet<[i32; 2]> = HashSet::new();
locations_visited.insert(travel_location);
for direction in directions {
let direction_char: char =
direction
.chars().nth(0).ok_or("Direction is empty!".to_owned())?;
let direction_parity: &i32 =
direction_parity_table
.get(&direction_char)
.ok_or("Direction not in parity table!".to_owned())?;
let distance: i32 =
(&direction[1..]).parse::<i32>().map_err(|e| e.to_string())?;
if index % 2 == 0 {
if ns_parity == 1 {
ew_parity = *direction_parity;
} else {
ew_parity = -1 * (*direction_parity);
}
let mut travel_from: i32 = travel_location[1];
travel_location[1] += ew_parity * distance;
let travel_to: i32 = travel_location[1];
while travel_from != travel_to {
travel_from += ew_parity;
let temp_location: [i32; 2] =
[travel_location[0], travel_from];
if locations_visited.contains(&temp_location) {
return Ok(temp_location[0].abs() + temp_location[1].abs());
}
locations_visited.insert(temp_location);
}
} else {
if ew_parity == 1 {
ns_parity = -1 * (*direction_parity);
} else {
ns_parity = *direction_parity;
}
let mut travel_from: i32 = travel_location[0];
travel_location[0] += ns_parity * distance;
let travel_to: i32 = travel_location[0];
while travel_from != travel_to {
travel_from += ns_parity;
let temp_location: [i32; 2] =
[travel_from, travel_location[1]];
if locations_visited.contains(&temp_location) {
return Ok(temp_location[0].abs() + temp_location[1].abs());
}
locations_visited.insert(temp_location);
}
}
index += 1;
}
Err("There is no intersection!".to_owned())
}
// Testing
#[cfg(test)]
mod tests {
use super::*;
use std::env;
use std::path::PathBuf;
#[test]
fn test_data_from_file() {
let data_string: String = (
"R1, R3, L2, L5, L2, L1, R3, L4, R2, L2, L4, R2, L1, R1, L2, R3, \
L1, L4, R2, L5, R3, R4, L1, R2, L1, R3, L4, R5, L4, L5, R5, L3, \
R2, L3, L3, R1, R3, L4, R2, R5, L4, R1, L1, L1, R5, L2, R1, L2, \
R188, L5, L3, R5, R1, L2, L4, R3, R5, L3, R3, R45, L4, R4, R72, \
R2, R3, L1, R1, L1, L1, R192, L1, L1, L1, L4, R1, L2, L5, L3, R5, \
L3, R3, L4, L3, R1, R4, L2, R2, R3, L5, R3, L1, R1, R4, L2, L3, \
R1, R3, L4, L3, L4, L2, L2, R1, R3, L5, L1, R4, R2, L4, L1, R3, \
R3, R1, L5, L2, R4, R4, R2, R1, R5, R5, L4, L1, R5, R3, R4, R5, \
R3, L1, L2, L4, R1, R4, R5, L2, L3, R4, L4, R2, L2, L4, L2, R5, \
R1, R4, R3, R5, L4, L4, L5, L5, R3, R4, L1, L3, R2, L2, R1, L3, \
L5, R5, R5, R3, L4, L2, R4, R5, R1, R4, L3").to_owned();
let data_vec: Vec<String> = data_string.split(", ")
.map(|s| s.to_owned())
.collect();
let mut data_path: PathBuf = env::current_dir().unwrap();
data_path.push("data");
data_path.push("input.txt");
assert_eq!(data_from_file(&data_path).unwrap(), data_vec);
}
#[test]
fn test_longest_distance() {
assert_eq!(
longest_block_distance(
&(vec!["R2".to_owned(), "L3".to_owned()])).unwrap(), 5);
assert_eq!(
longest_block_distance(
&(vec!["R2".to_owned(), "R2".to_owned(), "R2".to_owned()]))
.unwrap(),
2);
assert_eq!(
longest_block_distance(
&(vec![
"R5".to_owned(), "L5".to_owned(), "R5".to_owned(),
"R3".to_owned()]))
.unwrap(),
12);
}
#[test]
fn test_first_reoccuring_block_distance() {
let test_vec: Vec<String> =
vec!["R8".to_owned(), "R4".to_owned(), "R4".to_owned(),
"R8".to_owned()];
assert_eq!(first_reoccuring_block_distance(&test_vec).unwrap(), 4);
}
}
|
DirtGrubDylan/advent_of_code_2106
|
rust/day_1/src/main.rs
|
Rust
|
mit
| 7,518
|
using Castle.Core.Logging;
using Bivi.Infrastructure.Services.Depots;
using Bivi.Infrastructure.Services.Encryption;
using Bivi.BackOffice.Web.Controllers.Modularity;
using Bivi.BackOffice.Web.ViewModels.ModelBuilders.Administration.Profil;
using Bivi.BackOffice.Web.ViewModels.ModelBuilders.Common;
using System.Web.Mvc;
using Bivi.Infrastructure.Constant;
using Bivi.BackOffice.Web.Controllers.Helpers;
using Bivi.Infrastructure.Extensions;
using Bivi.BackOffice.Web.Controllers.Filters;
using Bivi.BackOffice.Web.ViewModels.Pages.Administration.Profil.Details;
using Bivi.Domaine.Composite;
using Bivi.BackOffice.Web.Controllers.ActionResults;
using System.Net;
using Bivi.BackOffice.Web.ViewModels.Pages;
using System.Collections.Generic;
using System.Transactions;
using Bivi.Infrastructure.Attributes.Modularity;
using Bivi.Domaine.Criterias;
using Bivi.Infrastructure.Services.Caching;
using Bivi.Infrastructure.Services.Exports;
using Bivi.BackOffice.Web.ViewModels.Pages.Common;
namespace Bivi.BackOffice.Web.Controllers.Administration
{
public class ProfilController : ModularController
{
private readonly IProfilModelBuilder _profilModelBuilder;
public ProfilController(
ILogger logger,
ICryptography encryption,
IDepotFactory depotFactory,
IProfilModelBuilder profilModelBuilder,
ICommonModelBuilder commonModelBuilder,
ICaching cachingService,
IExcelExport exportService)
: base(logger, encryption, depotFactory, commonModelBuilder, cachingService, exportService)
{
_profilModelBuilder = profilModelBuilder;
Page = PageEnum.Profil;
}
public ActionResult Index()
{
return ProcessPage();
}
[HttpGet]
public ActionResult Recherche()
{
BuildActionContext(VueEnum.ProfilSearch);
var vm = _commonModelBuilder.BuildPartialViewModel(Context, null);
return View(vm);
}
[HttpPost]
public ActionResult Recherche(SearchProfilCriterias criterias)
{
var res = _depotFactory.ProfilDepot.Search(criterias.Code, criterias.Description);
var model = new RechercheResultViewModel
{
Results = res
};
if (criterias.ExportExcel)
{
model.ExportUrl = CreateExportFile(res, "ExportRechercheDemande.xls", FileDownloadTypes.ExportRecherche);
}
return new JsonHttpStatusResult(model);
}
public ActionResult Details(long id, long? vueID)
{
var vm = _commonModelBuilder.BuildDetailsViewModel(Context, (long)ActionModeAffichageEnum.Consultation, (long)GroupeVueEnum.ProfilDetails, id, vueID);
foreach (var item in vm.GroupeVue.Vues)
{
item.Url = RoutesHelper.GetUrl(item.CodeRoute, new { id = id, utilisateurID = Context.User.ID, vueID = item.ID, type = Constants.GetStringValue(GroupeVueTraductibleEnum.Profil) });
}
return View("~/Views/Common/Details.cshtml", vm);
}
public ActionResult InformationsGenerales(long id)
{
BuildActionContext(VueEnum.ProfilInformationsGenerales, id );
var vm = _profilModelBuilder.BuildInfosGeneralesViewModel(Context, id);
return View(vm);
}
public ActionResult Create()
{
var vm = _commonModelBuilder.BuildDetailsViewModel(Context, (long)ActionModeAffichageEnum.Creation, (long)GroupeVueEnum.ProfilDetails, 0, null);
foreach (var item in vm.GroupeVue.Vues)
{
item.Url = RoutesHelper.GetUrl(item.CodeRoute, new { id = 0 });
}
return View("~/Views/Common/Details.cshtml", vm);
}
[HttpPost]
[ValidateModelState]
public ActionResult SaveInfosGenerales(InfosGeneralesViewModel model)
{
BuildActionContext(VueEnum.ProfilInformationsGenerales, model.Profil.ID, model.Profil.ID > 0 ? (long)TypeActionEnum.Save : (long)TypeActionEnum.Add, model.TimeStamp);
var profilComposite = AutoMapper.Mapper.Map<InfosGeneralesViewModel, GetProfilsByIdComposite>(model);
var profil = Save(() => _depotFactory.ProfilDepot.SaveProfilInfosGenerales(profilComposite));
return new JsonHttpStatusResult((int)HttpStatusCode.OK, new { id = profil.ID });
}
}
}
|
apo-j/Projects_Working
|
Bivi/src/Bivi.BackOffice/Bivi.BackOffice.Web.Controllers/Controllers/Administration/ProfilController.cs
|
C#
|
mit
| 4,679
|
<?PHP
$customer_info_table->get_post_vars();
$page_output = '';
// set customer ref code if assigned
if(!empty($_GET['user_ref_code'])) $_SESSION['user_ref_code'] = $_GET['user_ref_code'];
$user_ref_code = $_SESSION['user_ref_code'];
// check for form submission and run form check routines
if(isset($_POST['Submit'])) {
if ($_POST['Submit'] === 'Create Account') {
// extract post vars
extract($_POST);
$errored_fields = '';
$required_fields = array(
'Email Address' => 'email_address',
'Password' => 'password',
'Confirm Password' => 'confirm_password'
);
foreach($required_fields as $id => $value) {
if(empty($_POST[$value])) {
$errored_fields[] = $id;
}
}
// write error message
if(is_array($errored_fields)) $error_message = "Errors were found with these fields: ".implode(', ',$errored_fields).".";
// check if username exists
if($customer_info_table->email_check() > 0) {
$error_message .= 'You appear to already have an account.';
}
// make sure password fields match
if($_POST['password'] != $_POST['confirm_password']) {
$error_message .= '<br/>Password fields do not match.';
}
// check for valid email address
if(strpos($_POST['email_address'],'@') <= 0) {
$error_message .= '<br/>E-Mail address does not appear to be valid.';
}
// check password length
if (strlen($_POST['password']) < MINIMUM_PASSWORD_LENGTH) $error_message .= "<br>Password must be atleast ".MINIMUM_PASSWORD_LENGTH." characters in length.";
// if error found pring error message
if (!empty($error_message)) {
// clear entered passwords
$_POST['password'] = '';
$customer_info_table->password = '';
} else {
$customer_info_table->balance = CUSTOMER_DEFAULT_BALANCE;
$customer_info_table->account_enabled = 1;
$customer_info_table->city = $geo_data->city;
$customer_info_table->state = $geo_data->region;
$customer_info_table->usr_ref_code = $user_ref_code;
if($update_usr == 1){
$customer_info_table->update();
} else {
$customer_info_table->insert();
}
// add new account information to email message
$account_login_info = '<br><br><font color="red">Your new account login info:</font>'."<br>";
$account_login_info .= 'E-Mail: '.$email_address."<br>";
$account_login_info .= 'Password: '.$_POST['password']."<br>";
$account_login_info .= '<br><br>Get a FREE Credit towards your next $10 coupon when you refer a friend and they sign up! UNLIMITED credits. Just send your friends the Link below and when sign up via that link you instantly get a credit.'."<br>";
$account_login_info .= 'http://www.cheaplocaldeals.com/customer_admin/create_account.deal?user_ref_code='.$customer_info_table->ref_code."<br>";
$email_replace_arr = array($account_login_info);
$email_replace_str_arr = array('NEW_USER_ACC_LOGIN_INFO');
$html = str_replace($email_replace_str_arr,$email_replace_arr,CUSTOMER_SIGNUP_EMAIL);
$email_data = array();
$email_data['content'] = $html;
$email_data['from_address'] = SITE_FROM_ADDRESS;
$email_data['subject'] = SITE_NAME_VAL." Account Signup ".date("m-d-Y");
$email_data['to_addresses'] = $customer_info_table->email_address;
// send email
send_email($email_data);
// write admin account created email
$html = 'New Customer Account Created:'."<br>";
$html .= '<br><br>Customer Info:'."<br>";
$html .= 'Email Address: '.$customer_info_table->email_address."<br>";
$html .= '<br><br>Login Info:'."<br>";
$html .= 'password: '.$_POST['password']."<br>";
$email_data = array();
$email_data['content'] = $html;
$email_data['from_address'] = SITE_FROM_ADDRESS;
$email_data['subject'] = SITE_NAME_VAL." Customer Account Signup ".date("m-d-Y");
$email_data['to_addresses'] = SITE_CONTACT_EMAILS;
// send email
send_email($email_data);
// login user
$customer_info_table->user_login_check();
// added to check reference code and process as needed 5/4/2010
if(!empty($user_ref_code)) {
$ref_cust_id = $customer_info_table->ref_code_id_srch($user_ref_code);
// if cust id found get customer data
if(!empty($ref_cust_id)) {
$credit_amt = CUST_REF_CRED_AMT;
// get and update customer data
$customer_info_table->get_db_vars($ref_cust_id);
$customer_info_table->balance += $credit_amt;
$customer_info_table->update_balance();
// capture reference data
$cust_ref_info_tbl->customer_id = $customer_info_table->id;
$cust_ref_info_tbl->ref_code = $customer_info_table->ref_code;
$cust_ref_info_tbl->credit_amt = $credit_amt;
$cust_ref_info_tbl->api_id = $api_ref_chk->api_id;
$cust_ref_info_tbl->insert();
}
}
if ($shopping_cart_manage->contents_count > 0) {
header("Location: ".MOB_URL."checkout");
} else {
header("Location: ".MOB_URL."manageacc");
}
}
}
}
$login_form = '<div id="custLoginFrm">';
$login_form .= (!empty($error_message) ? '<center><strong><font color="red">'.$error_message.'</font></strong></center>' : '');
$login_form .= '<form name="login_form" method="post">';
$login_form .= '<p><a href="'. MOB_URL.'?action=page&pid=2" ><font size="2">Privacy Policy</font></a></p>';
$login_form .= '<label>Email:</label>'.$form_write->input_text('email_address',$email_address,30,160,1,'email_address');
$login_form .= '<label>Password:</label>'.$form_write->input_password('password',$password,20,50,2,'password');
$login_form .= '<label>Confirm Password:</label>'.$form_write->input_password('confirm_password',$confirm_password,20,50,3,'confirm_password');
$login_form .= '<input class="submit_btn" id="" type="submit" name="Submit" value="Create Account" />';
$login_form .= '</form></div>';
$page_output = $login_form;
// set page header -- only assign for static header data
$page_header_title = 'CheapLocalDeals.com - Customer Signup Page';
$page_meta_description = 'Create an account with us today.';
$page_meta_keywords = 'Assign keywords here';
// this script writes the content for the sites logoff page and handles search form submissions
$selTemp = 'pages.php';
$selHedMetTitle = $page_header_title;
$selHedMetDesc = $page_meta_description;
$selHedMetKW = $page_meta_keywords;
?>
|
doodersrage/CheapLocalDeals.com
|
mobile/includes/pages/createAcc.php
|
PHP
|
mit
| 6,282
|
import { h, Component } from 'preact';
import './style.css';
export default class Imprint extends Component {
render() {
return (
<div className="c-imprint b-content">
<h1>Imprint</h1>
<p>
Name
<br />
Address
<br />
Country
<br />
contact@example.com
</p>
</div>
);
}
}
|
jaylinski/frontend-webpack
|
src/pages/imprint/index.js
|
JavaScript
|
mit
| 389
|
<?php
// Composer autoload is already loaded
// require_once 'vendor/autoload.php';
// Benchmark
$time_start = microtime(true);
/* ---------- Formulator ---------- */
$formulator = new ntopulos\formulator\Formulator();
//$formulator->debug_mod = true;
// 1. adding and managing elements
$formulator->addElement('name');
$formulator->elements->root->name->addRule('required');
$formulator->addElement('age');
$formulator->elements->root->age->label = 'Your age';
$formulator->elements->root->age->addRule('required')->addRule('min:20')->addRule('max:30');
// 2nd syntax to add rules
$rules = array(
'required',
'email'
);
$formulator->addElement('email');
$formulator->elements->root->email->addRules($rules);
// 2. Computation
if($formulator->validate()) {
// if formulator is submitted AND completly valid...
}
// 3 Rendering
echo $formulator->renderTemplate();
|
ntopulos/formulator-devkit
|
pages/index.php
|
PHP
|
mit
| 896
|
<?php
return [
'@class' => 'Grav\\Common\\File\\CompiledYamlFile',
'filename' => '/Users/joltt/Desktop/sinoclean_tmp/user/plugins/login/languages.yaml',
'modified' => 1480466252,
'data' => [
'en' => [
'PLUGIN_LOGIN' => [
'USERNAME' => 'Username',
'PASSWORD' => 'Password',
'ACCESS_DENIED' => 'Access denied...',
'LOGIN_FAILED' => 'Login failed...',
'LOGIN_SUCCESSFUL' => 'You have been successfully logged in.',
'BTN_LOGIN' => 'Login',
'BTN_LOGOUT' => 'Logout',
'BTN_FORGOT' => 'Forgot',
'BTN_REGISTER' => 'Register',
'BTN_RESET' => 'Reset Password',
'BTN_SEND_INSTRUCTIONS' => 'Send Reset Instructions',
'RESET_LINK_EXPIRED' => 'Reset link has expired, please try again',
'RESET_PASSWORD_RESET' => 'Password has been reset',
'RESET_INVALID_LINK' => 'Invalid reset link used, please try again',
'FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL' => 'Instructions to reset your password have been sent via email to %s',
'FORGOT_FAILED_TO_EMAIL' => 'Failed to email instructions, please try again later',
'FORGOT_CANNOT_RESET_EMAIL_NO_EMAIL' => 'Cannot reset password for %s, no email address is set',
'FORGOT_USERNAME_DOES_NOT_EXIST' => 'User with username <b>%s</b> does not exist',
'FORGOT_EMAIL_NOT_CONFIGURED' => 'Cannot reset password. This site is not configured to send emails',
'FORGOT_EMAIL_SUBJECT' => '%s Password Reset Request',
'FORGOT_EMAIL_BODY' => '<h1>Password Reset</h1><p>Dear %1$s,</p><p>A request was made on <b>%4$s</b> to reset your password.</p><p><br /><a href="%2$s" class="btn-primary">Click this to reset your password</a><br /><br /></p><p>Alternatively, copy the following URL into your browser\'s address bar:</p> <p class="word-break"><a href="%2$s">%2$s</a></p> <p><br />Kind regards,<br /><br />%3$s</p>',
'SESSION' => '“Remember Me”-Session',
'REMEMBER_ME' => 'Remember Me',
'REMEMBER_ME_HELP' => 'Sets a persistent cookie on your browser to allow persistent-login authentication between sessions.',
'REMEMBER_ME_STOLEN_COOKIE' => 'Someone else has used your login information to access this page! All sessions were logged out. Please log in with your credentials and check your data.',
'BUILTIN_CSS' => 'Use built in CSS',
'BUILTIN_CSS_HELP' => 'Include the CSS provided by the admin plugin',
'ROUTE' => 'Login path',
'ROUTE_HELP' => 'Custom route to a custom login page that your theme provides',
'ROUTE_REGISTER' => 'Registration path',
'ROUTE_REGISTER_HELP' => 'Route to the registration page. Set this if you want to use the built-in registration page. Leave it empty if you have your own registration form',
'USERNAME_NOT_VALID' => 'Username should be between 3 and 16 characters, including lowercase letters, numbers, underscores, and hyphens. Uppercase letters, spaces, and special characters are not allowed',
'USERNAME_NOT_AVAILABLE' => 'Username %s already exists, please pick another username',
'PASSWORD_NOT_VALID' => 'Password must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters',
'PASSWORDS_DO_NOT_MATCH' => 'Passwords do not match. Double-check you entered the same password twice',
'USER_NEEDS_EMAIL_FIELD' => 'The user needs an email field',
'EMAIL_SENDING_FAILURE' => 'An error occurred while sending the email',
'ACTIVATION_EMAIL_SUBJECT' => 'Activate your account on %s',
'ACTIVATION_EMAIL_BODY' => 'Hi %s, click <a href="%s">here</a> to activate your account on %s',
'WELCOME_EMAIL_SUBJECT' => 'Welcome to %s',
'WELCOME_EMAIL_BODY' => 'Hi %s, welcome to %s!',
'NOTIFICATION_EMAIL_SUBJECT' => 'New user on %s',
'NOTIFICATION_EMAIL_BODY' => 'Hi, a new user registered on %s. Username: %s, email: %s',
'EMAIL_FOOTER' => 'GetGrav.org',
'ACTIVATION_LINK_EXPIRED' => 'Activation link expired',
'USER_ACTIVATED_SUCCESSFULLY' => 'User activated successfully',
'INVALID_REQUEST' => 'Invalid request',
'USER_REGISTRATION' => 'User Registration',
'USER_REGISTRATION_ENABLED_HELP' => 'Enable the user registration',
'VALIDATE_PASSWORD1_AND_PASSWORD2' => 'Validate double entered password',
'VALIDATE_PASSWORD1_AND_PASSWORD2_HELP' => 'Validate and compare two different fields for the passwords, named `password1` and `password2`. Enable this if you have two password fields in the registration form',
'SET_USER_DISABLED' => 'Set the user as disabled',
'SET_USER_DISABLED_HELP' => 'Best used along with the `Send activation email` email. Adds the user to Grav, but sets it as disabled',
'LOGIN_AFTER_REGISTRATION' => 'Login the user after registration',
'LOGIN_AFTER_REGISTRATION_HELP' => 'Immediately login the user after the registration. If email activation is required, the user will be logged in immediately after activating the account',
'SEND_ACTIVATION_EMAIL' => 'Send activation email',
'SEND_ACTIVATION_EMAIL_HELP' => 'Sends an email to the user to activate his account. Enable the `Set the user as disabled` option when using this feature, so the user will be set as disabled and an email will be sent to activate the account',
'SEND_NOTIFICATION_EMAIL' => 'Send notification email',
'SEND_NOTIFICATION_EMAIL_HELP' => 'Notifies the site admin that a new user has registered. The email will be sent to the `To` field in the Email Plugin configuration',
'SEND_WELCOME_EMAIL' => 'Send welcome email',
'SEND_WELCOME_EMAIL_HELP' => 'Sends an email to the newly registered user',
'DEFAULT_VALUES' => 'Default values',
'DEFAULT_VALUES_HELP' => 'List of field names and values associated, that will be added to the user profile (yaml file) by default, without being configurable by the user. Separate multiple values with a comma, with no spaces between the values',
'ADDITIONAL_PARAM_KEY' => 'Parameter',
'ADDITIONAL_PARAM_VALUE' => 'Value',
'REGISTRATION_FIELDS' => 'Registration fields',
'REGISTRATION_FIELDS_HELP' => 'Add the fields that will be added to the user yaml file. Fields not listed here will not be added even if present in the registration form',
'REGISTRATION_FIELD_KEY' => 'Field name',
'REDIRECT_AFTER_LOGIN' => 'Redirect after login',
'REDIRECT_AFTER_LOGIN_HELP' => 'Custom route to redirect after login',
'REDIRECT_AFTER_REGISTRATION' => 'Redirect after registration',
'REDIRECT_AFTER_REGISTRATION_HELP' => 'Custom route to redirect after the registration',
'OPTIONS' => 'Options',
'EMAIL_VALIDATION_MESSAGE' => 'Must be a valid email address',
'PASSWORD_VALIDATION_MESSAGE' => 'Password must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters',
'TIMEOUT_HELP' => 'Sets the session timeout in seconds when Remember Me is enabled and checked by the user. Minimum is 604800 which means 1 week',
'GROUPS_HELP' => 'List of groups the new registered user will be part of, if any',
'SITE_ACCESS_HELP' => 'List of site access levels the new registered user will have. Example: `login` -> `true` ',
'WELCOME' => 'Welcome',
'REDIRECT_AFTER_ACTIVATION' => 'Redirect after the user activation',
'REDIRECT_AFTER_ACTIVATION_HELP' => 'Used if the user is required to activate the account via email. Once activated, this route will be shown',
'REGISTRATION_DISABLED' => 'Registration disabled',
'USE_PARENT_ACL_LABEL' => 'Use parent access rules',
'USE_PARENT_ACL_HELP' => 'Check for parent access rules if no rules are defined',
'PROTECT_PROTECTED_PAGE_MEDIA_LABEL' => 'Protect a login-protected page media',
'PROTECT_PROTECTED_PAGE_MEDIA_HELP' => 'If enabled, media of a login protected page is login protected as well and cannot be seen unless logged in'
]
],
'de' => [
'PLUGIN_LOGIN' => [
'USERNAME' => 'Benutzername',
'PASSWORD' => 'Passwort',
'ACCESS_DENIED' => 'Zugang verweigert',
'LOGIN_FAILED' => 'Login fehlgeschlagen...',
'LOGIN_SUCCESSFUL' => 'Du wurdest erfolgreich eingeloggt.',
'BTN_LOGIN' => 'Anmelden',
'BTN_LOGOUT' => 'Ausloggen',
'BTN_FORGOT' => 'Vergessen',
'BTN_REGISTER' => 'Registrieren',
'REMEMBER_ME' => 'Angemeldet bleiben',
'REMEMBER_ME_HELP' => 'Speichert einen Cookie im Browser, welcher eine fortwährende Anmeldung sicherstellt.',
'BUILTIN_CSS' => 'Nutze das integrierte CSS',
'BUILTIN_CSS_HELP' => 'Nutze das CSS, welches vom Admin Plugin bereitgestellt werden',
'ROUTE' => 'Anmeldepfad',
'ROUTE_REGISTER' => 'Registrierungspfad',
'USERNAME_NOT_AVAILABLE' => 'Der Nutzername %s existiert bereits, bitte wähle einen Anderen',
'USER_NEEDS_EMAIL_FIELD' => 'Der Nutzer benötigt ein E-Mail Feld',
'EMAIL_SENDING_FAILURE' => 'Ein Fehler ist beim senden der E-Mail aufgetreten',
'ACTIVATION_EMAIL_SUBJECT' => 'Aktiviere dein Account auf %s',
'ACTIVATION_EMAIL_BODY' => 'Hi %s, click %s to activate your account on %s',
'WELCOME_EMAIL_SUBJECT' => 'Willkommen zu %s',
'WELCOME_EMAIL_BODY' => 'Hi %s, willkommen zu %s!',
'NOTIFICATION_EMAIL_SUBJECT' => 'Neuer Nutzer auf %s',
'NOTIFICATION_EMAIL_BODY' => 'Hi, ein neuer Nutzer hat sich auf %s registriert. Nutzername: %s, E-Mail: %s',
'EMAIL_FOOTER' => 'GetGrav.org',
'ACTIVATION_LINK_EXPIRED' => 'Aktivierungslink ist abgelaufen',
'USER_ACTIVATED_SUCCESSFULLY' => 'Nutzer erfolgreich aktiviert',
'INVALID_REQUEST' => 'Ungültige Anfrage',
'USER_REGISTRATION' => 'Nutzer Registrierung',
'USER_REGISTRATION_ENABLED_HELP' => 'Aktiviere die Nutzer Registrierung',
'VALIDATE_PASSWORD1_AND_PASSWORD2' => 'Überprüfe das doppelt eingegebene Passwort',
'SEND_ACTIVATION_EMAIL' => 'Aktivierungs E-Mail senden',
'SEND_NOTIFICATION_EMAIL' => 'Benachtichtigungs E-Mail senden',
'SEND_WELCOME_EMAIL' => 'Sende eine Willkommens E-Mail',
'DEFAULT_VALUES' => 'Standard Werte',
'ADDITIONAL_PARAM_KEY' => 'Parameter',
'ADDITIONAL_PARAM_VALUE' => 'Wert',
'REGISTRATION_FIELDS' => 'Registrierungsfelder',
'REGISTRATION_FIELD_KEY' => 'Feldname',
'REDIRECT_AFTER_LOGIN' => 'Umleitung nach Login',
'REDIRECT_AFTER_REGISTRATION' => 'Umleitung nach Registrierung',
'OPTIONS' => 'Optionen',
'EMAIL_VALIDATION_MESSAGE' => 'Muss eine gültige E-Mail Adresse sein'
]
],
'fr' => [
'PLUGIN_LOGIN' => [
'USERNAME' => 'Nom d’utilisateur',
'PASSWORD' => 'Mot de passe',
'ACCESS_DENIED' => 'Accès refusé...',
'LOGIN_FAILED' => 'Échec de la connexion...',
'LOGIN_SUCCESSFUL' => 'Vous vous êtes connecté avec succès.',
'BTN_LOGIN' => 'Connexion',
'BTN_LOGOUT' => 'Déconnexion',
'BTN_FORGOT' => 'Mot de passe oublié',
'BTN_REGISTER' => 'S’enregister',
'BTN_RESET' => 'Réinitialiser le mot de passe',
'BTN_SEND_INSTRUCTIONS' => 'Envoyer les instructions de Réinitialisation',
'RESET_LINK_EXPIRED' => 'Le lien de réinitialisation a expiré, veuillez réessayer',
'RESET_PASSWORD_RESET' => 'Le mot de passe a été réinitialisé',
'RESET_INVALID_LINK' => 'Le lien de réinitialisation utilisé n’est pas valide, veuillez réessayer',
'FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL' => 'Les instructions pour la réinitialisation de votre mot de passe ont été envoyées par e-mail à %s',
'FORGOT_FAILED_TO_EMAIL' => 'Impossible d’envoyer les instructions, veuillez réessayer ultérieurement',
'FORGOT_CANNOT_RESET_EMAIL_NO_EMAIL' => 'Impossible de réinitialiser le mot de passe pour %s, aucune adresse e-mail n’a été paramétrée',
'FORGOT_USERNAME_DOES_NOT_EXIST' => 'L’utilisateur avec le nom d’utilisateur <b>%s</b> n’existe pas',
'FORGOT_EMAIL_NOT_CONFIGURED' => 'Impossible de réinitialiser le mot de passe. Ce site n’est pas configuré pour envoyer des e-mails',
'FORGOT_EMAIL_SUBJECT' => 'Demande de réinitialisation de mot de passe %s',
'FORGOT_EMAIL_BODY' => '<h1>Réinitialisation de mot de passe</h1><p>%1$s,</p><p>Une demande a été faite sur <b>%4$s</b> pour la réinitialisation de votre mot de passe.</p><p><br /><a href="%2$s" class="btn-primary">Cliquez ici pour réinitialiser votre mot de passe</a><br /><br /></p><p>Vous pouvez également copier l’URL suivante dans la barre d’adresse de votre navigateur :</p> <p class="word-break"><a href="%2$s">%2$s</a></p> <p><br />Cordialement,<br /><br />%3$s</p>',
'SESSION' => 'Session - “Se souvenir de moi”',
'REMEMBER_ME' => 'Se souvenir de moi',
'REMEMBER_ME_HELP' => 'Définit un cookie persistant sur votre navigateur autorisant l’authentification par connexion persistante entre les sessions.',
'REMEMBER_ME_STOLEN_COOKIE' => 'Quelqu’un d’autre a utilisé vos informations de connexion pour accéder à cette page ! Toutes les sessions ont été déconnectées. Veuillez vous connecter avec vos identifiants et vérifier vos données.',
'BUILTIN_CSS' => 'Utiliser les CSS intégrés',
'BUILTIN_CSS_HELP' => 'Utiliser les CSS fournis dans le plugin d’administration',
'ROUTE' => 'Chemin de connexion',
'ROUTE_HELP' => 'Chemin personnalisé vers une page de connexion personnalisée proposée par votre thème',
'ROUTE_REGISTER' => 'Chemin vers l’inscription',
'ROUTE_REGISTER_HELP' => 'Chemin vers la page d’inscription. A définir si vous souhaitez utiliser la page d’inscription intégrée. Laisser vide si vous disposez de votre propre formulaire d’inscription.',
'USERNAME_NOT_VALID' => 'Le nom d’utilisateur doit comporter entre 3 et 16 caractères et peut être composé de lettres minuscules, de chiffres et de tirets de soulignement (underscores) et des traits d’union. Les lettres majuscules, les espaces et les caractères spéciaux ne sont pas autorisés.',
'USERNAME_NOT_AVAILABLE' => 'Le nom d’utilisateur %s existe déjà, veuillez en choisir un autre.',
'PASSWORD_NOT_VALID' => 'Le mot de passe doit contenir au moins un chiffre, une majuscule et une minuscule et être composé d’au moins 8 caractères',
'PASSWORDS_DO_NOT_MATCH' => 'Les mots de passe sont différents. Réessayez de saisir le même mot de passe deux fois.',
'USER_NEEDS_EMAIL_FIELD' => 'L’utilisateur a besoin d’un champ pour e-mail',
'EMAIL_SENDING_FAILURE' => 'Une erreur est survenue lors de l’envoi de l’e-mail.',
'ACTIVATION_EMAIL_SUBJECT' => 'Activer votre compte sur %s',
'ACTIVATION_EMAIL_BODY' => 'Bonjour %s, <a href="%s">cliquez</a> pour activer votre compte sur %s',
'WELCOME_EMAIL_SUBJECT' => 'Bienvenue sur %s',
'WELCOME_EMAIL_BODY' => 'Bonjour %s, bienvenue sur %s!',
'NOTIFICATION_EMAIL_SUBJECT' => 'Nouvel utilisateur sur %s',
'EMAIL_FOOTER' => 'GetGrav.org',
'NOTIFICATION_EMAIL_BODY' => 'Bonjour, un nouvel utilisateur s’est inscrit sur %s. Nom d’utilisateur : %s, e-mail : %s',
'ACTIVATION_LINK_EXPIRED' => 'Le lien d’activation a expiré',
'USER_ACTIVATED_SUCCESSFULLY' => 'Utilisateur activé avec succès',
'INVALID_REQUEST' => 'Requête non valide',
'USER_REGISTRATION' => 'Inscription de l’utilisateur',
'USER_REGISTRATION_ENABLED_HELP' => 'Activer l’inscription des utilisateurs',
'VALIDATE_PASSWORD1_AND_PASSWORD2' => 'Valider la double saisie du mot de passe',
'VALIDATE_PASSWORD1_AND_PASSWORD2_HELP' => 'Comparer et valider deux champs pour les mots de passe `Mot de passe 1` et `Mot de passe 2`. Activez cette option si vous avez deux champs de mots de passe dans le formulaire d’inscription.',
'SET_USER_DISABLED' => 'Définir l’utilisateur comme désactivé',
'SET_USER_DISABLED_HELP' => 'La meilleure pratique si vous utilisez l’option `Envoyer un e-mail d’activation`. Ajoute l’utilisateur à Grav, mais le défini comme étant désactivé.',
'LOGIN_AFTER_REGISTRATION' => 'Connecte l’utilisateur après son inscription',
'LOGIN_AFTER_REGISTRATION_HELP' => 'Identifier immédiatement l’utilisateur après l’inscription. Si l’e-mail d’activation est demandé, l’utilisateur sera connecté immédiatement après l’activation du compte.',
'SEND_ACTIVATION_EMAIL' => 'Envoyer un e-mail d’activation',
'SEND_ACTIVATION_EMAIL_HELP' => 'Envoyer un e-mail à l’utilisateur pour l’activation son compte. Lorsque vous utilisez cette fonction, activez l’option `Définir l’utilisateur comme désactivé` afin que l’utilisateur soit désactivé et qu’un e-mail lui soit envoyé pour activer son compte.',
'SEND_NOTIFICATION_EMAIL' => 'Envoyer un e-mail de notification',
'SEND_NOTIFICATION_EMAIL_HELP' => 'Informe l’administrateur du site qu’un nouvel utilisateur s’est enregistré. L’e-mail sera envoyé à la personne renseignée dans le champ `À` dans la configuration du plugin e-mail.',
'SEND_WELCOME_EMAIL' => 'Envoyer un e-mail de bienvenue',
'SEND_WELCOME_EMAIL_HELP' => 'Envoyer un e-mail à un nouvel utilisateur enregistré.',
'DEFAULT_VALUES' => 'Valeurs par défaut',
'DEFAULT_VALUES_HELP' => 'Liste des noms et valeurs associés pour les champs. Ils seront ajoutés au profil utilisateur par défaut (fichier yaml), sans pouvoir être configurables par l’utilisateur. Séparez les différentes valeurs par une virgule, sans espaces entre les valeurs.',
'ADDITIONAL_PARAM_KEY' => 'Paramètre',
'ADDITIONAL_PARAM_VALUE' => 'Valeur',
'REGISTRATION_FIELDS' => 'Champs d’inscription',
'REGISTRATION_FIELDS_HELP' => 'Ajouter les champs qui seront ajoutés au fichier yaml de l’utilisateur. Les champs non listés ne seront pas ajoutés même s’ils sont présent sur le formulaire d’inscription',
'REGISTRATION_FIELD_KEY' => 'Nom du champ',
'REDIRECT_AFTER_LOGIN' => 'Redirection après connexion',
'REDIRECT_AFTER_LOGIN_HELP' => 'Chemin personnalisé de redirection après la connexion',
'REDIRECT_AFTER_REGISTRATION' => 'Redirection après inscription',
'REDIRECT_AFTER_REGISTRATION_HELP' => 'Chemin personnalisé de redirection après l’inscription',
'OPTIONS' => 'Options',
'EMAIL_VALIDATION_MESSAGE' => 'Doit-être une adresse e-mail valide',
'PASSWORD_VALIDATION_MESSAGE' => 'Le mot de passe doit-être composé d’au moins un chiffre, une majuscule et une minuscule, et au moins 8 caractères',
'TIMEOUT_HELP' => 'Définit le délai d’expiration de la session en secondes lorsque `Se souvenir de moi` est activé et coché par l’utilisateur. Minimum de 604800 ce qui correspond à 1 semaine.',
'GROUPS_HELP' => 'Liste des groupes auxquels le nouvel utilisateur enregistré fera partie, le cas échéant.',
'SITE_ACCESS_HELP' => 'Liste des niveaux d’accès au site attribués au nouvel utilisateur enregistré. Exemple : `login` -> `true` ',
'WELCOME' => 'Bienvenue',
'REDIRECT_AFTER_ACTIVATION' => 'Redirection après l’activation de l’utilisateur',
'REDIRECT_AFTER_ACTIVATION_HELP' => 'Utilisé s’il est nécessaire pour l’utilisateur d’activer le compte par e-mail. Une fois activé, ce chemin s’affichera',
'REGISTRATION_DISABLED' => 'Inscription désactivée',
'USE_PARENT_ACL_LABEL' => 'Appliquer les règles d’accès parentes',
'USE_PARENT_ACL_HELP' => 'Utiliser les règles d’accès parentes si aucune règle n’a été définie',
'PROTECT_PROTECTED_PAGE_MEDIA_LABEL' => 'Protéger le média d\'une page par une protection par connexion',
'PROTECT_PROTECTED_PAGE_MEDIA_HELP' => 'Si activé, les médias d\'une page protégée par connexion sera également protégé par un système de connexion et ne pourra pas être visible à moins d\'être connecté.'
]
],
'hr' => [
'PLUGIN_LOGIN' => [
'ACCESS_DENIED' => 'Pristup odbijen...',
'LOGIN_FAILED' => 'Prijava nije uspjela...',
'BTN_LOGIN' => 'Prijava',
'BTN_LOGOUT' => 'Odjava',
'BTN_FORGOT' => 'Zaboravih',
'BTN_REGISTER' => 'Registriraj',
'REMEMBER_ME' => 'Zapamti me',
'BUILTIN_CSS' => 'Koristi ugrađeni CSS',
'BUILTIN_CSS_HELP' => 'Uključi CSS koji dolazi sa admin pluginom',
'ROUTE' => 'Putanja prijave',
'ROUTE_REGISTER' => 'Putanja registracije',
'USERNAME_NOT_VALID' => 'Korisničko ime bi trebalo biti između 3 i 16 znakova, uključujući mala slova, brojeve, _, i crtice. VELIKA SLOVA, razmaci, i posebni znakovi nisu dopušteni',
'USERNAME_NOT_AVAILABLE' => 'Korisničko ime %s već postoji, odaberi neko drugo',
'PASSWORD_NOT_VALID' => 'Lozinka mora sadržavati bar jedan broj i jedno veliko i malo slovo, i bar još 8 ili više znakova',
'PASSWORDS_DO_NOT_MATCH' => 'Lozinke se ne slažu. Poonovo provjeri da li si unio istu lozinku dva puta',
'USER_NEEDS_EMAIL_FIELD' => 'Korisnik treba email polje',
'EMAIL_SENDING_FAILURE' => 'Došlo je do greške pri slanju emaila',
'ACTIVATION_LINK_EXPIRED' => 'Aktivacijski link je istekao',
'USER_ACTIVATED_SUCCESSFULLY' => 'Korisnik je uspješno aktiviran',
'INVALID_REQUEST' => 'Nevaljani zahtjev',
'USER_REGISTRATION' => 'Registracija korisnika',
'USER_REGISTRATION_ENABLED_HELP' => 'Omogući registraciju korisnika',
'VALIDATE_PASSWORD1_AND_PASSWORD2' => 'Validiraj duplo unesenu lozinku',
'VALIDATE_PASSWORD1_AND_PASSWORD2_HELP' => 'Validiraj i usporedi dva različčita polja za lozinke, imenovana `lozinka1` i `lozinka2`. Omogući ovo ako imaš dva polja za lozinke u formularu registracije',
'LOGIN_AFTER_REGISTRATION' => 'Ulogiraj korisnika nakon reegistracije',
'LOGIN_AFTER_REGISTRATION_HELP' => 'Ulogiraj korisnika odmah nakon registracije. Ako je potrebna email aktivacija, korisnik će biti ulogiran odmah nakon aktiviranja računa',
'SEND_ACTIVATION_EMAIL' => 'Pošalji aktivacijski email',
'SEND_ACTIVATION_EMAIL_HELP' => 'Šalje email korisniku da aktivira svoja račun.',
'SEND_NOTIFICATION_EMAIL' => 'Pošalji email obavijest',
'SEND_NOTIFICATION_EMAIL_HELP' => 'Obavještava administratora da se novi korisnik registrirao. Email će biti poslan na `To` polje u Email Plugin konfiguraciji',
'SEND_WELCOME_EMAIL' => 'Pošalji email dobrodošlice',
'SEND_WELCOME_EMAIL_HELP' => 'Šalje email novoregistriranom korisniku',
'DEFAULT_VALUES' => 'Određene vrijednosti',
'DEFAULT_VALUES_HELP' => 'List of field names and values associated, that will be added to the user profile (yaml file) by default, without being configurable by the user. Separate multiple values with a comma, with no spaces between the values',
'ADDITIONAL_PARAM_KEY' => 'Parametar',
'ADDITIONAL_PARAM_VALUE' => 'Vrijednost',
'REGISTRATION_FIELDS' => 'Registracijska polja',
'REGISTRATION_FIELDS_HELP' => 'Add the fields that will be added to the user yaml file. Fields not listed here will not be added even if present in the registration form',
'REGISTRATION_FIELD_KEY' => 'Ime polja',
'OPTIONS' => 'Opcije'
]
],
'hu' => [
'PLUGIN_LOGIN' => [
'ACCESS_DENIED' => 'Hozzáférés megtagadva...',
'LOGIN_FAILED' => 'Sikertelen belépés...',
'LOGIN_SUCCESSFUL' => 'Sikeresen beléptél.',
'BTN_LOGIN' => 'Belépés',
'BTN_LOGOUT' => 'Kilépés',
'BTN_FORGOT' => 'Elfelejtettem',
'BTN_REGISTER' => 'Regisztráció',
'REMEMBER_ME' => 'Jegyezz Meg',
'REMEMBER_ME_HELP' => 'Elhelyezünk egy hosszú lejáratú sütit a böngésződben, hogy belépve maradhass két munkamenet között.',
'REMEMBER_ME_STOLEN_COOKIE' => 'Valaki a belépési adataid felhasználásával látogatta meg ezt az oldalt! Minden munkamenetet kiléptettünk. Kérlek, jelentkezz be ismét és ellenőrizd az adataidat.',
'BUILTIN_CSS' => 'Beépített CSS használata',
'BUILTIN_CSS_HELP' => 'Az admin plugin által biztosított CSS beillesztése',
'ROUTE' => 'Belépés útvonala',
'ROUTE_HELP' => 'Egyedi útvonal egy egyedi belépő oldalhoz, melyet az aktuális téma biztosít',
'ROUTE_REGISTER' => 'Regisztráció útvonala',
'ROUTE_REGISTER_HELP' => 'A regisztrációs oldal elérési útja. Akkor állítsd be, ha a beépített regisztrációs oldalt szeretnéd használni',
'USERNAME_NOT_VALID' => 'A felhasználónév 3-16 karakter hosszú legyen, tartalmazhat kisbetűket, számokat, aláhúzást és kötőjelet. Nagybetűk, szóköz és speciális karakterek használata nem megengedett',
'USERNAME_NOT_AVAILABLE' => '%s nevű felhasználó már létezik, kérlek válassz más felhasználónevet',
'PASSWORD_NOT_VALID' => 'A jelszónak tartalmaznia kell legalább egy számot, egy kisbetűt és egy nagybetűt, valamint legalább 8 karakter hosszú kell, hogy legyen',
'PASSWORDS_DO_NOT_MATCH' => 'A két jelszó nem egyezik meg. Győzödj meg róla, hogy azonos legyen a kettő'
]
],
'ro' => [
'PLUGIN_LOGIN' => [
'USERNAME' => 'Nume utilizator',
'PASSWORD' => 'Parolă',
'ACCESS_DENIED' => 'Acces refuzat...',
'LOGIN_FAILED' => 'Logare eșuată...',
'LOGIN_SUCCESSFUL' => 'Ați fost logat cu succes.',
'BTN_LOGIN' => 'Logare',
'BTN_LOGOUT' => 'Ieșire din cont ',
'BTN_FORGOT' => 'Am uitat',
'BTN_REGISTER' => 'Înregistrare',
'BTN_RESET' => 'Resetează parola',
'BTN_SEND_INSTRUCTIONS' => 'Trimite instrucțiuni pentru resetare',
'RESET_LINK_EXPIRED' => 'Link-ul pentru resetarea parolei a expirat, vă rugăm încercați din nou ',
'RESET_PASSWORD_RESET' => 'Parola a fost modificată',
'RESET_INVALID_LINK' => 'Link-ul pentru resetare este invalid, Invalid reset link used, vă rugăm încercați din nou ',
'FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL' => 'Instrucțiunile pentru resetarea parolei au fst trimise pe email la %s',
'FORGOT_FAILED_TO_EMAIL' => 'Instrucțiunile nu au putut fi trimise pe email, vă rugăm încercați mai târziu ',
'FORGOT_CANNOT_RESET_EMAIL_NO_EMAIL' => 'Parola nu poate fi resetată pentru %s, nu este setată nici o adresă de email',
'FORGOT_USERNAME_DOES_NOT_EXIST' => 'Utilizatorul cu numele <b>%s</b> nu există',
'FORGOT_EMAIL_NOT_CONFIGURED' => 'Parola nu poate fi resetată. Acest site nu este configurat pentru a trimite email-uri.',
'FORGOT_EMAIL_SUBJECT' => '%s Cerere de resetare a parolei',
'FORGOT_EMAIL_BODY' => '<h1>Resetare parolă</h1><p> Dragă %1$s,</p><p>O cerere de resetare a parolei a fost făcută în data de <b>%4$s</b>.</p><p><br /><a href="%2$s" class="btn-primary">Apasă aici pentru a reseta parola</a><br /><br /></p><p>Alternativ, copiază URL de mai jos în bara de adrese a browser-ului favorit:</p> <p class="word-break"><a href="%2$s">%2$s</a></p> <p><br />Cu respect,<br /><br />%3$s</p>',
'SESSION' => '“Ține-mă minte”-Sesiune',
'REMEMBER_ME' => 'Ține-mă minte',
'REMEMBER_ME_HELP' => 'Setează o cookie în browserul Dvs. ce permite menținerea datelor de logare între sesiuni.',
'REMEMBER_ME_STOLEN_COOKIE' => 'Altcineva a folosit darele Dvs de logare pentru a accesa această pagină! Toate sesiunile au fost deconectate. Vă rugăm să vă logați cu datele Dvs. și să verificați toate detaliile. ',
'BUILTIN_CSS' => 'Folosește CSS-ul din modul',
'BUILTIN_CSS_HELP' => 'Include CSS-ul furnizat de către modulul Admin',
'ROUTE' => 'Calea pentru logare',
'ROUTE_HELP' => 'O rută personalizată către pagina de logare pe care o furnizează tema activă ',
'ROUTE_REGISTER' => 'Calea pentru înregistrare ',
'ROUTE_REGISTER_HELP' => 'Ruta către pagina de înregistrare. Setați această rută dacă doriți folosirea paginei implicite pentru înregistrare. Lăsați gol dacă folosiți o pagină personalizată pentru înregistrare.',
'USERNAME_NOT_VALID' => 'Numele de utilizator trebuie să fie între 3-16 caractere, incluzând litere mici, numere, linii de subliniere și cratime. Literele de tipar, spațiile și caracterele speciale nu sunt permise. ',
'USERNAME_NOT_AVAILABLE' => 'Utilizatorul %s există deja, vă rugăm alegeți un alt nume de utilizator ',
'PASSWORD_NOT_VALID' => ' Parola trebuie să conțină cel puțin 1 număr și o literă de tipar și o literă mică; și să aibă minim 8 caractere',
'PASSWORDS_DO_NOT_MATCH' => ' Parolele nu sunt identice. Vă rugăm verificați că ași scris aceeiași parolă de două ori.',
'USER_NEEDS_EMAIL_FIELD' => 'Utilizatorul trebuie să aibă adresa de email completată',
'EMAIL_SENDING_FAILURE' => 'A apărut o eroare la trimirea email-ului',
'ACTIVATION_EMAIL_SUBJECT' => 'Activați-vă contrul pentru %s',
'ACTIVATION_EMAIL_BODY' => 'Salut %s, apasă <a href="%s">aici</a> pentru a-ți activa contul de pe %s',
'WELCOME_EMAIL_SUBJECT' => 'Bine ați venit pe %s',
'WELCOME_EMAIL_BODY' => 'Salut %s, bine ai venit la %s!',
'NOTIFICATION_EMAIL_SUBJECT' => 'Utilizator nou pe %s',
'NOTIFICATION_EMAIL_BODY' => 'Salut, un nou utilizator s-a înregistrat pe %s. Nume de utilizator: %s, adresă de email: %s',
'ACTIVATION_LINK_EXPIRED' => 'Link-ul pentru activare este expirat',
'USER_ACTIVATED_SUCCESSFULLY' => 'Utilizator activat cu succes',
'INVALID_REQUEST' => 'Cerere invalidă ',
'USER_REGISTRATION' => 'Înregistrare utilizator ',
'USER_REGISTRATION_ENABLED_HELP' => 'Activați înregistrarea utilizatorilor',
'VALIDATE_PASSWORD1_AND_PASSWORD2' => 'Validați parola introdusă de două ori',
'VALIDATE_PASSWORD1_AND_PASSWORD2_HELP' => 'Validați și comparați cele două câmpuri pentru parolă cu numele `password1` și `password2`. Activați această opțiune dacă există două câmpuri pentru parolă în formularul de înregistrare.',
'SET_USER_DISABLED' => 'Setați utilizatorul dezactivat',
'SET_USER_DISABLED_HELP' => 'Cel mai bine să fie folosit împreună cu email-ul pentru activare. Adaugă utilizatorul în Grav dar îl setează ca dezactivat',
'LOGIN_AFTER_REGISTRATION' => 'Loghează utilizatorul după înregistrare',
'LOGIN_AFTER_REGISTRATION_HELP' => 'Imediat după înregistrare loghează utilizatorul în cont. Dacă este necesară activarea prin email, utilizatorul va fi logat imediat după activarea contului.',
'SEND_ACTIVATION_EMAIL' => 'Trimite email-ul pentru activare',
'SEND_ACTIVATION_EMAIL_HELP' => 'Trimite un email către utilizatorul nou înregistrat pentru activarea contului. Activați opțiunea `Setați utilizatorul dezactivat` când folosiți această opțiune pentru a seta utilizatorul dezactivat și pentru a trimite un email automat pentru activarea contului. ',
'SEND_NOTIFICATION_EMAIL' => 'Trimite email cu notificare',
'SEND_NOTIFICATION_EMAIL_HELP' => 'Notifică adminstratorul site-ului când un utilizator nou s-a înregistrat. Email-ul va di trimis către adresa `Către` din configurarea modului de Email',
'SEND_WELCOME_EMAIL' => 'Trimite email de bun venit',
'SEND_WELCOME_EMAIL_HELP' => 'Trimite un email către utilizatorul nou înregistrat.',
'DEFAULT_VALUES' => ' Valori implicite',
'DEFAULT_VALUES_HELP' => 'Listă de câmpuri și valorile asociate acestora ce vor fi adăugate profilului utilizatorului (în fișierul yaml) în mod implicit fără a putea fi configurabile de către utilizator. Separați valorile multiple cu virgulă, fără spații între valori.',
'ADDITIONAL_PARAM_KEY' => 'Parametru',
'ADDITIONAL_PARAM_VALUE' => 'Valoare',
'REGISTRATION_FIELDS' => 'Câmpuri pentru înregistrare',
'REGISTRATION_FIELDS_HELP' => 'Adaugă câmpurile ce vor fi adăugate fișierului yaml al utilizatorului. Câmpurile care nu sunt listate aici nu vor fi adăugate chiar dacă sunt prezente în formularul de înregistrare.',
'REGISTRATION_FIELD_KEY' => ' Numele câmpului',
'REDIRECT_AFTER_LOGIN' => 'Redirecționează după logare',
'REDIRECT_AFTER_LOGIN_HELP' => 'Ruta personalizată pentru redirecționare după logare',
'REDIRECT_AFTER_REGISTRATION' => 'Redirecționează după înregistrare',
'REDIRECT_AFTER_REGISTRATION_HELP' => 'Ruta personalizată pentru redirecționare după înregistrare',
'OPTIONS' => 'Opțiuni',
'EMAIL_VALIDATION_MESSAGE' => 'Trebuie să fie o adresă de email validă',
'PASSWORD_VALIDATION_MESSAGE' => 'Parola trebuie să conțină cel puțin un număr și o literă de tipar și să aibă cel puțin 8 caractere',
'TIMEOUT_HELP' => 'Setează pauza pentru sesiune când este activat \'Ține-mă minte\' de către utilizator. Minimul este de 604800 care înseamnă 1 săptămână.',
'GROUPS_HELP' => 'Lista grupurilor din care utilizatorii nou înregistrați vor face parte, dacă este necesar',
'SITE_ACCESS_HELP' => 'Lista cu niveluri de acces la care utilizatorul nou înregistrat are acces. De eg: `login` -> `true` ',
'WELCOME' => 'Bine ați venit',
'REDIRECT_AFTER_ACTIVATION' => 'Redirecționează după activarea utilizatorului',
'REDIRECT_AFTER_ACTIVATION_HELP' => 'Folosită dacă utilizatorul trebuie să-și activeze contul prin email. Odată activat contul va fi folosită această rută.',
'REGISTRATION_DISABLED' => ' Dezactivează înregistrarea ',
'USE_PARENT_ACL_LABEL' => 'Folosește regulile de acces ale părintelui',
'USE_PARENT_ACL_HELP' => 'Verifică regulie de acces ale părintelui dacă nu sunt specificate alte reguli de acces',
'PROTECT_PROTECTED_PAGE_MEDIA_LABEL' => ' Protejează media ce aparține paginii de logare ',
'PROTECT_PROTECTED_PAGE_MEDIA_HELP' => 'Dacă este activată, media ce aparține unei pagini de logare este protejată și nu poate fi accesată decât după logare.'
]
]
]
];
|
kevinqi34/Sinoclean
|
cache/compiled/files/b83ef0cd00cf076524f4cd33317e4391.yaml.php
|
PHP
|
mit
| 37,947
|
cd libuv; sh autogen.sh; ./configure; make
rm .libs/lib*.so*
rm .libs/lib*.dylib
cd ../luajit; make
rm src/lib*.so*
rm src/lib*.dylib
cd ..
#premake5 clean
rm -rf src/build
#rm *.make
#rm Makefile
premake5 gmake
make config=debug_macosx
|
kostyll/node9
|
rebuild.sh
|
Shell
|
mit
| 238
|
---
layout: page
title: About
permalink: /about/
---
Crazy Developer, working for General Motors in very interesting projects!
You can find the source code for the Jekyll new theme at:
{% include icon-github.html username="jekyll" %} /
[minima](https://github.com/jekyll/minima)
You can find the source code for Jekyll at
{% include icon-github.html username="jekyll" %} /
[jekyll](https://github.com/jekyll/jekyll)
|
darioalessandro/darioalessandro.github.io
|
about.md
|
Markdown
|
mit
| 420
|
{% extends "_base.html" %}
{% block content %}
tady dashboard. kupy budíků a infowerků po celý ploše.
{% endblock %}
|
martastain/cherryadmin
|
site/templates/index.html
|
HTML
|
mit
| 123
|
/*
* Copyright (C) 2013 by Glenn Hickey (hickey@soe.ucsc.edu)
* Copyright (C) 2012-2019 by UCSC Computational Genomics Lab
*
* Released under the MIT license, see LICENSE.txt
*/
#ifndef _HALPHYLOPBED_H
#define _HALPHYLOPBED_H
#include "halBedScanner.h"
#include "halPhyloP.h"
#include <iostream>
#include <set>
#include <string>
#include <vector>
namespace hal {
/** Use the halBedScanner to parse a bed file, running halPhyloP on each
* line */
class PhyloPBed : public BedScanner {
public:
PhyloPBed(AlignmentConstPtr alignment, const Genome *refGenome, const Sequence *refSequence, hal_index_t start,
hal_size_t length, hal_size_t step, PhyloP &phyloP, std::ostream &outStream);
virtual ~PhyloPBed();
void run(std::istream *bedStream);
protected:
virtual void visitLine();
protected:
AlignmentConstPtr _alignment;
const Genome *_refGenome;
const Sequence *_refSequence;
hal_index_t _refStart;
hal_index_t _refLength;
hal_size_t _step;
PhyloP &_phyloP;
std::ostream &_outStream;
};
}
#endif
// Local Variables:
// mode: c++
// End:
|
glennhickey/hal
|
phyloP/inc/halPhyloPBed.h
|
C
|
mit
| 1,196
|
from __future__ import unicode_literals
import django
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase, Client
from django.test.client import RequestFactory
from django.test.utils import override_settings
from custard.conf import (CUSTOM_TYPE_TEXT, CUSTOM_TYPE_INTEGER,
CUSTOM_TYPE_BOOLEAN, CUSTOM_TYPE_FLOAT,
CUSTOM_TYPE_DATE, CUSTOM_TYPE_DATETIME,
CUSTOM_TYPE_TIME, settings)
from custard.builder import CustomFieldsBuilder
from custard.utils import import_class
from .models import (SimpleModelWithManager, SimpleModelWithoutManager,
CustomFieldsModel, CustomValuesModel, builder)
#==============================================================================
class SimpleModelWithManagerForm(builder.create_modelform()):
class Meta:
model = SimpleModelWithManager
fields = '__all__'
#class ExampleAdmin(admin.ModelAdmin):
# form = ExampleForm
# search_fields = ('name',)
#
# def get_search_results(self, request, queryset, search_term):
# queryset, use_distinct = super(ExampleAdmin, self).get_search_results(request, queryset, search_term)
# queryset |= self.model.objects.search(search_term)
# return queryset, use_distinct
#
# admin.site.register(Example, ExampleAdmin)
#==============================================================================
class CustomModelsTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.simple_with_manager_ct = ContentType.objects.get_for_model(SimpleModelWithManager)
self.simple_without_manager_ct = ContentType.objects.get_for_model(SimpleModelWithoutManager)
self.cf = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='text_field',
label="Text field",
data_type=CUSTOM_TYPE_TEXT)
self.cf.save()
self.cf2 = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='another_text_field',
label="Text field 2",
data_type=CUSTOM_TYPE_TEXT,
required=True,
searchable=False)
self.cf2.clean()
self.cf2.save()
self.cf3 = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='int_field', label="Integer field",
data_type=CUSTOM_TYPE_INTEGER)
self.cf3.save()
self.cf4 = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='boolean_field', label="Boolean field",
data_type=CUSTOM_TYPE_BOOLEAN)
self.cf4.save()
self.cf5 = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='float_field', label="Float field",
data_type=CUSTOM_TYPE_FLOAT)
self.cf5.save()
self.cf6 = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='date_field', label="Date field",
data_type=CUSTOM_TYPE_DATE)
self.cf6.save()
self.cf7 = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='datetime_field', label="Datetime field",
data_type=CUSTOM_TYPE_DATETIME)
self.cf7.save()
self.cf8 = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='time_field', label="Time field",
data_type=CUSTOM_TYPE_TIME)
self.cf8.save()
self.obj = SimpleModelWithManager.objects.create(name='old test')
self.obj.save()
def tearDown(self):
CustomFieldsModel.objects.all().delete()
def test_import_class(self):
self.assertEqual(import_class('custard.builder.CustomFieldsBuilder'), CustomFieldsBuilder)
def test_model_repr(self):
self.assertEqual(repr(self.cf), "<CustomFieldsModel: text_field>")
val = CustomValuesModel.objects.create(custom_field=self.cf,
object_id=self.obj.pk,
value="abcdefg")
val.save()
self.assertEqual(repr(val), "<CustomValuesModel: text_field: abcdefg>")
@override_settings(CUSTOM_CONTENT_TYPES=['simplemodelwithmanager'])
def test_field_creation(self):
builder2 = CustomFieldsBuilder('tests.CustomFieldsModel',
'tests.CustomValuesModel',
settings.CUSTOM_CONTENT_TYPES)
class TestCustomFieldsModel(builder2.create_fields()):
class Meta:
app_label = 'tests'
self.assertQuerysetEqual(ContentType.objects.filter(builder2.content_types_query),
ContentType.objects.filter(Q(name__in=['simplemodelwithmanager'])))
def test_mixin(self):
self.assertIn(self.cf, self.obj.get_custom_fields())
self.assertIn(self.cf, SimpleModelWithManager.get_model_custom_fields())
self.assertEqual(self.cf, self.obj.get_custom_field('text_field'))
val = CustomValuesModel.objects.create(custom_field=self.cf,
object_id=self.obj.pk,
value="123456")
val.save()
self.assertEqual("123456", self.obj.get_custom_value('text_field'))
self.obj.set_custom_value('text_field', "abcdefg")
self.assertEqual("abcdefg", self.obj.get_custom_value('text_field'))
val.delete()
def test_field_model_clean(self):
cf = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='another_text_field',
label="Text field already present",
data_type=CUSTOM_TYPE_INTEGER)
with self.assertRaises(ValidationError):
cf.full_clean()
cf = CustomFieldsModel.objects.create(content_type=self.simple_with_manager_ct,
name='name',
label="Text field already in model",
data_type=CUSTOM_TYPE_TEXT)
with self.assertRaises(ValidationError):
cf.full_clean()
def test_value_model_clean(self):
val = CustomValuesModel.objects.create(custom_field=self.cf2,
object_id=self.obj.pk)
val.value = "qwertyuiop"
val.save()
val = CustomValuesModel.objects.create(custom_field=self.cf2,
object_id=self.obj.pk)
val.value = "qwertyuiop"
with self.assertRaises(ValidationError):
val.full_clean()
def test_value_creation(self):
val = CustomValuesModel.objects.create(custom_field=self.cf,
object_id=self.obj.pk,
value="qwertyuiop")
val.save()
self.assertEqual(val.content_type, self.simple_with_manager_ct)
self.assertEqual(val.content_type, val.custom_field.content_type)
self.assertEqual(val.value_text, "qwertyuiop")
self.assertEqual(val.value, "qwertyuiop")
def test_value_search(self):
newobj = SimpleModelWithManager.objects.create(name='new simple')
newobj.save()
v1 = CustomValuesModel.objects.create(custom_field=self.cf,
object_id=self.obj.pk,
value="qwertyuiop")
v1.save()
v2 = CustomValuesModel.objects.create(custom_field=self.cf,
object_id=newobj.pk,
value="qwertyuiop")
v2.save()
v3 = CustomValuesModel.objects.create(custom_field=self.cf,
object_id=newobj.pk,
value="000asdf123")
v3.save()
qs1 = SimpleModelWithManager.objects.search("asdf")
self.assertQuerysetEqual(qs1, [repr(newobj)])
qs2 = SimpleModelWithManager.objects.search("qwerty")
self.assertQuerysetEqual(qs2, [repr(self.obj), repr(newobj)], ordered=False)
def test_value_search_not_searchable_field(self):
v1 = CustomValuesModel.objects.create(custom_field=self.cf,
object_id=self.obj.pk,
value="12345")
v1.save()
v2 = CustomValuesModel.objects.create(custom_field=self.cf2,
object_id=self.obj.pk,
value="67890")
v2.save()
qs1 = SimpleModelWithManager.objects.search("12345")
self.assertQuerysetEqual(qs1, [repr(self.obj)])
qs2 = SimpleModelWithManager.objects.search("67890")
self.assertQuerysetEqual(qs2, [])
def test_get_formfield_for_field(self):
with self.settings(CUSTOM_FIELD_TYPES={CUSTOM_TYPE_TEXT: 'django.forms.fields.EmailField'}):
builder2 = CustomFieldsBuilder('tests.CustomFieldsModel', 'tests.CustomValuesModel')
class SimpleModelWithManagerForm2(builder2.create_modelform(field_types=settings.CUSTOM_FIELD_TYPES)):
class Meta:
model = SimpleModelWithManager
fields = '__all__'
form = SimpleModelWithManagerForm2(data={}, instance=self.obj)
self.assertIsNotNone(form.get_formfield_for_field(self.cf))
self.assertEqual(django.forms.fields.EmailField, form.get_formfield_for_field(self.cf).__class__)
def test_get_widget_for_field(self):
with self.settings(CUSTOM_WIDGET_TYPES={CUSTOM_TYPE_TEXT: 'django.forms.widgets.CheckboxInput'}):
builder2 = CustomFieldsBuilder('tests.CustomFieldsModel', 'tests.CustomValuesModel')
class SimpleModelWithManagerForm2(builder2.create_modelform(widget_types=settings.CUSTOM_WIDGET_TYPES)):
class Meta:
fields = '__all__'
model = SimpleModelWithManager
form = SimpleModelWithManagerForm2(data={}, instance=self.obj)
self.assertIsNotNone(form.get_widget_for_field(self.cf))
self.assertEqual(django.forms.widgets.CheckboxInput, form.get_widget_for_field(self.cf).__class__)
def test_form(self):
class TestForm(builder.create_modelform()):
custom_name = 'My Custom Fields'
custom_description = 'Edit the Example custom fields here'
custom_classes = 'zzzap-class'
class Meta:
fields = '__all__'
model = SimpleModelWithManager
request = self.factory.post('/', { 'text_field': '123' })
form = TestForm(request.POST, instance=self.obj)
self.assertFalse(form.is_valid())
self.assertIn('another_text_field', form.errors)
self.assertRaises(ValueError, lambda: form.save())
request = self.factory.post('/', { 'id': self.obj.pk,
'name': 'xxx',
'another_text_field': 'wwwzzzyyyxxx' })
form = TestForm(request.POST, instance=self.obj)
self.assertTrue(form.is_valid())
form.save()
self.assertEqual(self.obj.get_custom_value('another_text_field'), 'wwwzzzyyyxxx')
self.assertEqual(self.obj.name, 'xxx')
#self.assertInHTML(TestForm.custom_name, form.as_p())
#self.assertInHTML(TestForm.custom_description, form.as_p())
#self.assertInHTML(TestForm.custom_classes, form.as_p())
def test_admin(self):
modeladmin_class = builder.create_modeladmin()
#c = Client()
#if c.login(username='fred', password='secret'):
# response = c.get('/admin/', follow=True)
# print(response)
|
quamilek/django-custard
|
custard/tests/test.py
|
Python
|
mit
| 13,067
|
Console Component
=================
Console eases the creation of beautiful and testable command line interfaces.
The Application object manages the CLI application:
use Symfony\Component\Console\Application;
$console = new Application();
$console->run();
The ``run()`` method parses the arguments and options passed on the command
line and executes the right command.
Registering a new command can easily be done via the ``register()`` method,
which returns a ``Command`` instance:
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
$console
->register('ls')
->setDefinition(array(
new InputArgument('dir', InputArgument::REQUIRED, 'Directory name'),
))
->setDescription('Displays the files in the given directory')
->setCode(function (InputInterface $input, OutputInterface $output) {
$dir = $input->getArgument('dir');
$output->writeln(sprintf('Dir listing for <info>%s</info>', $dir));
})
;
You can also register new commands via classes.
The component provides a lot of features like output coloring, input and
output abstractions (so that you can easily unit-test your commands),
validation, automatic help messages, ...
Resources
---------
You can run the unit tests with the following command:
phpunit -c src/Symfony/Component/Console/
|
richardmiller/symfony
|
src/Symfony/Component/Console/README.md
|
Markdown
|
mit
| 1,537
|
var Notify = require('../')
var tape = require('tape')
var pull = require('pull-stream')
tape('simple', function (t) {
var notify = Notify()
var r = Math.random()
pull(
notify.listen(),
pull.drain(function (data) {
t.equal(data, r)
}, function () {
t.end()
})
)
t.equal(notify(r), r)
notify.end()
})
tape('end', function (t) {
var notify = Notify()
var r = Math.random()
var n = 3
pull(
notify.listen(),
pull.drain(function (data) {
t.equal(data, r)
}, function () {
if (--n) return
t.end()
})
)
pull(
notify.listen(),
pull.drain(function (data) {
t.equal(data, r)
}, function () {
if (--n) return
t.end()
})
)
pull(
notify.listen(),
pull.drain(function (data) {
t.equal(data, r)
}, function () {
if (--n) return
t.end()
})
)
t.equal(notify(r), r)
notify.end()
})
|
dominictarr/pull-notify
|
test/index.js
|
JavaScript
|
mit
| 935
|
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="http://bootswatch.com/yeti/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<title>{{ title }}</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<style>
body {
background-image: url("/footer_lodyas.png");
/*background-size: cover;*/
}
</style>
</head>
<body>
<div class="container">
<nav class="navbar navbar-default navbar-fixed-top">
{% if user != false %}
<div class="container-fluid">
<div class="navbar-nav navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Eagle</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li class="navbar-link"><a href="/event/all">Events List</a></li>
<li class="navbar-link"><a href="/scouting/pit">Pit Scouting</a></li>
<li class="navbar-link"><a href="/scouting/match">Match Scouting</a></li>
<li class="navbar-link"><a href="/comment/new">Add New Comment</a></li>
{% if user.rank >= 9 %}
<li class="navbar-link"><a href="/register">Register User</a></li>
<li class="navbar-link"><a href="/directory">User Directory</a></li>
{% endif %}
<li class="navbar-link"><a href="/logout"><i class="glyphicon glyphicon-log-out"></i> Click to logout</a></li>
</ul>
</div>
</div>
{% endif %}
</nav>
<br>
<div class="jumbotron">
|
CAPS-Robotics/Eagle
|
eagle/templates/partials/header.html
|
HTML
|
mit
| 2,114
|
<?php
namespace Khepin\Medusa\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Command\Command;
use Khepin\Medusa\DependencyResolver;
use Guzzle\Service\Client;
use Khepin\Medusa\Downloader;
use Symfony\Component\Console\Input\ArrayInput;
class MirrorCommand extends Command
{
protected $guzzle;
protected function configure()
{
$this
->setName('mirror')
->setDescription('Mirrors all repositories given a config file')
->setDefinition(array(
new InputArgument('config', InputArgument::OPTIONAL, 'A config file', null),
))
;
}
/**
* @param InputInterface $input The input instance
* @param OutputInterface $output The output instance
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('<info>First getting all dependencies</info>');
$this->guzzle = new Client('http://packagist.org');
$config = json_decode(file_get_contents($input->getArgument('config')));
$repos = [];
foreach($config->require as $dependency){
$output->writeln(' - Getting dependencies for <info>'.$dependency.'</info>');
$resolver = new DependencyResolver($dependency);
$deps = $resolver->resolve();
$repos = array_merge($repos, $deps);
}
$repos = array_unique($repos);
$output->writeln('<info>Create mirror repositories</info>');
foreach($repos as $repo){
$command = $this->getApplication()->find('add');
$arguments = array(
'command' => 'add',
'package' => $repo,
'repos-dir' => $config->repodir,
);
if(!is_null($config->satisconfig)){
$arguments['--config-file'] = $config->satisconfig;
}
$input = new ArrayInput($arguments);
$returnCode = $command->run($input, $output);
}
}
}
|
khepin/medusa
|
src/Khepin/Medusa/Command/MirrorCommand.php
|
PHP
|
mit
| 2,209
|
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\Core\Tests\Serializer;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
use ApiPlatform\Core\Serializer\SerializerContextBuilder;
use Symfony\Component\HttpFoundation\Request;
/**
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class SerializerContextBuilderTest extends \PHPUnit_Framework_TestCase
{
/**
* @var SerializerContextBuilder
*/
private $builder;
protected function setUp()
{
$resourceMetadata = new ResourceMetadata(
null,
null,
null,
[],
[],
['normalization_context' => ['foo' => 'bar'], 'denormalization_context' => ['bar' => 'baz']]
);
$resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class);
$resourceMetadataFactoryProphecy->create('Foo')->willReturn($resourceMetadata);
$this->builder = new SerializerContextBuilder($resourceMetadataFactoryProphecy->reveal());
}
public function testCreateFromRequest()
{
$request = new Request([], [], ['_api_resource_class' => 'Foo', '_api_item_operation_name' => 'get', '_api_format' => 'xml', '_api_mime_type' => 'text/xml']);
$expected = ['foo' => 'bar', 'item_operation_name' => 'get', 'resource_class' => 'Foo', 'request_uri' => '', 'operation_type' => 'item'];
$this->assertEquals($expected, $this->builder->createFromRequest($request, true));
$request = new Request([], [], ['_api_resource_class' => 'Foo', '_api_collection_operation_name' => 'pot', '_api_format' => 'xml', '_api_mime_type' => 'text/xml']);
$expected = ['foo' => 'bar', 'collection_operation_name' => 'pot', 'resource_class' => 'Foo', 'request_uri' => '', 'operation_type' => 'collection'];
$this->assertEquals($expected, $this->builder->createFromRequest($request, true));
$request = new Request([], [], ['_api_resource_class' => 'Foo', '_api_item_operation_name' => 'get', '_api_format' => 'xml', '_api_mime_type' => 'text/xml']);
$expected = ['bar' => 'baz', 'item_operation_name' => 'get', 'resource_class' => 'Foo', 'request_uri' => '', 'api_allow_update' => false, 'operation_type' => 'item'];
$this->assertEquals($expected, $this->builder->createFromRequest($request, false));
$request = new Request([], [], ['_api_resource_class' => 'Foo', '_api_collection_operation_name' => 'post', '_api_format' => 'xml', '_api_mime_type' => 'text/xml'], [], [], ['REQUEST_METHOD' => 'POST']);
$expected = ['bar' => 'baz', 'collection_operation_name' => 'post', 'resource_class' => 'Foo', 'request_uri' => '', 'api_allow_update' => false, 'operation_type' => 'collection'];
$this->assertEquals($expected, $this->builder->createFromRequest($request, false));
$request = new Request([], [], ['_api_resource_class' => 'Foo', '_api_collection_operation_name' => 'put', '_api_format' => 'xml', '_api_mime_type' => 'text/xml'], [], [], ['REQUEST_METHOD' => 'PUT']);
$expected = ['bar' => 'baz', 'collection_operation_name' => 'put', 'resource_class' => 'Foo', 'request_uri' => '', 'api_allow_update' => true, 'operation_type' => 'collection'];
$this->assertEquals($expected, $this->builder->createFromRequest($request, false));
$request = new Request([], [], ['_api_resource_class' => 'Foo', '_api_subresource_operation_name' => 'get', '_api_format' => 'xml', '_api_mime_type' => 'text/xml'], [], [], ['REQUEST_METHOD' => 'GET']);
$expected = ['bar' => 'baz', 'subresource_operation_name' => 'get', 'resource_class' => 'Foo', 'request_uri' => '', 'operation_type' => 'subresource', 'api_allow_update' => false];
$this->assertEquals($expected, $this->builder->createFromRequest($request, false));
}
/**
* @expectedException \ApiPlatform\Core\Exception\RuntimeException
*/
public function testThrowExceptionOnInvalidRequest()
{
$this->builder->createFromRequest(new Request(), false);
}
public function testReuseExistingAttributes()
{
$expected = ['bar' => 'baz', 'item_operation_name' => 'get', 'resource_class' => 'Foo', 'request_uri' => '', 'api_allow_update' => false, 'operation_type' => 'item'];
$this->assertEquals($expected, $this->builder->createFromRequest(new Request(), false, ['resource_class' => 'Foo', 'item_operation_name' => 'get']));
}
}
|
tuanphpvn/core
|
tests/Serializer/SerializerContextBuilderTest.php
|
PHP
|
mit
| 4,763
|
// Program part for parsing the input
#include <iostream>
#include <seqan/sequence.h>
#include <seqan/seq_io.h>
using namespace seqan;
int main(int argc, char const ** argv)
{
/*if (argc < 2)
{
std::cerr << "Please input the path to the input file as first argument.\n";
return 1;
}*/
//StringSet<seqan::CharString> ids;
//StringSet<seqan::Dna5String> seqs;
//StringSet<seqan::CharString> quals;
//int res = 0;
/*SequenceStream seqStream(argv[1]);*/
/*if (!isGood(seqStream))
{
std::cerr << "Error while opening the input file.\n";
return 1;
}*/
//if(!readBatch(ids, seqs, quals, seqStream, 10)) //Verursacht iwie noch probleme
//{
// std::cerr << "Error while reading the sequences.\n";
// return 1;
//}
return 0;
}
|
bkahlert/seqan-research
|
raw/pmsb13/pmsb13-data-20130530/sources/24xc47o54r0zzgyu/2013-04-26T09-24-47.891+0200/sandbox/my_sandbox/apps/SeqDPT/input.cpp
|
C++
|
mit
| 783
|
---
layout: default
title: Набор проблем 4. Экспертиза. Recover (Восстановление).
---
# Recover (Восстановление)
## Коротко
Реализуйте программу, которая будет восстанавливать JPEG'и из образа карты памяти, как указано ниже.
```
$ ./recover card.raw
```
## Объяснение
В ожидании этой проблемы, я провел последние несколько дней фотографируя своих знакомых, изображения которых были сохранены моей цифровой камерой в виде JPEG'ов на карте памяти (ну ладно, скорее всего я провел последние несколько дней просматривая мемы на Facebook'е). К сожалению, я каким-то непонятным образом удалил все фотографии! Но, к счастью, в компьютерном мире, слово "удалил" не подразумевает под собой "удалено", а скорее "забыто". Мой компьютер настаивает на том, что на карте теперь ничего нету, но я уверен что это не правда . Я надеюсь, что вы сможете написать для меня программу, восстанавливающую фотографии!
Хоть JPEG'и в своей структуре намного сложнее BMP, у JPEG'ов есть "подписи" (шаблоны байтов), которые отличают их от других файловых форматов. Все JPEG'и начинаются с трех байтов, слева направо:
```
0xff 0xd8 0xff
```
Четвертый байт может иметь следующие значения: `0xe0`, `0xe1`, `0xe2`, `0xe3`, `0xe4`, `0xe5`, `0xe6`, `0xe7`, `0xe8`, `0xe8`, `0xe9`, `0xea`, `0xeb`, `0xec`, `0xed`, `0xee`, `0xef`. Заметьте, первые четыре бита четвертого байта везде равны `1110`.
Вполне вероятно, если вы найдете этот шаблон из 4 байтов на медианосителе (т.е. на моей карте памяти), что они будут обозначать начало JPEG'а. Конечно, на каком-либо другом диске, вы наткнулись бы на данные шаблоны чисто случайным образом, поэтому восстановление данных не может быть точной наукой.
К счастью, цифровые камеры имеют привычку последовательно хранить фотографии на карте памяти. Каждая фотография сохраняется сразу за предыдущей. Поэтому начало одного JPEG'а обычно говорит о конце другого JPEG'а. Цифровые камеры часто инициализируют карты задавая им файловую систему FAT, в котором "размер одного блока" равен 512 байтам (Б). Суть в том, что эти камеры записывают данные на карты памяти по 512 Б. Таким образом фотография размером в 1 MB (т.е. 1,048,576 Б) занимает 1048576 ÷ 512 = 2048 "блоков" на карте памяти. Но проблема в том, что такое же количество блоков займет файл с размером в один байт меньше предыдущего (т.е. 1,048,575 Б)! Незаполненное дисковое пространство называют "провисающим пространством" ("slack space"). Судебные следователи часто используют эту особенность для нахождения остатков подозрительных веществ.
Суть всех этих деталей в том, что вы, как следователь, скорее всего сможете написать программу, которая будет итерировать копию моей карты памяти, ищя подписи (признаки) JPEG'ов. Каждый раз находя подпись, вы можете открывать новый записываемый файл и начинать заполнять этот файл байтами, которые будут браться из моей карты памяти. При этом закрывать этот файл будете только тогда, когда найдется другая подпись. Более того, для эффективности, вместо того чтобы читать по одному байту за раз, вы можете считывать в буфер по 512 байтов. Благодаря файловой системе FAT, вы можете быть уверены, что подписи JPEG-файлов будут "по блокам выровненными". Т.е. вам нужно будет искать эти подписи только в первых четырех байтах блока.
JPEG'и состоят из смежных блоков. В противном случае, ни один JPEG не смог бы быть больше 512 Б. Может быть и такое, что последний байт JPEG'а может не оказаться в самом конце блока. Вспомните "провисание пространства". Но не беспокойтесь об этом. Так как карта-памяти была совершенно новой, когда я начал "щелкать" фотографии, поэтому, вполне вероятно, что эти пространства "обнулены" (то есть заполнены нулями) производителем. Это хорошо, если эти нули окажутся в восстановленных вами JPEG'ах. Эти файлы по-прежнему должны будут быть доступными для просмотра.
Так, у меня есть только одна карта памяти, а вас не так уж и мало! Я все заранее продумал и создал для вас образ (файл) карты памяти, в котором хранится весь контент, байт за байтом, и этот файл называется `card.raw`. Чтобы вам не пришлось перебирать миллионы лишних нулей, я сделал образ только первых нескольких мегабайт карты памяти. В конечном итоге, у вас должно будет восстановиться 50 JPEG-изображений.
## Развертывание
### Скачивание
```
$ mkdir recover
$ cd recover
$ wget http://cdn.cs50.net/2016/fall/psets/4/pset4/card.raw
$ ls
card.raw
```
## Описание
Создайте программу под названием `recover`, которая будет восстанавливать JPEG'и с образа карты-памяти.
Реализуйте вашу программу в файле `recover.c`, которая должна будет находиться в папке `recover`.
Ваша программа должна принимать ровно один аргумент командной строки - название образа карты-памяти, с которого будет происходить восстановление JPEG'ов. + если вашу программу запустили ненадлежащим образом (с меньшим или большим числом аргументов), она должна оповестить об этом пользователя, используя `fprintf` (с `stderr`). При этом функция `main` должна вернуть `1`.
Если образ невозможно открыть для чтения, ваша программа должна сообщить об этом пользователя, используя `fprintf` (с `stderr`). При этом функция `main` должна вернуть `2`.
Если ваша программа будет пользоваться функцией `malloc`, вы должны будете позаботиться о том, чтобы не возникло никаких утечек памяти.
## Использование
Ваша программа должна проделывать тоже самое, что показано в примере ниже.
```
$ ./recover
Usage (Использование): ./recover image
$ echo $?
1
```
```
$ ./recover card.raw
$ echo $?
0
```
## Проверка
```
check50 cs50/2017/x/recover
```
## Подсказки
Вполне вероятно, что вы захотите начать решать задание с создания файла под названием `recover.c` (в той же папке что и `card.raw`). Вам не понадобится библиотека CS50, но вам лучше объявить функцию `main` таким образом, что она будет поддерживать аргументы командной строки. (Помните как?)
Вы всегда можете открыть `card.raw` программным способом с помощью `fopen`, как показано ниже, главное чтобы `argv[1]` существовал.
```
FILE *file = fopen(argv[1], "r");
```
При выполнении, ваша программа должа восстановить каждое JPEG-изображения, хранящееся на `card.raw`, далее отдельно сохраняя каждый файл в вашей текущей рабочей директории (папке). Ваша программа должна пронумеровать выходные файлы, задавая каждому следующее имя `###.jpg`, где `###` представляют из себя три целых десятичных числа, начиная с `000` и далее (001, 002...). Не нужно восстанавливать оригинальные имена JPEG-изображений. Чтобы проверить на наличие ошибок в фотографиях, которые ваша программа произвела, просто дважды щелкните по ней и посмотрите! Если изображение есть, значит все прошло успешно!
Хотя, вполне вероятно, что первые JPEG'и, которые "выплюнет" ваш (в начале) ошибочный код, окажутся некорректными (Если вы откроете фотографии и ничего не увидите, очень высока вероятность, что они дефектные). Выполните нижеприведенную команду, чтобы удалить все JPEG'и в вашей текущей рабочей директории.
```
rm *.jpg
```
Если вы не хотите, чтобы вас каждый раз просили подтвердить удаление, выполните следующую команду.
```
rm -f *.jpg
```
Будьте осторожнее с переключателем `-f`, так как он "forces" (заставляет) удалять файлы, без вашего подтверждения.
|
stshmakov/stshmakov.github.io
|
_pages/problems/recover/index.md
|
Markdown
|
mit
| 12,156
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""zigzi, Platform independent binary instrumentation module.
Copyright (c) 2016-2017 hanbum park <kese111@gmail.com>
All rights reserved.
For detailed copyright information see the file COPYING in the root of the
distribution archive.
"""
import argparse
from PEInstrument import *
from PEAnalyzeTool import *
from PEManager import *
from keystone import *
from DataSegment import *
from SampleReturnVerifier import *
from WindowAPIHelper import *
code_rva = 0
def simple_return_address_save_function():
global code_rva
allocation = pe_instrument.falloc(0x1000)
code = ("push eax;push ebx;" # save register
"mov eax, [{0}];" # get shadow stack counter
"inc eax;" # increase shadow stack counter
"" # get return address from stack
"mov [{0}], eax;" # save return address
"pop ebx;pop eax;" # restore register
"ret;" # return
).format(allocation.get_va() + 4)
code_rva = pe_instrument.append_code(code)
code_abs_va = pe_manager.get_abs_va_from_rva(code_rva)
allocation[0:4] = code_abs_va
# TODO : need a way for does not calculate the relocation address directly.
pe_manager.register_rva_to_relocation(code_rva + 1 + 1)
pe_manager.register_rva_to_relocation(code_rva + 7 + 1)
def simple_indirect_branch_counting_function_call_instrument(instruction):
global code_rva
code_zero_rva = code_rva - 0x1000
instruction_zero_rva = instruction.address
# 5 mean instrumented code size.
code = "CALL {:d}".format(code_zero_rva - instruction_zero_rva + 5)
hex_code = binascii.hexlify(code).decode('hex')
try:
# Initialize engine in X86-32bit mode
ks = Ks(KS_ARCH_X86, KS_MODE_32)
encoding, count = ks.asm(hex_code)
return encoding, count
except KsError as ex:
print("ERROR: %s" % ex)
return None, 0
def simple_indirect_branch_counting_function_instrument():
global code_rva
allocation = pe_instrument.falloc(0x1000)
code = ("push eax;"
"mov eax, [{0}];"
"inc eax;"
"mov [{0}], eax;"
"pop eax;"
"ret;").format(allocation.get_va() + 4)
code_rva = pe_instrument.append_code(code)
code_abs_va = pe_manager.get_abs_va_from_rva(code_rva)
allocation[0:4] = code_abs_va
# TODO : need a way for does not calculate the relocation address directly.
pe_manager.register_rva_to_relocation(code_rva + 1 + 1)
pe_manager.register_rva_to_relocation(code_rva + 7 + 1)
def do_indirect_branch_counting():
simple_indirect_branch_counting_function_instrument()
pe_instrument.register_pre_indirect_branch(
simple_indirect_branch_counting_function_call_instrument
)
def do_return_address_verifier(pe_instrument, pe_manager, fn_rva):
simple_instrument_error_handler(pe_instrument, pe_manager, fn_rva)
pe_instrument.register_after_relative_branch(
simple_instrument_return_address_at_after_branch
)
pe_instrument.register_after_indirect_branch(
simple_instrument_return_address_at_after_branch
)
pe_instrument.register_pre_return(
simple_instrument_return_address_verifier_at_pre_return
)
pe_instrument.do_instrument()
if __name__ == '__main__':
parser = argparse.ArgumentParser("zigzi")
parser.add_argument("file",
help="filename include its absolute path.",
type=str)
args = parser.parse_args()
filename = args.file
if not os.path.isfile(filename):
parser.print_help()
exit()
pe_manager = PEManager(filename)
# add api
window_api_helper = WindowAPIHelper(pe_manager)
message_box_fn_rva = window_api_helper.add_message_box()
# set new instrumentation
pe_instrument = PEInstrument(pe_manager)
do_return_address_verifier(pe_instrument, pe_manager, message_box_fn_rva)
# do_indirect_branch_counting()
# TODO : change to avoid duplicate processing.
# do not double adjustment for file, it break file layout.
# pe_manager.adjust_file_layout()
output_filename = filename[:-4] + "_after_test.exe"
pe_manager.writefile(output_filename)
pe_instrument._save_instruction_log()
# C:\work\python\zigzi\tests\simple_echo_server.exe
|
ParkHanbum/zigzi
|
__init__.py
|
Python
|
mit
| 4,427
|
# hackcourses
Short assignments for the hackbulgaria courses.
|
NJichev/hackcourses
|
README.md
|
Markdown
|
mit
| 62
|
/*!
* wyre: the new way to do websockets
* Copyright(c) 2015 Jordan S Davidson <thatoneemail@gmail.com>
* MIT Licensed
*/
var port = 22345;
exports = module.exports = function() {
return port++;
}
|
from-nibly/wyre
|
test/portGetter.js
|
JavaScript
|
mit
| 203
|
package sourcemap
import (
"io"
)
type (
RuneReader interface {
ReadRune() (r rune, size int, err error)
}
RuneWriter interface {
WriteRune(r rune) (size int, err error)
}
Segment struct {
GeneratedLine int
GeneratedColumn int
SourceIndex int
SourceLine int
SourceColumn int
NameIndex int
}
)
var (
hexc = "0123456789abcdef"
)
func encodeString(rw RuneWriter, rr RuneReader) error {
for {
r, _, err := rr.ReadRune()
if err == io.EOF {
return nil
} else if err != nil {
return err
}
switch r {
case '\\', '"':
rw.WriteRune('\\')
_, err = rw.WriteRune(r)
case '\n':
rw.WriteRune('\\')
_, err = rw.WriteRune('n')
case '\r':
rw.WriteRune('\\')
_, err = rw.WriteRune('r')
case '\t':
rw.WriteRune('\\')
_, err = rw.WriteRune('t')
case '\u2028':
rw.WriteRune('\\')
rw.WriteRune('u')
rw.WriteRune('2')
rw.WriteRune('0')
rw.WriteRune('2')
_, err = rw.WriteRune('8')
case '\u2029':
rw.WriteRune('\\')
rw.WriteRune('u')
rw.WriteRune('2')
rw.WriteRune('0')
rw.WriteRune('2')
_, err = rw.WriteRune('9')
default:
if r < 0x20 {
rw.WriteRune('\\')
rw.WriteRune('u')
rw.WriteRune('0')
rw.WriteRune('0')
rw.WriteRune(rune(hexc[byte(r)>>4]))
_, err = rw.WriteRune(rune(hexc[byte(r)&0xF]))
} else {
_, err = rw.WriteRune(r)
}
}
if err != nil {
return err
}
}
}
|
badgerodon/sourcemap
|
util.go
|
GO
|
mit
| 1,428
|
require('es6-promise').polyfill();
var expect = require('expect.js');
var sinon = require('sinon');
var mockery = require('mockery');
describe('Incident controller: GET', function () {
var incident = require('./incidents');
it('has GET handler', function () {
expect(typeof(incident.GET)).equal('function');
});
it('resonds to /', function () {
var req = res = {};
res.send = sinon.spy();
incident.GET(req, res);
expect(res.send.calledOnce).to.equal(true);
});
});
describe('Incident controller: POST', function () {
var incidents;
before(function() {
mockery.registerMock('../models/incident', function () {
var model = function () {};
model.prototype = {
save: function () {
console.warn('Should be overriden with sinon.stub');
throw new Error('Not implemented');
}
};
return model;
}());
// mock the error reporter
mockery.enable({
warnOnReplace: false,
warnOnUnregistered: false,
useCleanCache: true
});
incidents = require('./incidents');
});
afterEach(function () {
// var Incident = require('../models/incident');
// Incident.prototype.save.restore();
});
after(function() {
// disable mock after tests complete
mockery.disable();
});
it('has POST handler', function () {
expect(typeof(incidents.POST)).equal('function');
});
it('creates new incident properly', function (done) {
// Why it's called unittest?
// Because we know all about the internal implementation of the unit.
var Incident = require('../models/incident');
var mockedIncident = {
__v: 0,
_id: 'abc123',
type: 'accident',
location: {
latlng: [1,2],
spec: {
placeid: '123',
administrative_area_level_1: 'Ho Chi Minh City',
country: 'Vietnam'
}
}
};
sinon.stub(Incident.prototype, 'save').returns(Promise.resolve(mockedIncident))
var req = {
body: {
type: 'accident',
location: {
latlng: [1,2],
spec: {
placeid: '123',
administrative_area_level_1: 'Ho Chi Minh City',
country: 'Vietnam'
}
}
}
};
var res = {};
res.send = sinon.spy();
// Perform the tested action
incidents.POST(req, res);
process.nextTick(function() {
expect(Incident.prototype.save.calledOnce).to.equal(true);
// TODO Fix the assertion
expect(res.send.calledOnce).to.equal(true);
Incident.prototype.save.restore();
done();
});
});
it('generates error for improper incident data: No JSON body', function (done) {
// Why it's called unittest?
// Because we know all about the internal implementation of the unit.
var Incident = require('../models/incident');
sinon.stub(Incident.prototype, 'save').returns(Promise.reject({ message: 'Invalid data' }));
var req = {
body: null
};
var send = sinon.spy();
var status = sinon.stub().returns({ send: send }) ;
var res = {
status: status
};
// Perform the tested action
incidents.POST(req, res);
process.nextTick(function() {
expect(Incident.prototype.save.callCount).to.equal(0);
// TODO Fix the assertion
expect(status.calledWith(400)).to.equal(true);
expect(send.calledWith('Invalid data')).to.equal(true);
Incident.prototype.save.restore();
done();
});
});
it('generates error for improper incident data: No type', function (done) {
// Why it's called unittest?
// Because we know all about the internal implementation of the unit.
var Incident = require('../models/incident');
sinon.stub(Incident.prototype, 'save').returns(Promise.reject({ message: 'Invalid data' }));
var req = {
body: {
location: {
latlng: [1,2],
spec: {
placeid: '123',
administrative_area_level_1: 'Ho Chi Minh City',
country: 'Vietnam'
}
}
}
};
var send = sinon.spy();
var status = sinon.stub().returns({ send: send }) ;
var res = {
status: status
};
// Perform the tested action
incidents.POST(req, res);
process.nextTick(function() {
expect(Incident.prototype.save.callCount).to.equal(0);
// TODO Fix the assertion
expect(status.calledWith(400)).to.equal(true);
expect(send.calledWith('Invalid data')).to.equal(true);
Incident.prototype.save.restore();
done();
});
});
it('generates error for improper incident data: No latlng', function (done) {
// Why it's called unittest?
// Because we know all about the internal implementation of the unit.
var Incident = require('../models/incident');
sinon.stub(Incident.prototype, 'save').returns(Promise.reject({ message: 'Invalid data' }));
var req = {
body: {
type: 'accident',
location: {
spec: {
placeid: '123',
administrative_area_level_1: 'Ho Chi Minh City',
country: 'Vietnam'
}
}
}
};
var send = sinon.spy();
var status = sinon.stub().returns({ send: send }) ;
var res = {
status: status
};
// Perform the tested action
incidents.POST(req, res);
process.nextTick(function() {
expect(Incident.prototype.save.callCount).to.equal(0);
// TODO Fix the assertion
expect(status.calledWith(400)).to.equal(true);
expect(send.calledWith('Invalid data')).to.equal(true);
Incident.prototype.save.restore();
done();
});
});
it('generates error for improper incident data: No location', function (done) {
// Why it's called unittest?
// Because we know all about the internal implementation of the unit.
var Incident = require('../models/incident');
sinon.stub(Incident.prototype, 'save').returns(Promise.reject({ message: 'Invalid data' }));
var req = {
body: {
type: 'accident'
}
};
var send = sinon.spy();
var status = sinon.stub().returns({ send: send }) ;
var res = {
status: status
};
// Perform the tested action
incidents.POST(req, res);
process.nextTick(function() {
expect(Incident.prototype.save.callCount).to.equal(0);
// TODO Fix the assertion
expect(status.calledWith(400)).to.equal(true);
expect(send.calledWith('Invalid data')).to.equal(true);
Incident.prototype.save.restore();
done();
});
});
});
|
FatmanDesigner/dirty-corners-api
|
app/routes/incidents.spec.js
|
JavaScript
|
mit
| 7,982
|
The BeforeBuild build step on the JavaScript tests project should execute a command that generate a `.d.ts` file and sticks it here. (If all is good)
|
ToTypeScriptD/ToTypeScriptD
|
src/ToTypeScriptD.Tests.JavascriptTests/Scripts/typings/ToTypeScriptD.Native/Readme.md
|
Markdown
|
mit
| 151
|
package com.ame.bus3.client;
import com.ame.bus3.common.*;
import com.ame.bus3.common.Tiles.Wall;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.util.HashMap;
/**
* Renders the tiles on the screen.
* @author Amelorate
*/
public class TileRenderer implements Renderer {
@SuppressWarnings({"WeakerAccess", "CanBeFinal"})
public Coordinate[] renderLayers = {new Coordinate(0, 0, 0, "default")};
private static final int PIXELS_PER_TILE = 48;
public TileRenderer() {
RendererController.register("TileRender", this);
}
@Override
public void render(SpriteBatch batch, World world) {
throw new NotImplementedException();
}
}
|
Ameliorate/Buildstation-3
|
core/src/com/ame/bus3/client/TileRenderer.java
|
Java
|
mit
| 766
|
---
title: UC Block Storage
---
# Universally Composable Block Storage
### Kyle Hogan, Mayank Varia, Ran Canetti
---
## Introduction to Universal Composability
* Point 1
* Point 2
> This is a quote
Note: this is a hidden speaker note
==
## Intro UC pt 2
---
## Introduction to Block Storage
==
## Security for Block Storage
==
It isn't running by itself...
---
## Security Analysis of a Cloud
==
# Clouds are Big
==
Note: show openstack
==
* Many components - block storage is just one
* Modular Analysis - analyzing it as a whole is too much
==
## Implementation
### A single component could have many different implemetations
==
## Implementation: iSCSI vs Ceph
---
## Applying UC - why
==
## Block Storage - general
==
## Show different implemetations match general
---
## Conclusion
### Process for each component
|
kylehogan/slides
|
_slides/uc_block.md
|
Markdown
|
mit
| 857
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="icon" type="image/png" href="images/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="images/favicon-16x16.png" sizes="16x16" />
<link href='css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='css/reset.css' media='print' rel='stylesheet' type='text/css'/>
<link href='css/print.css' media='print' rel='stylesheet' type='text/css'/>
<script src='lib/object-assign-pollyfill.js' type='text/javascript'></script>
<script src='lib/jquery-1.8.0.min.js' type='text/javascript'></script>
<script src='lib/jquery.slideto.min.js' type='text/javascript'></script>
<script src='lib/jquery.wiggle.min.js' type='text/javascript'></script>
<script src='lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
<script src='lib/handlebars-4.0.5.js' type='text/javascript'></script>
<script src='lib/lodash.min.js' type='text/javascript'></script>
<script src='lib/backbone-min.js' type='text/javascript'></script>
<script src='swagger-ui.js' type='text/javascript'></script>
<script src='lib/highlight.9.1.0.pack.js' type='text/javascript'></script>
<script src='lib/highlight.9.1.0.pack_extended.js' type='text/javascript'></script>
<script src='lib/jsoneditor.min.js' type='text/javascript'></script>
<script src='lib/marked.js' type='text/javascript'></script>
<script src='lib/swagger-oauth.js' type='text/javascript'></script>
<!-- Some basic translations -->
<!-- <script src='lang/translator.js' type='text/javascript'></script> -->
<!-- <script src='lang/ru.js' type='text/javascript'></script> -->
<!-- <script src='lang/en.js' type='text/javascript'></script> -->
<script type="text/javascript">
$(function () {
var url = window.location.search.match(/url=([^&]+)/);
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
} else {
// url = "http://petstore.swagger.io/v2/swagger.json";
url = 'json';
}
hljs.configure({
highlightSizeThreshold: 5000
});
// Pre load translate...
if(window.SwaggerTranslator) {
window.SwaggerTranslator.translate();
}
window.swaggerUi = new SwaggerUi({
url: url,
dom_id: "swagger-ui-container",
supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
onComplete: function(swaggerApi, swaggerUi){
if(typeof initOAuth == "function") {
initOAuth({
clientId: "your-client-id",
clientSecret: "your-client-secret-if-required",
realm: "your-realms",
appName: "your-app-name",
scopeSeparator: " ",
additionalQueryStringParams: {}
});
}
if(window.SwaggerTranslator) {
window.SwaggerTranslator.translate();
}
},
onFailure: function(data) {
log("Unable to Load SwaggerUI");
},
docExpansion: "none",
jsonEditor: false,
defaultModelRendering: 'schema',
showRequestHeaders: false
});
window.swaggerUi.load();
function log() {
if ('console' in window) {
console.log.apply(console, arguments);
}
}
});
</script>
</head>
<body class="swagger-section">
<div id='header'>
<div class="swagger-ui-wrap">
<a id="logo" href="http://swagger.io"><img class="logo__img" alt="swagger" height="30" width="30" src="images/logo_small.png" /><span class="logo__title">swagger</span></a>
<!--<form id='api_selector'>
<div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
<div id='auth_container'></div>
<div class='input'><a id="explore" class="header__btn" href="#" data-sw-translate>Explore</a></div>
</form>-->
</div>
</div>
<div id="message-bar" class="swagger-ui-wrap" data-sw-translate> </div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>
|
jeffmarston/fixalicious-ui
|
server/docs/index.html
|
HTML
|
mit
| 4,278
|
ALTER TABLE PLACE
MODIFY COLUMN LATITUDE DOUBLE(10, 6) NOT NULL;
ALTER TABLE PLACE
MODIFY COLUMN LONGITUDE DOUBLE(10, 6) NOT NULL;
ALTER TABLE READING
MODIFY COLUMN LATITUDE DOUBLE(10, 6) NOT NULL;
ALTER TABLE READING
MODIFY COLUMN LONGITUDE DOUBLE(10, 6) NOT NULL;
|
mwcaisse/car-tracker-server
|
CarTracker/Database/VersionedScripts/V0005_UpdatePlace_LatLon.sql
|
SQL
|
mit
| 277
|
import { createReducer } from '../utils/misc';
import {
CHAT_MESSAGES_SUCCESS,
CHAT_MESSAGES_FAILURE,
CHAT_MESSAGES_REQUEST,
FRIEND_LIST_SUCCESS,
FRIEND_LIST_FAILURE,
FRIEND_LIST_REQUEST,
FRIEND_HISTORY_REQUEST,
FRIEND_HISTORY_SUCCESS,
FRIEND_HISTORY_FAILURE,
ADD_FRIEND_SUCCESS,
ADD_FRIEND_FAILURE,
ADD_FRIEND_REQUEST,
NEW_CHAT_CHANNEL,
ADD_MESSAGE,
SET_IS_PARTY,
PARTY_LIST_SUCCESS,
PARTY_LIST_FAILURE,
PARTY_LIST_REQUEST,
PARTY_HISTORY_REQUEST,
PARTY_HISTORY_SUCCESS,
PARTY_HISTORY_FAILURE,
ADD_PARTY_SUCCESS,
ADD_PARTY_FAILURE,
ADD_PARTY_REQUEST,
} from '../constants/index';
const initialState = {
party_name: 'Lobby',
party_id: -1,
receiver: null,
friendlist: [],
friendListStatusText: null,
friendHistoryStatusText: null,
messages: [],
allMessages: {},
messagesStatusText: null,
addFriendStatusText: null,
isParty: true,
partylist: [],
partyListStatusText: null,
addPartyStatusText: null,
};
export default createReducer(initialState, {
[CHAT_MESSAGES_REQUEST]: (state) =>
Object.assign({}, state, {
messagesStatusText: null,
}),
[CHAT_MESSAGES_SUCCESS]: (state) => {
console.log('chatmessagesuccess.');
return Object.assign({}, state, {
messagesStatusText: 'messages retreived successfully.',
}); },
[CHAT_MESSAGES_FAILURE]: (state) =>
Object.assign({}, state, {
messagesStatusText: 'error retreiving messages.',
}),
[FRIEND_LIST_REQUEST]: (state) =>
Object.assign({}, state, {
friendListStatusText: null,
}),
[FRIEND_LIST_SUCCESS]: (state, payload) => {
console.log('friendlistsuccess.');
console.dir(payload);
return Object.assign({}, state, {
friendListStatusText: 'friendlist retreived successfully.',
friendlist: payload.data,
}); },
[FRIEND_LIST_FAILURE]: (state) =>
Object.assign({}, state, {
friendListStatusText: 'error retreiving friendlist.',
}),
[FRIEND_HISTORY_REQUEST]: (state) =>
Object.assign({}, state, {
friendHistoryStatusText: null,
}),
[FRIEND_HISTORY_SUCCESS]: (state, payload) => {
if (state.allMessages[payload.party_name].length > 1) { return state; }
console.log('friendhistorysuccess.');
console.dir(payload);
const newstate = Object.assign({}, state, {
allMessages: Object.assign({}, state.allMessages, { [payload.party_name]: state.allMessages[payload.party_name].slice().concat(payload.messages) }),
messages: state.allMessages[payload.party_name].slice().concat(payload.messages),
friendHistoryStatusText: 'friend history retreived successfully.',
});
return newstate;
},
[FRIEND_HISTORY_FAILURE]: (state) =>
Object.assign({}, state, {
friendHistoryStatusText: 'error retreiving friend history.',
}),
[NEW_CHAT_CHANNEL]: (state, payload) => {
console.log('In NEW_CHAT_CHANNEL reducer');
console.dir(payload);
const updatedAllMessages = Object.assign({}, ({ [payload.party_name]: [] }), state.allMessages);
console.log('allmessages: ');
console.dir(updatedAllMessages);
const updatedMessages = updatedAllMessages[payload.party_name].slice();
console.log('messages: ');
console.dir(updatedMessages);
const newstate = Object.assign({}, state, {
party_name: payload.party_name,
party_id: payload.party_id,
allMessages: updatedAllMessages,
messages: updatedMessages,
messagesStatusText: null,
});
// console.log('----__------__');
// console.dir(newstate);
return newstate;
},
[ADD_MESSAGE]: (state, payload) => {
console.log('In ADD_MESSAGE reducer');
console.dir(payload);
return Object.assign({}, state, {
allMessages: Object.assign({}, state.allMessages, { [payload.party_name]: state.allMessages[payload.party_name].slice().concat([payload.message]) }),
messages: state.allMessages[payload.party_name].slice().concat([payload.message]),
messagesStatusText: null,
}); },
[ADD_FRIEND_REQUEST]: (state) =>
Object.assign({}, state, {
addFriendStatusText: null,
}),
[ADD_FRIEND_SUCCESS]: (state) => {
console.log('addfriend success.');
return Object.assign({}, state, {
addFriendStatusText: 'addFriend done successfully.',
}); },
[ADD_FRIEND_FAILURE]: (state) =>
Object.assign({}, state, {
addFriendStatusText: 'error adding a friend.',
}),
[SET_IS_PARTY]: (state, payload) =>
Object.assign({}, state, {
isParty: payload.isParty,
receiver: payload.receiver,
}),
[PARTY_LIST_REQUEST]: (state) =>
Object.assign({}, state, {
partyListStatusText: null,
}),
[PARTY_LIST_SUCCESS]: (state, payload) => {
console.log('partylistsuccess.');
console.dir(payload);
return Object.assign({}, state, {
partyListStatusText: 'partylist retreived successfully.',
partylist: payload.data,
}); },
[PARTY_LIST_FAILURE]: (state) =>
Object.assign({}, state, {
partyListStatusText: 'error retreiving partylist.',
}),
[PARTY_HISTORY_REQUEST]: (state) =>
Object.assign({}, state, {
partyHistoryStatusText: null,
}),
[PARTY_HISTORY_SUCCESS]: (state, payload) => {
if (state.allMessages[payload.party_name].length > 1) { return state; }
console.log('partyhistorysuccess.');
console.dir(payload);
const newstate = Object.assign({}, state, {
allMessages: Object.assign({}, state.allMessages, { [payload.party_name]: state.allMessages[payload.party_name].slice().concat(payload.messages) }),
messages: state.allMessages[payload.party_name].slice().concat(payload.messages),
partyHistoryStatusText: 'party history retreived successfully.',
});
return newstate;
},
[PARTY_HISTORY_FAILURE]: (state) =>
Object.assign({}, state, {
partyHistoryStatusText: 'error retreiving party history.',
}),
[ADD_PARTY_REQUEST]: (state) =>
Object.assign({}, state, {
addPartyStatusText: null,
}),
[ADD_PARTY_SUCCESS]: (state) => {
console.log('addparty success.');
return Object.assign({}, state, {
addPartyStatusText: 'addParty done successfully.',
}); },
[ADD_PARTY_FAILURE]: (state) =>
Object.assign({}, state, {
addPartyStatusText: 'error adding a party.',
}),
});
|
morrishopkins/test_spa
|
src/reducers/chat.js
|
JavaScript
|
mit
| 6,683
|
$(document).ready(function () {
$(".courses").each(function () {
var courseClass = ['course-blue', 'course-red', 'course-green', 'course-peach', 'course-darck-green', 'course-darck-blue', 'course-purple', 'course-orange'];
var rand = courseClass[Math.floor(Math.random() * courseClass.length)];
$(this).addClass(rand);
});
});
|
bugsancho/Academy-Platform
|
AcademyPlatform.Web/Scripts/Custom.js
|
JavaScript
|
mit
| 362
|
# SwiftLibraries
Swift sample code that displays a list of libraries in Chicago from the city's public data source
|
lingoslinger/SwiftLibraries
|
README.md
|
Markdown
|
mit
| 115
|
<header class="symbol-info-header"><h1 id="expressapplication">ExpressApplication</h1><label class="symbol-info-type-label decorator">Decorator</label></header>
<!-- summary -->
<section class="symbol-info"><table class="is-full-width"><tbody><tr><th>Module</th><td><div class="lang-typescript"><span class="token keyword">import</span> { ExpressApplication } <span class="token keyword">from</span> <span class="token string">"@tsed/common"</span></div></td></tr><tr><th>Source</th><td><a href="https://github.com/Romakita/ts-express-decorators/blob/v4.12.0/src//common/mvc/decorators/class/expressApplication.ts#L0-L0">/common/mvc/decorators/class/expressApplication.ts</a></td></tr></tbody></table></section>
<!-- overview -->
### Overview
<pre><code class="typescript-lang ">type ExpressApplication = Express.Application<span class="token punctuation">;</span>
function <span class="token function">ExpressApplication</span><span class="token punctuation">(</span>target<span class="token punctuation">:</span> <a href="#api/core/type"><span class="token">Type</span></a><<span class="token keyword">any</span>><span class="token punctuation">,</span> targetKey<span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">,</span> descriptor<span class="token punctuation">:</span> TypedPropertyDescriptor<Function> | <span class="token keyword">number</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">any</span><span class="token punctuation">;</span></code></pre>
<!-- Parameters -->
<!-- Description -->
### Description
`ExpressApplication` is an alias type to the [Express.Application](http://expressjs.com/fr/4x/api.html#app) interface. It use the util `registerFactory()` and let you to inject [Express.Application](http://expressjs.com/fr/4x/api.html#app) created by [ServerLoader](docs/server-loader/lifecycle-hooks.md).
```typescript
import {ExpressApplication, Service, Inject} from "@tsed/common";
@Service()
export default class OtherService {
constructor(@ExpressApplication expressApplication: Express.Application) {}
}
```
> Note: TypeScript transform and store `ExpressApplication` as `Function` type in the metadata. So to inject a factory, you must use the `@Inject(type)` decorator.
<!-- Members -->
|
lwallent/ts-express-decorators
|
docs/api/common/mvc/expressapplication.md
|
Markdown
|
mit
| 2,371
|
using System.Collections.Concurrent;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence.Dtos;
namespace Umbraco.Core.Persistence.Mappers
{
/// <summary>
/// Represents a <see cref="Content"/> to DTO mapper used to translate the properties of the public api
/// implementation to that of the database's DTO as sql: [tableName].[columnName].
/// </summary>
[MapperFor(typeof(Content))]
[MapperFor(typeof(IContent))]
public sealed class ContentMapper : BaseMapper
{
private static readonly ConcurrentDictionary<string, DtoMapModel> PropertyInfoCacheInstance = new ConcurrentDictionary<string, DtoMapModel>();
internal override ConcurrentDictionary<string, DtoMapModel> PropertyInfoCache => PropertyInfoCacheInstance;
protected override void BuildMap()
{
if (PropertyInfoCache.IsEmpty == false) return;
CacheMap<Content, NodeDto>(src => src.Id, dto => dto.NodeId);
CacheMap<Content, NodeDto>(src => src.Key, dto => dto.UniqueId);
CacheMap<Content, ContentVersionDto>(src => src.VersionId, dto => dto.Id);
CacheMap<Content, ContentVersionDto>(src => src.Name, dto => dto.Text);
CacheMap<Content, NodeDto>(src => src.ParentId, dto => dto.ParentId);
CacheMap<Content, NodeDto>(src => src.Level, dto => dto.Level);
CacheMap<Content, NodeDto>(src => src.Path, dto => dto.Path);
CacheMap<Content, NodeDto>(src => src.SortOrder, dto => dto.SortOrder);
CacheMap<Content, NodeDto>(src => src.Trashed, dto => dto.Trashed);
CacheMap<Content, NodeDto>(src => src.CreateDate, dto => dto.CreateDate);
CacheMap<Content, NodeDto>(src => src.CreatorId, dto => dto.UserId);
CacheMap<Content, ContentDto>(src => src.ContentTypeId, dto => dto.ContentTypeId);
CacheMap<Content, ContentVersionDto>(src => src.UpdateDate, dto => dto.VersionDate);
CacheMap<Content, DocumentDto>(src => src.Published, dto => dto.Published);
//CacheMap<Content, DocumentDto>(src => src.Name, dto => dto.Alias);
//CacheMap<Content, DocumentDto>(src => src, dto => dto.Newest);
//CacheMap<Content, DocumentDto>(src => src.Template, dto => dto.TemplateId);
}
}
}
|
lars-erik/Umbraco-CMS
|
src/Umbraco.Core/Persistence/Mappers/ContentMapper.cs
|
C#
|
mit
| 2,325
|
#include <iostream>
#include <vector>
using namespace std;
using ll = long long;
// ----- MaxFlow -----
class MaxFlow
{
struct Edge
{
int to;
ll cap;
int rev;
};
constexpr static ll INFTY = 10000000000000010LL;
int N;
vector<vector<Edge>> G;
vector<bool> used;
public:
MaxFlow() {}
MaxFlow(int N) : N{N}
{
G.resize(N);
used.resize(N);
}
void add_edge(int from, int to, ll cap = 1LL)
{
G[from].push_back({to, cap, static_cast<int>(G[to].size())});
G[to].push_back({from, 0, static_cast<int>(G[from].size() - 1)});
}
ll max_flow(int s, int t)
{
ll flow = 0;
while (true)
{
fill(used.begin(), used.end(), false);
ll f = dfs(s, t, INFTY);
if (f == 0)
{
return flow;
}
flow += f;
}
}
private:
ll dfs(int v, int t, ll f)
{
if (v == t)
{
return f;
}
used[v] = true;
for (auto &e : G[v])
{
if (!used[e.to] && e.cap > 0)
{
ll d = dfs(e.to, t, min(f, e.cap));
if (d > 0)
{
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
};
|
kazunetakahashi/library
|
Flow/MaxFlow.cpp
|
C++
|
mit
| 1,184
|
<!--
* CoreUI - Open Source Bootstrap Admin Template
* @version v1.0.0-alpha.2
* @link http://coreui.io
* Copyright (c) 2016 creativeLabs Łukasz Holeczek
* @license MIT
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="CoreUI Bootstrap 4 Admin Template">
<meta name="author" content="Lukasz Holeczek">
<meta name="keyword" content="CoreUI Bootstrap 4 Admin Template">
<!-- <link rel="shortcut icon" href="assets/ico/favicon.png"> -->
<title>CoreUI Bootstrap 4 Admin Template</title>
<!-- Icons -->
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/simple-line-icons.css" rel="stylesheet">
<!-- Main styles for this application -->
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div class="container d-table">
<div class="d-100vh-va-middle">
<div class="row">
<div class="col-md-6 offset-md-3">
<div class="card mx-2">
<div class="card-block p-2">
<h1>Register</h1>
<p class="text-muted">Create your account</p>
<div class="input-group mb-1">
<span class="input-group-addon"><i class="icon-user"></i>
</span>
<input type="text" class="form-control" placeholder="Username">
</div>
<div class="input-group mb-1">
<span class="input-group-addon">@</span>
<input type="text" class="form-control" placeholder="Email">
</div>
<div class="input-group mb-1">
<span class="input-group-addon"><i class="icon-lock"></i>
</span>
<input type="password" class="form-control" placeholder="Password">
</div>
<div class="input-group mb-2">
<span class="input-group-addon"><i class="icon-lock"></i>
</span>
<input type="password" class="form-control" placeholder="Repeat password">
</div>
<button type="button" class="btn btn-block btn-success">Create Account</button>
</div>
<div class="card-footer p-2">
<div class="row">
<div class="col-xs-6">
<button class="btn btn-block btn-facebook" type="button">
<span>facebook</span>
</button>
</div>
<div class="col-xs-6">
<button class="btn btn-block btn-twitter" type="button">
<span>twitter</span>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Bootstrap and necessary plugins -->
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/tether/dist/js/tether.min.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
</body>
</html>
|
rubyframework/CoreUI-Free-Bootstrap-Admin-Template
|
Static_Full_Project_GULP/pages-register.html
|
HTML
|
mit
| 3,862
|
module Hyperpublic
class Categories< Base
extend Forwardable
def_delegators :client, :get, :post, :post_multi, :put, :delete
attr_reader :client
def initialize(client)
@client = client
end
def find(params={})
q = Addressable::URI.new
q.query_values = stringify(params)
perform_get("/categories#{("?" + q.query) unless q.query.empty?}")
end
end
end
|
hyperpublic/hyperpublic_ruby
|
lib/hyperpublic/categories.rb
|
Ruby
|
mit
| 408
|
export default _normalizeLink;
/**
This method normalizes a link to an "links object". If the passed link is
already an object it's returned without any modifications.
See http://jsonapi.org/format/#document-links for more information.
@method _normalizeLink
@private
@param {String} link
@return {Object|null}
@for DS
*/
function _normalizeLink(link) {
switch (typeof link) {
case 'object':
return link;
case 'string':
return { href: link };
}
return null;
}
|
hoka-plus/p-01-web
|
tmp/babel-output_path-Ihxrnc4F.tmp/modules/ember-data/-private/system/normalize-link.js
|
JavaScript
|
mit
| 504
|
/*=============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 11404.cc
# Description: UVa Online Judge - 11404
=============================================================================*/
#include <bits/stdc++.h>
#pragma GCC optimizer("Ofast")
#pragma GCC target("avx2")
using namespace std;
typedef pair<int, int> ii;
typedef pair<long long, long long> ll;
typedef pair<double, double> dd;
typedef tuple<int, int, int> iii;
typedef tuple<long long, long long, long long> lll;
typedef tuple<double, double, double> ddd;
typedef vector<string> vs;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef vector<long long> vl;
typedef vector<vector<long long>> vvl;
typedef vector<double> vd;
typedef vector<vector<double>> vvd;
typedef vector<ii> vii;
typedef vector<ll> vll;
typedef vector<dd> vdd;
// Debug Snippets
void __print(int x) { cerr << x; }
void __print(long x) { cerr << x; }
void __print(long long x) { cerr << x; }
void __print(unsigned x) { cerr << x; }
void __print(unsigned long x) { cerr << x; }
void __print(unsigned long long x) { cerr << x; }
void __print(float x) { cerr << x; }
void __print(double x) { cerr << x; }
void __print(long double x) { cerr << x; }
void __print(char x) { cerr << '\'' << x << '\''; }
void __print(const char* x) { cerr << '\"' << x << '\"'; }
void __print(const string& x) { cerr << '\"' << x << '\"'; }
void __print(bool x) { cerr << (x ? "true" : "false"); }
template <typename T, typename V>
void __print(const pair<T, V>& x) {
cerr << '{';
__print(x.first);
cerr << ',';
__print(x.second);
cerr << '}';
}
template <typename T>
void __print(const T& x) {
int f = 0;
cerr << '{';
for (auto& i : x) cerr << (f++ ? "," : ""), __print(i);
cerr << "}";
}
void _print() { cerr << "]\n"; }
template <typename T, typename... V>
void _print(T t, V... v) {
__print(t);
if (sizeof...(v)) cerr << ", ";
_print(v...);
}
#define debug(x...) \
cerr << "[" << #x << "] = ["; \
_print(x)
template <class Ch, class Tr, class Container>
basic_ostream<Ch, Tr>& operator<<(basic_ostream<Ch, Tr>& os,
Container const& x) {
os << "{ ";
for (auto& y : x) os << y << " ";
return os << "}";
}
template <class X, class Y>
ostream& operator<<(ostream& os, pair<X, Y> const& p) {
return os << "[ " << p.first << ", " << p.second << "]";
}
// End Debug Snippets
vs split(string line) {
vs output;
istringstream iss(line);
string tmp;
while (iss >> tmp) {
output.push_back(tmp);
}
return output;
}
vs split(string line, regex re) {
vs output;
sregex_token_iterator it(line.begin(), line.end(), re, -1), it_end;
while (it != it_end) {
output.push_back(it->str());
it++;
}
return output;
}
const int INF_INT = 1e9 + 7;
const long long INF_LL = 1e18;
const int MAXN = 1005;
string S;
string dp[MAXN][MAXN];
bool done[MAXN][MAXN];
string f(int L, int R) {
if (L == R) {
done[L][R] = true;
return dp[L][R] = S[L];
} else if (L + 1 == R) {
done[L][R] = true;
if (S[L] == S[R])
dp[L][R] = S.substr(L, 2);
else
dp[L][R] = min(S[L], S[R]);
return dp[L][R];
}
if (done[L][R]) return dp[L][R];
if (S[L] == S[R]) {
return S[L] + f(L + 1, R - 1) + S[R];
} else {
string S1 = f(L + 1, R);
string S2 = f(L, R - 1);
if (S1.length() > S2.length() or
(S1.length() == S2.length() and S1 < S2)) {
dp[L][R] = S1;
} else {
dp[L][R] = S2;
}
}
done[L][R] = true;
return dp[L][R];
}
void solve() {
memset(done, 0, sizeof(done));
cout << f(0, S.length() - 1) << endl;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
while (cin >> S) solve();
return 0;
}
|
mjenrungrot/competitive_programming
|
UVa Online Judge/v114/11404.cc
|
C++
|
mit
| 4,008
|
<?php
namespace Dvsa\Mot\Frontend\SecurityCardModule\CardActivation\Service;
use Core\Routing\ProfileRoutes;
use Core\Service\MotFrontendAuthorisationServiceInterface;
use Core\Service\MotFrontendIdentityProvider;
use Core\Service\MotFrontendIdentityProviderInterface;
use Dvsa\Mot\Frontend\PersonModule\Security\PersonProfileGuardBuilder;
use Dvsa\Mot\Frontend\SecurityCardModule\GracePeriodAuthentication\Service\SecurityCardGracePeriodService;
use Dvsa\Mot\Frontend\SecurityCardModule\Security\SecurityCardGuard;
use DvsaCommon\Auth\MotAuthorisationServiceInterface;
use DvsaCommon\Factory\AutoWire\AutoWireableInterface;
use DvsaFeature\FeatureToggles;
use Zend\View\Helper\Url;
class RegisterCardViewStrategy implements AutoWireableInterface
{
/** @var FeatureToggles */
private $featureToggles;
/** @var RegisterCardHardStopCondition */
private $hardStopCondition;
/** @var MotFrontendAuthorisationServiceInterface $authorisationService */
private $authorisationService;
/** @var MotFrontendIdentityProvider $identityProvider */
private $identityProvider;
/** @var SecurityCardGuard $securityCardGuard */
private $securityCardGuard;
/** @var SecurityCardGracePeriodService $securityCardGracePeriodService */
private $securityCardGracePeriodService;
/** @var PersonProfileGuardBuilder $personProfileGuardBuilder */
private $personProfileGuardBuilder;
/** @var Url $url */
private $url;
/**
* RegisterCardViewStrategy constructor.
*
* @param FeatureToggles $featureToggles
* @param RegisterCardHardStopCondition $hardStopCondition
* @param MotAuthorisationServiceInterface $authorisationService
* @param MotFrontendIdentityProviderInterface $identityProvider
* @param SecurityCardGuard $securityCardGuard
* @param SecurityCardGracePeriodService $securityCardGracePeriodService
* @param PersonProfileGuardBuilder $personProfileGuardBuilder
* @param Url $url
*/
public function __construct(
FeatureToggles $featureToggles,
RegisterCardHardStopCondition $hardStopCondition,
MotAuthorisationServiceInterface $authorisationService,
MotFrontendIdentityProviderInterface $identityProvider,
SecurityCardGuard $securityCardGuard,
SecurityCardGracePeriodService $securityCardGracePeriodService,
PersonProfileGuardBuilder $personProfileGuardBuilder,
Url $url
) {
$this->featureToggles = $featureToggles;
$this->hardStopCondition = $hardStopCondition;
$this->authorisationService = $authorisationService;
$this->identityProvider = $identityProvider;
$this->securityCardGuard = $securityCardGuard;
$this->securityCardGracePeriodService = $securityCardGracePeriodService;
$this->personProfileGuardBuilder = $personProfileGuardBuilder;
$this->url = $url;
}
/**
* If user cannot activate a card, it will not put them
* On to the activate a card journey.
*
* @return bool
*/
public function canActivateACard()
{
$identity = $this->identityProvider->getIdentity();
$hasActiveCard = $this->securityCardGuard->hasActiveTwoFaCard($identity);
$hasCardOrdered = $this->securityCardGuard->hasOutstandingCardOrdersAndNoActiveCard($identity);
$twoFactorEligibleUser = $this->securityCardGuard->is2faEligibleUserWhichCanActivateACard($identity);
return $twoFactorEligibleUser && (!$hasActiveCard || $hasCardOrdered);
}
public function pageSubTitle()
{
if ($this->hardStopCondition->isTrue()) {
return '';
} else {
return 'Your profile';
}
}
public function breadcrumbs()
{
$breadcrumbs = [];
if (!$this->hardStopCondition->isTrue()) {
$breadcrumbs[] = ['Your profile' => ProfileRoutes::of($this->url)->yourProfile()];
}
$breadcrumbs[] = ['Activate your security card' => ''];
return $breadcrumbs;
}
public function skipCtaTemplate()
{
if ($this->hardStopCondition->isTrue()) {
return '2fa/register-card/skip-cta/goToSignIn';
} else {
return '2fa/register-card/skip-cta/goToProfile';
}
}
/**
* @return bool
*/
public function isHardBlockedAfterExpiredGracePeriod()
{
return $this->securityCardGracePeriodService->isHardBlockedAfterExpiredGracePeriod($this->identityProvider->getIdentity()->getUsername());
}
}
|
dvsa/mot
|
mot-web-frontend/module/SecurityCardModule/src/CardActivation/Service/RegisterCardViewStrategy.php
|
PHP
|
mit
| 4,668
|
<!-- HTML header for doxygen 1.8.8-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- For Mobile Devices -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<title>Traffic Assignment frameworK (TAsK): LazyShortestPath Class Reference</title>
<!--<link href="tabs.css" rel="stylesheet" type="text/css"/>-->
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="customdoxygen.css" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="doxy-boot.js"></script>
</head>
<body>
<nav class="navbar navbar-default" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand">Traffic Assignment frameworK (TAsK) </a>
</div>
</div>
</nav>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div class="content" id="content">
<div class="container">
<div class="row">
<div class="col-sm-12 panel panel-default" style="padding-bottom: 15px;">
<div style="margin-bottom: 15px;">
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<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><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</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="inherits.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)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pri-methods">Private Member Functions</a> |
<a href="#pri-attribs">Private Attributes</a> |
<a href="classLazyShortestPath-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">LazyShortestPath Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>Lazy shortest path for single-objective shortest path algorithms.
<a href="classLazyShortestPath.html#details">More...</a></p>
<p><code>#include <<a class="el" href="LazyShortestPath_8h_source.html">LazyShortestPath.h</a>></code></p>
<div class="dynheader">
Inheritance diagram for LazyShortestPath:</div>
<div class="dyncontent">
<div class="center"><img src="classLazyShortestPath__inherit__graph.png" border="0" usemap="#LazyShortestPath_inherit__map" alt="Inheritance graph"/></div>
<map name="LazyShortestPath_inherit__map" id="LazyShortestPath_inherit__map">
<area shape="rect" id="node2" href="classShortestPath.html" title="This is an abstract class that defines the interface for single-objective shortest-path algorithms..." alt="" coords="16,5,145,171"/>
</map>
</div>
<div class="dynheader">
Collaboration diagram for LazyShortestPath:</div>
<div class="dyncontent">
<div class="center"><img src="classLazyShortestPath__coll__graph.png" border="0" usemap="#LazyShortestPath_coll__map" alt="Collaboration graph"/></div>
<map name="LazyShortestPath_coll__map" id="LazyShortestPath_coll__map">
<area shape="rect" id="node2" href="classShortestPath.html" title="This is an abstract class that defines the interface for single-objective shortest-path algorithms..." alt="" coords="16,5,145,171"/>
</map>
</div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:a9bc494cba0b00024d81a365ec65ad4ae"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a9bc494cba0b00024d81a365ec65ad4ae"></a>
 </td><td class="memItemRight" valign="bottom"><b>LazyShortestPath</b> (<a class="el" href="classShortestPath.html">ShortestPath</a> *shPath)</td></tr>
<tr class="separator:a9bc494cba0b00024d81a365ec65ad4ae"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:acfcb62e2ead17a9c85b2afdaf5296b44"><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="classLazyShortestPath.html#acfcb62e2ead17a9c85b2afdaf5296b44">calculate</a> (int originIndex)</td></tr>
<tr class="separator:acfcb62e2ead17a9c85b2afdaf5296b44"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a981ff8ac5be3c1cb6b78cd7358fc4cb6"><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="classLazyShortestPath.html#a981ff8ac5be3c1cb6b78cd7358fc4cb6">calculate</a> (int originIndex, int destIndex, int odPairIndex)</td></tr>
<tr class="separator:a981ff8ac5be3c1cb6b78cd7358fc4cb6"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aaf84a8b62bc8f7510f3f96b8440e2e07"><td class="memItemLeft" align="right" valign="top">virtual FPType </td><td class="memItemRight" valign="bottom"><a class="el" href="classLazyShortestPath.html#aaf84a8b62bc8f7510f3f96b8440e2e07">getCost</a> (int destIndex) const </td></tr>
<tr class="separator:aaf84a8b62bc8f7510f3f96b8440e2e07"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a8b2d3072e78ff0b4369ed1abd1bb6ff6"><td class="memItemLeft" align="right" valign="top">virtual <a class="el" href="classStarLink.html">StarLink</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="classLazyShortestPath.html#a8b2d3072e78ff0b4369ed1abd1bb6ff6">getInComeLink</a> (int destIndex) const </td></tr>
<tr class="separator:a8b2d3072e78ff0b4369ed1abd1bb6ff6"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_methods_classShortestPath"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_classShortestPath')"><img src="closed.png" alt="-"/> Public Member Functions inherited from <a class="el" href="classShortestPath.html">ShortestPath</a></td></tr>
<tr class="memitem:a82a236c1957abb308d16f546b69a9813 inherit pub_methods_classShortestPath"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="classShortestPath.html#a82a236c1957abb308d16f546b69a9813">printPath</a> (int destIndex) const </td></tr>
<tr class="separator:a82a236c1957abb308d16f546b69a9813 inherit pub_methods_classShortestPath"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pri-methods"></a>
Private Member Functions</h2></td></tr>
<tr class="memitem:ac66f5fe93ae48f41227202665f458b51"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="classLazyShortestPath.html#ac66f5fe93ae48f41227202665f458b51">updatePathCost</a> (int destIndex)</td></tr>
<tr class="separator:ac66f5fe93ae48f41227202665f458b51"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pri-attribs"></a>
Private Attributes</h2></td></tr>
<tr class="memitem:a8b82691b758f4bd37f0ed945bb7fb50b"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a8b82691b758f4bd37f0ed945bb7fb50b"></a>
<a class="el" href="classShortestPath.html">ShortestPath</a> * </td><td class="memItemRight" valign="bottom"><b>shPath_</b></td></tr>
<tr class="separator:a8b82691b758f4bd37f0ed945bb7fb50b"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a75692c8ecc28acbd7e6d35db08612bd7"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a75692c8ecc28acbd7e6d35db08612bd7"></a>
int </td><td class="memItemRight" valign="bottom"><b>prevOriginIndex_</b></td></tr>
<tr class="separator:a75692c8ecc28acbd7e6d35db08612bd7"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2190d5f22fd465c8e33166433e6e7d5f"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a2190d5f22fd465c8e33166433e6e7d5f"></a>
bool </td><td class="memItemRight" valign="bottom"><b>originChanged_</b></td></tr>
<tr class="separator:a2190d5f22fd465c8e33166433e6e7d5f"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a323d59b901d48c83f7c65a9020e04474"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a323d59b901d48c83f7c65a9020e04474"></a>
FPType </td><td class="memItemRight" valign="bottom"><b>newPathCost_</b></td></tr>
<tr class="separator:a323d59b901d48c83f7c65a9020e04474"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>Lazy shortest path for single-objective shortest path algorithms. </p>
<p>For details, see <a class="el" href="citelist.html#CITEREF_Chen1998">[3]</a>. </p>
</div><h2 class="groupheader">Member Function Documentation</h2>
<a class="anchor" id="acfcb62e2ead17a9c85b2afdaf5296b44"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">void LazyShortestPath::calculate </td>
<td>(</td>
<td class="paramtype">int </td>
<td class="paramname"><em>originIndex</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Calculates shortest path from origin <b>originIndex</b> to all other nodes that are reachable from this origin. </p>
<p>Implements <a class="el" href="classShortestPath.html#a7ce734ae74cffe4e71b60f9a1db00071">ShortestPath</a>.</p>
</div>
</div>
<a class="anchor" id="a981ff8ac5be3c1cb6b78cd7358fc4cb6"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">void LazyShortestPath::calculate </td>
<td>(</td>
<td class="paramtype">int </td>
<td class="paramname"><em>originIndex</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">int </td>
<td class="paramname"><em>destIndex</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">int </td>
<td class="paramname"><em>odPairIndex</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Calculates shortest path from origin <b>originIndex</b> to destination <b>destIndex</b>. If it is not over-ridden by children classes usual shortest path from a given origin to all other nodes is called. </p>
<p>Reimplemented from <a class="el" href="classShortestPath.html#a17000f3aff5ad292daa0d929298904a3">ShortestPath</a>.</p>
</div>
</div>
<a class="anchor" id="aaf84a8b62bc8f7510f3f96b8440e2e07"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">FPType LazyShortestPath::getCost </td>
<td>(</td>
<td class="paramtype">int </td>
<td class="paramname"><em>destIndex</em></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<dl class="section return"><dt>Returns</dt><dd>shortest path distance to node <b>destIndex</b> </dd></dl>
<p>Implements <a class="el" href="classShortestPath.html#a6e9b7fba57ea8d9497fbcf82c2500976">ShortestPath</a>.</p>
</div>
</div>
<a class="anchor" id="a8b2d3072e78ff0b4369ed1abd1bb6ff6"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="classStarLink.html">StarLink</a> * LazyShortestPath::getInComeLink </td>
<td>(</td>
<td class="paramtype">int </td>
<td class="paramname"><em>destIndex</em></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">virtual</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<dl class="section return"><dt>Returns</dt><dd>pointer to a link that belongs to the shortest path and points to node <b>destIndex</b>, return NULL if the origin is passed or if destIndex is not reachable from current origin. </dd></dl>
<p>Implements <a class="el" href="classShortestPath.html#a7c9f28d266abc5f16d4eb02623af3a92">ShortestPath</a>.</p>
</div>
</div>
<a class="anchor" id="ac66f5fe93ae48f41227202665f458b51"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">void LazyShortestPath::updatePathCost </td>
<td>(</td>
<td class="paramtype">int </td>
<td class="paramname"><em>destIndex</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">private</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Goes through the stored shortest path to the destination destIndex and updates shortest path distance that might have changed after flow shifts </p>
</div>
</div>
<hr/>The documentation for this class was generated from the following files:<ul>
<li><a class="el" href="LazyShortestPath_8h_source.html">LazyShortestPath.h</a></li>
<li>LazyShortestPath.cpp</li>
</ul>
</div><!-- contents -->
<!-- HTML footer for doxygen 1.8.8-->
<!-- start footer part -->
</div>
</div>
</div>
</div>
</div>
<hr class="footer"/><address class="footer"><small>
Generated on Tue Mar 10 2015 15:45:14 for Traffic Assignment frameworK (TAsK) by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html>
|
olga-perederieieva/TAsK
|
vendor/Docs/classLazyShortestPath.html
|
HTML
|
mit
| 17,516
|
<p>
player-profile works!
</p>
<div *ngIf="player">
<h2>{{ player.nickname }} profile</h2>
<div>
<div><label>id:</label>{{ player.id}}</div>
<div><label>Games:</label>{{ player.gamesPlayed }}</div>
<div><label>Kills:</label> {{ player.kills }}</div>
<div><label>Deaths:</label> {{ player.deaths }}</div>
<div><label>Wins:</label> {{ player.wins }}</div>
<div>Description: {{ player.description }}</div>
</div>
</div>
|
togus/uhc
|
src/app/player-profile/player-profile.component.html
|
HTML
|
mit
| 446
|
<?php
namespace TwbBundleTest\View\Helper;
class TwbBundleDropDownTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \TwbBundle\View\Helper\TwbBundleDropDown
*/
protected $dropDownHelper;
/**
* @see \PHPUnit_Framework_TestCase::setUp()
*/
public function setUp()
{
$oViewHelperPluginManager = \TwbBundleTest\Bootstrap::getServiceManager()->get('ViewHelperManager');
$oRenderer = new \Zend\View\Renderer\PhpRenderer();
$this->dropDownHelper = $oViewHelperPluginManager->get('dropDown')->setView($oRenderer->setHelperPluginManager($oViewHelperPluginManager));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testRenderToggleWithWrongTypeAttributes()
{
$this->dropDownHelper->renderToggle(array('toggle_attributes' => 'wrong'));
}
public function testRenderToggleWithEmptyClassAttribute()
{
$this->assertEquals('<a class="sr-only dropdown-toggle" data-toggle="dropdown" role="button" href="#"> <b class="caret"></b></a>', $this->dropDownHelper->renderToggle(array('toggle_attributes' => array('class' => ''))));
}
public function testRenderToggleWithDefinedClassAttribute()
{
$this->assertEquals('<a class="test-toggle sr-only dropdown-toggle" data-toggle="dropdown" role="button" href="#"> <b class="caret"></b></a>', $this->dropDownHelper->renderToggle(array('toggle_attributes' => array('class' => 'test-toggle'))));
}
public function testRenderItemWithDefinedClassAttribute()
{
$oReflectionClass = new \ReflectionClass('\TwbBundle\View\Helper\TwbBundleDropDown');
$oReflectionMethod = $oReflectionClass->getMethod('renderItem');
$oReflectionMethod->setAccessible(true);
//Header
$this->assertEquals(
'<li class="test-item dropdown-header" role="presentation">test-label</li>', $oReflectionMethod->invoke($this->dropDownHelper, array(
'type' => \TwbBundle\View\Helper\TwbBundleDropDown::TYPE_ITEM_HEADER,
'label' => 'test-label',
'attributes' => array('class' => 'test-item')
))
);
//Divider
$this->assertEquals(
'<li class="test-item divider" role="presentation"></li>', $oReflectionMethod->invoke($this->dropDownHelper, array(
'type' => \TwbBundle\View\Helper\TwbBundleDropDown::TYPE_ITEM_DIVIDER,
'attributes' => array('class' => 'test-item')
))
);
}
}
|
neilime/zf2-twb-bundle
|
tests/TwbBundleTest/View/Helper/TwbBundleDropDownTest.php
|
PHP
|
mit
| 2,682
|
# -*- coding: utf-8 -*-
"""
Clement Michard (c) 2015
"""
import os
import sys
import nltk
from emotion import Emotion
from nltk.corpus import WordNetCorpusReader
import xml.etree.ElementTree as ET
class WNAffect:
"""WordNet-Affect ressource."""
def __init__(self, wordnet16_dir, wn_domains_dir):
"""Initializes the WordNet-Affect object."""
try:
cwd = os.getcwd()
nltk.data.path.append(cwd)
wn16_path = "{0}/dict".format(wordnet16_dir)
self.wn16 = WordNetCorpusReader(os.path.abspath("{0}/{1}".format(cwd, wn16_path)), nltk.data.find(wn16_path))
self.flat_pos = {'NN':'NN', 'NNS':'NN', 'JJ':'JJ', 'JJR':'JJ', 'JJS':'JJ', 'RB':'RB', 'RBR':'RB', 'RBS':'RB', 'VB':'VB', 'VBD':'VB', 'VGB':'VB', 'VBN':'VB', 'VBP':'VB', 'VBZ':'VB'}
self.wn_pos = {'NN':self.wn16.NOUN, 'JJ':self.wn16.ADJ, 'VB':self.wn16.VERB, 'RB':self.wn16.ADV}
self._load_emotions(wn_domains_dir)
self.synsets = self._load_synsets(wn_domains_dir)
except:
print "Please download the dependencies and re-run the script after installing them successfully. Exiting !"
exit()
def _load_synsets(self, wn_domains_dir):
"""Returns a dictionary POS tag -> synset offset -> emotion (str -> int -> str)."""
tree = ET.parse("{0}/wn-affect-1.1/a-synsets.xml".format(wn_domains_dir))
root = tree.getroot()
pos_map = { "noun": "NN", "adj": "JJ", "verb": "VB", "adv": "RB" }
synsets = {}
for pos in ["noun", "adj", "verb", "adv"]:
tag = pos_map[pos]
synsets[tag] = {}
for elem in root.findall(".//{0}-syn-list//{0}-syn".format(pos, pos)):
offset = int(elem.get("id")[2:])
if not offset: continue
if elem.get("categ"):
synsets[tag][offset] = Emotion.emotions[elem.get("categ")] if elem.get("categ") in Emotion.emotions else None
elif elem.get("noun-id"):
synsets[tag][offset] = synsets[pos_map["noun"]][int(elem.get("noun-id")[2:])]
return synsets
def _load_emotions(self, wn_domains_dir):
"""Loads the hierarchy of emotions from the WordNet-Affect xml."""
tree = ET.parse("{0}/wn-affect-1.1/a-hierarchy.xml".format(wn_domains_dir))
root = tree.getroot()
for elem in root.findall("categ"):
name = elem.get("name")
if name == "root":
Emotion.emotions["root"] = Emotion("root")
else:
Emotion.emotions[name] = Emotion(name, elem.get("isa"))
def get_emotion(self, word, pos):
"""Returns the emotion of the word.
word -- the word (str)
pos -- part-of-speech (str)
"""
if pos in self.flat_pos:
pos = self.flat_pos[pos]
synsets = self.wn16.synsets(word, self.wn_pos[pos])
if synsets:
offset = synsets[0].offset
if offset in self.synsets[pos]:
return self.synsets[pos][offset], offset
return None
def get_emotion_synset(self, offset):
"""Returns the emotion of the synset.
offset -- synset offset (int)
"""
for pos in self.flat_pos.values():
if offset in self.synsets[pos]:
return self.synsets[pos][offset]
return None
|
Arnukk/TDS
|
wnaffect.py
|
Python
|
mit
| 3,540
|
var Employee = require('../models/Employee');
var Owner = require('../models/User');
var baby = require('babyparse');
var _ = require('lodash');
var async = require('async');
var nodemailer = require('nodemailer');
var passport = require('passport');
var fs = require('fs');
var validator = require('validator');
var Logger = require('le_node');
var logger = new Logger({
token:'4ed0e98c-c21f-42f0-82ee-0031f09ca161'
});
/**
+ * GET /subdomain login
+ * Employees page.
+ */
exports.postSubdomain = function(req, res){
Owner.findOne({subdomainurl: req.body.subdomain}, function(err, domain) {
if (err) {
// Send logs to logentries
logger.log(4,"Find subDomain Error:" + domain);
console.log("ERROR find subDomain: " + domain);
res.redirect('/subdomain_login');
}
if(domain) {
// Send logs to logentries
logger.log(2,"Find subDomain Success:" + domain);
console.log("success: " + domain);
req.flash('success', { msg: 'Success! You are logged in.' });
res.redirect('/login_employee');
}
else {
res.render('subdomain_login', { msg: 'Cannot Find Your Company' });
}
});
};
/**
* GET /add_employees
* Employees page.
*/
exports.getEmployees = function(req, res){
Employee.find({_admin_id: req.user.id/*, name: "Jane Doe"*/}, function (err, employees) {
//console.log(employee);
// Send logs to logentries
logger.log(2,"Find Employee Success:" + employees);
res.render('add_employees',{title: 'Add Employees', employees: employees, layout: 'navigation_admin'});
});
};
/**
* POST /add_employees
* Add an employee using form.
*/
exports.addEmployee = function(req, res) {
var name = req.body.name;
var number = req.body.number;
var email = req.body.email;
var password = generateRandomString();
var company_id = req.user.id;
var subdomainurl = req.user.subdomainurl;
req.assert('email', 'Email is not valid').isEmail();
//req.assert('number', 'Phone number is invalid').isMobilePhone('en-US'); // not a good validator
Employee.create({
name: name,
phone_number: number,
email: email,
password: password,
subdomainurl: subdomainurl,
_admin_id: company_id
}, function (err, employee) {
if (err) {
// Send logs to logentries
logger.log(4,"Create employee failed: "+err);
console.log("ERROR creating employee: ");
console.log(err);
//TODO - display error message
res.redirect('add_employees');
//res.send("There was a problem adding the employee to the databaase");
} else {
// Send logs to logentries
logger.log(2,"Create employee Success: "+err);
//console.log('Creating new employee: ' + employee);
res.redirect('add_employees');
emailEmployee(employee, req.user, password);
}
});
};
exports.addEmployeesThroughCSV = function(req, res) {
var content = fs.readFileSync(req.file.path, { encoding: 'binary' });
var parsed = baby.parse(content);
var rows = parsed.data;
var admin_id = req.user.id;
for(var i = 0; i < rows.length; i++){
var name = rows[i][0].trim();
var phone = rows[i][1].trim();
var email = rows[i][2].trim();
if (!validator.isEmail(email)) {
console.log("Employee #" + i + " " + name + " does not have a valid email: " + email + ".")
} else {
(function(password) { //anonymous function to enforce password is not outside closure
Employee.create({
name: name,
phone_number: phone,
email: email,
password: password,
_admin_id: admin_id
}, function (err, employee) {
if (err) {
console.log("ERROR creating employee");
console.log(err);
//res.send("There was a problem adding the employee to the database");
} else {
//emailEmployee(employee, req.user, password);
}
}
);
})(generateRandomString());
}
}
res.redirect('/add_employees');
};
exports.selectEmployee = function(req, res) {
Employee.findById(req.id, function(err, employee) {
if (err) {
console.log("ERROR selecting employee: " + employee);
//res.send("There was an error selecting the employee");
} else {
res.render('editEmployee', {title: "Employee: " + employee.name, employee: employee});
}
})
};
exports.editEmployee = function(req, res) {
var name = req.body.name;
var phone = req.body.phone;
var email = req.body.email;
Employee.findById(req.id, function(err, employee) {
if (err) {
console.log("ERROR selecting employee: " + employee);
//res.send("There was an error selecting the employee");
} else {
employee.update({
name: name,
phone_number: phone,
email: email
}, function(err, employee) {
if (err) {
console.log("ERROR updating employee: " + employee);
//res.send("There was an error updating the employee");
} else {
res.redirect("/add_employees");
}
})
}
})
};
exports.emailEmployee = function(req, res) {
var options = {
service: 'gmail',
auth: {
user: 'donotreply.receptional@gmail.com',
pass: 'nightowls1'
}
};
var emailtext = req.body.message;
var transporter = nodemailer.createTransport(options);
// Setup email data
var mailOptions = {
from: req.user.email,
to: req.body.to,
subject: "Receptional",
text: emailtext,
html: emailtext
};
// Send email
transporter.sendMail(mailOptions, function(error, info) {
if(error) {
console.log("Fail sending" + error);
}
else {
console.log('Message sent: ' + info);
console.log(emailtext);
}
});
res.redirect("/add_employees");
};
exports.removeEmployee = function(req, res) {
Employee.findById(req.params.id, function(err, employee) {
if (err) {
console.log("ERROR selecting employee: " + employee);
//res.send("There was an error selecting the employee");
} else {
employee.remove(function (err, employee) {
if (err) {
console.log("ERROR removing employee: " + employee);
//res.send("There was an error removing the employee");
} else {
console.log("Successfully removed " + employee.name);
res.redirect("/add_employees");
}
})
}
})
};
/**
* GET /login
* Login page.
*/
exports.getEmployeeLogin = function(req, res) {
if (req.user) {
return res.redirect('/');
}
var domain = req.headers.host,
subDomain = domain.split('.');
if(subDomain.length > 1) {
subDomain = subDomain[0].split("-").join(" ");
}
res.render('login_employee', {
subdomain: subDomain
});
};
/**
* POST /login
* Sign in using email and password.
*/
exports.postEmployeeLogin = function(req, res, next) {
req.assert('email', 'Email is not valid').isEmail();
req.assert('password', 'Password cannot be blank').notEmpty();
var errors = req.validationErrors();
if (errors) {
console.log(errors);
req.flash('errors', errors);
logger.log(4,"User login Failed:" + errors);
return res.redirect('/login_employee');
}
passport.authenticate('employee', function(err, employee, info) {
console.log(info);
if (err) {
logger.log(4,"User login Failed:" + err);
return next(err);
}
if (!employee) {
console.log(err);
req.flash('errors', { msg: info.message });
logger.log(4,"User login Failed:" + err);
return res.redirect('/login_employee');
}
req.logIn(employee, function(err) {
if (err) {
return next(err);
logger.log(4,"User login Failed:" + err);
}
employee.lastLoginDate = Date.now();
employee.save();
logger.log(2,"User login Success:");
req.flash('success', { msg: 'Success! You are logged in.' });
//res.redirect(req.session.returnTo || '/dashboard_admin');
res.redirect('/dashboard_employee');
});
})(req, res, next);
};
function generateRandomString() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 8; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function emailEmployee(employee, admin, password) {
// Create SMTP transporter object
var options = {
service: 'gmail',
auth: {
user: 'donotreply.receptional@gmail.com',
pass: 'nightowls1'
}
};
var companyname = admin.companyname;
var subdomainurl = admin.subdomainurl;
var emailtext = "Hello " + employee.name + "! Welcome to receptional. You have been added to the company: " + companyname + ". You can access your company receptional website at: " + subdomainurl + ".receptional.xyz. You're password is " + password + ".";
var transporter = nodemailer.createTransport(options);
// Setup email data
var mailOptions = {
from: '"Receptional.xyz" <donotreply.receptional@gmail.com>',
to: employee.email,
subject: "Welcome to Receptional",
text: emailtext,
html: emailtext
};
// Send email
transporter.sendMail(mailOptions, function(error, info) {
if(error) {
console.log(error);
}
else {
console.log('Message sent: ' + info.response);
console.log(emailtext);
}
});
}
/**
* POST /account/password
* Update current password.
*/
exports.postUpdatePassword = function(req, res, next) {
// req.assert('password', 'Password must be at least 4 characters long').len(4);
// req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password);
// console.log("get in update password ");
// var errors = req.validationErrors();
// if (errors) {
// console.log("update password failed: " + errors);
// req.flash('errors', errors);
// return res.redirect('/settings');
// }
Employee.findById(req.user.id, function(err, user) {
if (err) {
console.log(" failed: " + err);
return next(err);
}
user.password = req.body.password;
user.save(function(err) {
if (err) {
console.log(" failed: " + err);
return next(err);
}
console.log("success ");
req.flash('success', { msg: 'Password has been changed.' });
res.redirect('/settings');
});
});
};
/**
* POST /account/profile
* Update profile information.
*/
exports.postUpdateProfile = function(req, res, next) {
console.log("update profile");
Employee.findById(req.user.id, function(err, user) {
console.log(req.user.id);
if (err) {
// Send logs to logentries
console.log("Edit profile failed: " + err);
return next(err);
}
user.email = req.body.email || '';
user.name = req.body.name || '';
user.phone_number = req.body.phone || '';
user.picture = req.body.photo || '';
user.save(function(err) {
if (err) {
// Send logs to logentries
console.log("Edit profile failed: " + err);
return next(err);
}
// Send logs to logentries
console.log("Edit profile Success");
req.flash('success', { msg: 'Profile information updated.' });
res.redirect('/settings');
});
});
};
|
denniskkim/jackson5
|
controllers/employee.js
|
JavaScript
|
mit
| 12,598
|
05. Conditional Statements
if-else constructs, switch-case
|
StoikoNeykov/Telerik
|
CSharp1/ConditionalStatements/README.md
|
Markdown
|
mit
| 59
|
---
title: Authentication
pageTitle: "Authentication with GraphQL, VueJS & Apollo Tutorial"
description: "Learn best practices to implement authentication with GraphQL & Apollo Client to provide an email-and-password-based login in a VueJS app with Graphcool."
question: Where do you handle routing to a different component after a successful mutation?
answers: ["Within the update callback", "Within the mutation's .then block", "Within the mutation's .catch block", "Within a routing callback"]
correctAnswer: 1
---
In this section, you'll learn how you can implement authentication functionality with Apollo and Graphcool to provide a login to the user.
### Prepare the VueJS components
As in the sections before, you'll set the stage for the login functionality by preparing the VueJS components that are needed for this feature. You'll start by implementing the `AppLogin` component.
<Instruction>
Create a new file in `src/components` and call it `AppLogin.vue`. Then paste the following code inside of it:
```js(path=".../hackernews-vue-apollo/src/components/AppLogin.vue")
<template>
<div>
<h4 class='mv3'>{{login ? 'Login' : 'Sign Up'}}</h4>
<div class='flex flex-column'>
<input
v-show="!login"
v-model="name"
type="text"
placeholder="Your name">
<input
v-model="email"
type="text"
placeholder="Your email address">
<input
v-model="password"
type="password"
placeholder="Password">
</div>
<div class='flex mt3'>
<button
type="button"
class='pointer mr2 button'
@click="confirm()">
{{login ? 'login' : 'create account'}}
</button>
<button
type="button"
class='pointer button'
@click="login = !login">
{{login ? 'need to create an account?' : 'already have an account?'}}
</button>
</div>
</div>
</template>
<script>
import { GC_USER_ID, GC_AUTH_TOKEN } from '../constants/settings'
export default {
name: 'AppLogin',
data () {
return {
email: '',
login: true,
name: '',
password: ''
}
},
methods: {
confirm () {
// ... you'll implement this in a bit
},
saveUserData (id, token) {
localStorage.setItem(GC_USER_ID, id)
localStorage.setItem(GC_AUTH_TOKEN, token)
this.$root.$data.userId = localStorage.getItem(GC_USER_ID)
}
}
}
</script>
```
</Instruction>
Let's quickly gain an understanding of the structure of this new component which can have two major states.
One state is for users that already have an account and only need to login. In this state, the component will only render two `input` fields for the user to provide their `email` and `password`. Notice that `login` will be `true` in this case.
The second state is for users that haven't created an account yet, and thus still need to sign up. Here, you also render a third `input` field where users can provide their `name`. In this case, `login` will be `false`.
The method `confirm` will be used to implement the mutations that we need to send for the login functionality.
Next you also need to provide the `src/constants/settings.js` file that we use to define keys for the credentials that we're storing in the browser's `localStorage`.
<Instruction>
In `src/constants`, create a new file called `settings.js` and add the following two definitions:
```js(path=".../hackernews-vue-apollo/src/constants/settings.js")
export const GC_USER_ID = 'graphcool-user-id'
export const GC_AUTH_TOKEN = 'graphcool-auth-token'
```
</Instruction>
With that component in place, you can go ahead and add a new route to your `src/router/index.js` file.
<Instruction>
Open `src/router/index.js` and update the `routes` array to include the new route:
```js{10-13}(path=".../hackernews-vue-apollo/src/router/index.js")
routes: [
{
path: '/',
component: LinkList
},
{
path: '/create',
component: CreateLink
},
{
path: '/login',
component: AppLogin
}
],
```
</Instruction>
<Instruction>
Also import the `AppLogin` component near top of the same file:
```js(path=".../hackernews-vue-apollo/src/router/index.js")
import AppLogin from '../components/AppLogin'
```
</Instruction>
Finally, go ahead and add the `AppLink` to the `AppHeader` component that allows users to navigate to the `Login` page.
<Instruction>
Open `src/components/AppHeader.vue` and update the file to look like the following:
```js(path=".../hackernews-vue-apollo/src/components/AppHeader.vue")
<template>
<div class="flex pa1 justify-between nowrap orange">
<div class="flex flex-fixed black">
<div class="fw7 mr1">Hacker News</div>
<router-link to="/" class="ml1 no-underline black">new</router-link>
<div class="flex" v-if="userId">
<div class="ml1">|</div>
<router-link to="/create" class="ml1 no-underline black">submit</router-link>
</div>
</div>
<div class="flex flex-fixed">
<div v-if="userId" class="ml1 pointer black" @click="logout()">logout</div>
<router-link v-else to="/login" class="ml1 no-underline black">login</router-link>
</div>
</div>
</template>
<script>
import { GC_USER_ID, GC_AUTH_TOKEN } from '../constants/settings'
export default {
name: 'AppHeader',
computed: {
userId () {
return this.$root.$data.userId
}
},
methods: {
logout () {
localStorage.removeItem(GC_USER_ID)
localStorage.removeItem(GC_AUTH_TOKEN)
this.$root.$data.userId = localStorage.getItem(GC_USER_ID)
}
}
}
</script>
```
</Instruction>
You first retrieve the `userId` from `this.$root.$data`. If the `userId` is not available, the _submit_-button won't be rendered anymore. That way you make sure only authenticated users can create new links.
You're also adding a second button on the right side of the `AppHeader` that users can use to login and logout.
Here is what the `AppLogin` and `AppHeader` components now look like:

Before you can implement the authentication functionality in `src/components/AppLogin.vue`, you need to prepare the Graphcool project and enable authentication on the server-side.
### Enabling Email-and-Password Authentication & Updating the Schema
<Instruction>
In the directory where `project.graphcool` is located, type the following into the terminal:
```bash
graphcool console
```
</Instruction>
This will open up the Graphcool Console - the web UI that allows you to configure your Graphcool project.
<Instruction>
Select the _Integrations_-tab on the left side-menu and then click on the _Email-Password-Auth_-integration.
</Instruction>

This will open the popup that allows you to enable Graphcool's email-based authentication mechanism.
<Instruction>
In the popup, simply click _Enable_.
</Instruction>

Having the `Email-and-Password` auth provider enabled adds two new mutations to the project's API:
```graphql(nocopy)
# 1. Create new user
createUser(authProvider: { email: { email, password } }): User
# 2. Login existing user
signinUser(email: { email, password }): SignInUserPayload
# SignInUserPayload bundles information about the `user` and `token`
type SignInUserPayload {
user: User
token: String
}
```
Next, you have to make sure that the changes introduced by the authentication provider are reflected in your local project file. You can use the `graphcool pull` command to update your local schema file with changes that happened remotely.
<Instruction>
Open a terminal window and navigate to the directory where `project.graphcool` is located. Then run the following command:
```bash
graphcool pull
```
</Instruction>
> Note: Before the remote schema gets fetched, you will be asked to confirm that you want to override the current project file. You can confirm by typing `y`.
This will bump the schema `version` to `2` and update the `User` type to now also include the `email` and `password` fields:
```{3,5}graphql(nocopy)
type User @model {
createdAt: DateTime!
email: String @isUnique
id: ID! @isUnique
password: String
updatedAt: DateTime!
}
```
Next you need to make one more modification to the schema. Generally, when updating the schema of a Graphcool project, you've got two ways of doing so:
1. Use the web-based [Graphcool Console](https://console.graph.cool) and change the schema directly
2. Use the Graphcool project file and the CLI to update the schema from your local machine
<Instruction>
Open your project file `project.graphcool` and update the `User` and `Link` types as follows:
```graphql{7,15,17}
type Link @model {
createdAt: DateTime!
description: String!
id: ID! @isUnique
updatedAt: DateTime!
url: String!
postedBy: User @relation(name: "UsersLinks")
}
type User @model {
createdAt: DateTime!
id: ID! @isUnique
email: String @isUnique
updatedAt: DateTime!
name: String!
password: String
links: [Link!]! @relation(name: "UsersLinks")
}
```
</Instruction>
You added two things to the schema:
- A new field on the `User` type to store the `name` of the user.
- A new relation between the `User` and the `Link` type that represents a one-to-many relationship and expresses that one `User` can be associated with multiple links. The relation manifests itself in the two fields `postedBy` and `links`.
<Instruction>
Save the file and execute the following command in the Terminal:
```bash
graphcool push
```
</Instruction>
Here is the Terminal output after you issue the command:
```sh(nocopy)
$ graphcool push
✔ Your schema was successfully updated. Here are the changes:
| (*) The type `User` is updated.
├── (+) A new field with the name `name` and type `String!` is created.
|
| (+) The relation `UsersLinks` is created. It connects the type `Link` with the type `User`.
Your project file project.graphcool was updated. Reload it in your editor if needed.
```
> **Note**: You can also use the `graphcool status` command after having made changes to the schema to preview the potential changes that would be performed with `graphcool push`.
Perfect, you're all set now to actually implement the authentication functionality inside your app.
### Implementing the Login Mutations
`createUser` and `signinUser` are two regular GraphQL mutations that you can use in the same way as you did with the `createLink` mutation from before.
<Instruction>
Open `src/constants/graphql.js` and add the following two definitions to the file:
```js(path=".../hackernews-vue-apollo/src/constants/graphql.js")
export const CREATE_USER_MUTATION = gql`
mutation CreateUserMutation($name: String!, $email: String!, $password: String!) {
createUser(
name: $name,
authProvider: {
email: {
email: $email,
password: $password
}
}
) {
id
}
signinUser(email: {
email: $email,
password: $password
}) {
token
user {
id
}
}
}
`
export const SIGNIN_USER_MUTATION = gql`
mutation SigninUserMutation($email: String!, $password: String!) {
signinUser(email: {
email: $email,
password: $password
}) {
token
user {
id
}
}
}
`
```
</Instruction>
Now, let's gain a better understanding what's going on in the two mutations that you just added to the `src/constants/graphql.js` file.
The `SIGNIN_USER_MUTATION` looks very similar to the mutations we saw before. It simply takes the `email` and `password` as arguments and returns info about the `user` as well as a `token` that you can attach to subsequent requests to authenticate the user. You'll learn in a bit how to do so.
The `CREATE_USER_MUTATION` however is a bit different! Here, we actually define _two_ mutations at once! When you're doing that, the execution order is always _from top to bottom_. So, in your case the `createUser` mutation will be executed _before_ the `signinUser` mutation. Bundling two mutations like this allows you to sign up and login in a single request!
All right, all that's left to do is to call the two mutations inside the `AppLogin` component!
<Instruction>
Open `src/components/AppLogin.vue` and implement `confirm` as follows:
```js(path=".../hackernews-vue-apollo/src/components/AppLogin.vue")
confirm () {
const { name, email, password } = this.$data
if (this.login) {
this.$apollo.mutate({
mutation: SIGNIN_USER_MUTATION,
variables: {
email,
password
}
}).then((result) => {
const id = result.data.signinUser.user.id
const token = result.data.signinUser.token
this.saveUserData(id, token)
}).catch((error) => {
alert(error)
})
} else {
this.$apollo.mutate({
mutation: CREATE_USER_MUTATION,
variables: {
name,
email,
password
}
}).then((result) => {
const id = result.data.signinUser.user.id
const token = result.data.signinUser.token
this.saveUserData(id, token)
}).catch((error) => {
alert(error)
})
}
this.$router.push({path: '/'})
}
```
</Instruction>
The code is pretty straightforward. If the user wants to only login, you're calling the `signinUserMutation` and pass the provided `email` and `password` as arguments. Otherwise you're using the `createUserMutation` where you also pass the user's `name`. After the mutation is performed, you're storing the `id` and `token` in `localStorage` and navigating back to the root route.
<Instruction>
Also import the `CREATE_USER_MUTATION` and `SIGNIN_USER_MUTATION` constants near top of the `script` block:
```js(path=".../hackernews-vue-apollo/src/components/AppLogin.vue")
import { CREATE_USER_MUTATION, SIGNIN_USER_MUTATION } from '../constants/graphql'
```
</Instruction>
You now need to make a couple more changes to `src/main.js` to get things working.
<Instruction>
First, import `GC_USER_ID` near top of `src/main.js`:
```js(path=".../hackernews-vue-apollo/src/main.js")
import { GC_USER_ID } from './constants/settings'
```
</Instruction>
<Instruction>
Still in `src/main.js` make the following change to the bottom of the file:
```js{1-2,9-12}(path=".../hackernews-vue-apollo/src/main.js")
// 1
let userId = localStorage.getItem(GC_USER_ID)
/* eslint-disable no-new */
new Vue({
el: '#app',
provide: apolloProvider.provide(),
router,
// 2
data: {
userId
},
render: h => h(App)
})
```
</Instruction>
1. You get the current `GC_USER_ID` from `localStorage` if there is one
2. You set this `userId` on the `$root` `$data` object
You can now create an account by providing a `name`, `email` and `password`. Once you do so, the _submit_-button will be rendered again:

### Updating the `createLink`-mutation
Since you're now able to authenticate users and also added a new relation between the `Link` and `User` type, you can also make sure that every new link that gets created in the app can store information about the user that posted it. That's what the `postedBy` field on `Link` will be used for.
<Instruction>
Open `src/constants/graphql.js` and update the definition of `CREATE_LINK_MUTATION` as follows:
```js(path=".../hackernews-vue-apollo/src/constants/graphql.js")
export const CREATE_LINK_MUTATION = gql`
mutation CreateLinkMutation($description: String!, $url: String!, $postedById: ID!) {
createLink(
description: $description,
url: $url,
postedById: $postedById
) {
id
createdAt
url
description
postedBy {
id
name
}
}
}
`
```
</Instruction>
There are two major changes. You first added another argument to the mutation that represents the `id` of the user that is posting the link. Secondly, you also include the `postedBy` information in the _payload_ of the mutation.
Now you need to make sure that the `id` of the posting user is included when you're calling the mutation in `createLink`.
<Instruction>
Open `src/components/CreateLink.vue` and update the implementation of `createLink` like so:
```js(path=".../hackernews-vue-apollo/src/components/CreateLink.vue")
createLink () {
const postedById = localStorage.getItem(GC_USER_ID)
if (!postedById) {
console.error('No user logged in')
return
}
const newDescription = this.description
const newUrl = this.url
this.description = ''
this.url = ''
this.$apollo.mutate({
mutation: CREATE_LINK_MUTATION,
variables: {
description: newDescription,
url: newUrl,
postedById
},
update: (store, { data: { createLink } }) => {
const data = store.readQuery({ query: ALL_LINKS_QUERY })
data.allLinks.push(createLink)
store.writeQuery({ query: ALL_LINKS_QUERY, data })
}
}).then((data) => {
this.$router.push({path: '/'})
}).catch((error) => {
console.error(error)
this.newDescription = newDescription
this.newUrl = newUrl
})
}
```
</Instruction>
For this to work, you also need to import the `GC_USER_ID` key.
<Instruction>
Add the following import statement near the top of `src/components/CreateLink.vue`'s `script` block.
```js(path=".../hackernews-vue-apollo/src/components/CreateLink.vue")
import { GC_USER_ID } from '../constants/settings'
```
</Instruction>
Perfect! Before sending the mutation, you're now also retrieving the corresponding user id from `localStorage`. If that succeeds, you'll pass it to the call to `createLinkMutation` so that every new `Link` will from now on store information about the `User` who created it.
If you haven't done so before, go ahead and test the login functionality. Open `http://localhost:8080/login`. Then click the _need to create an account?_-button and provide some user data for the user you're creating. Finally, click the _create Account_-button. If all went well, the app navigates back to the root route and your user was created. You can verify that the new user is there by checking the [data browser](https://www.graph.cool/docs/reference/console/data-browser-och3ookaeb/) or sending the `allUsers` query in a Playground.
### Configuring Apollo with the Auth Token
Now that users are able to login and obtain a token that authenticates them against the Graphcool backend, you actually need to make sure that the token gets attached to all requests that are sent to the API.
Since all the API requests are actually created and sent by the `ApolloClient` in your app, you need to make sure it knows about the user's token. Luckily, Apollo provides a nice way for authenticating all requests by using [middleware](http://dev.apollodata.com/react/auth.html#Header).
<Instruction>
Open `src/main.js` and put the following code _between_ the creation of the `httpLink` and the instantiation of the `ApolloClient`:
```js(path=".../hackernews-vue-apollo/src/main.js")
const authMiddleware = new ApolloLink((operation, forward) => {
// add the authorization to the headers
const token = localStorage.getItem(GC_AUTH_TOKEN)
operation.setContext({
headers: {
authorization: token ? `Bearer ${token}` : null
}
})
return forward(operation)
})
```
</Instruction>
<Instruction>
Then directly import the key that you need to retrieve the token from `localStorage` on top of the same file:
```js(path=".../hackernews-vue-apollo/src/main.js")
import { GC_USER_ID, GC_AUTH_TOKEN } from './constants/settings'
```
</Instruction>
<Instruction>
Everything looks fine but there is no `ApolloLink` (1) and auth middleware is not connected yet (2) to the instance of `ApolloClient`. Let's fix this:
```js(path=".../hackernews-vue-apollo/src/main.js")
import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
// 1
import { ApolloLink } from 'apollo-link'
// ...
const apolloClient = new ApolloClient({
// 2
link: authMiddleware.concat(httpLink),
cache: new InMemoryCache(),
connectToDevTools: true
})
```
</Instruction>
That's it - now all your API requests will be authenticated if a `token` is available.
> Note: In a real application you would now configure the [authorization rules](https://www.graph.cool/docs/reference/auth/authorization-iegoo0heez/) (permissions) of your project to define what kind of operations authenticated and non-authenticated users should be allowed to perform.
|
howtographql/howtographql
|
content/frontend/vue-apollo/5-authentication.md
|
Markdown
|
mit
| 20,807
|
import React, { Component, PropTypes } from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity
} from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
export default class Home extends Component {
static propTypes = {
onNavigate: PropTypes.func.isRequired
};
toCounter = () => {
const { onNavigate } = this.props;
onNavigate({
type: 'push',
key: 'counter'
});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native Boilerplate!
</Text>
<TouchableOpacity onPress={this.toCounter}>
<Text style={styles.instructions}>Navigate to Counter</Text>
</TouchableOpacity>
</View>
);
}
}
|
SWTPAIN/Lift-to-dominate
|
src/containers/Home.js
|
JavaScript
|
mit
| 1,056
|
<div class="action-bar">
<button type="button" class="search" ng-if="$ctrl.search" tooltip-append-to-body="true" uib-tooltip="Search" ng-click="$ctrl.toggleSearch()">
<span class="sr-only">Search</span>
<i></i>
</button>
<button ng-repeat="action in $ctrl.actions" type="button" class="{{ action.class }}" tooltip-apprend-to-body="true" ng-click="action.click()" uib-tooltip="{{ action.text }}">
<span class="sr-only">{{ action.text }}</span>
<i></i>
</button>
<div class="search-form" ng-if="$ctrl.search" uib-collapse="$ctrl.isSearchCollapsed">
<input type="text" ng-model="$ctrl.searchModel"></input>
</div>
</div>
|
Zokormazo/ngLlery
|
app/components/common/partials/action-bar.html
|
HTML
|
mit
| 650
|
require 'nq'
require 'singleton'
class Nq::CLI
def initialize
end
def run
end
end
|
flingbob/nq
|
lib/nq/cli.rb
|
Ruby
|
mit
| 96
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.