repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
dibu13/TxAndpu_Engine | TxAndpu_Engine/TxAndpu_Engine/ModuleCamera3D.cpp | 4109 | #include "Globals.h"
#include "Application.h"
#include "ModuleCamera3D.h"
#include "ModuleInput.h"
ModuleCamera3D::ModuleCamera3D(bool startEnabled) : Module(startEnabled)
{
LOG("Camera3D: Creation.");
calculateViewMatrix();
X = vec3(1.0f, 0.0f, 0.0f);
Y = vec3(0.0f, 1.0f, 0.0f);
Z = vec3(0.0f, 0.0f, 1.0f);
position = vec3(1.0f, 1.0f, 0.0f);
reference = vec3(0.0f, 0.0f, 0.0f);
}
ModuleCamera3D::~ModuleCamera3D()
{
LOG("Camera3D: Destroying.");
}
// -----------------------------------------------------------------
bool ModuleCamera3D::start()
{
LOG("Camera3D: Start.");
LOG("Setting up the camera");
bool ret = true;
X = vec3(1.0f, 0.0f, 0.0f);
Y = vec3(0.0f, 1.0f, 0.0f);
Z = vec3(0.0f, 0.0f, 1.0f);
position = vec3(2.0f, 3.0f, 2.0f);
reference = vec3(0.0f, 0.0f, 0.0f);
//TMP
app->camera->move(vec3(5.0f, 1.0f, 0.0f));
app->camera->lookAt(vec3(0, 0, 0));
return ret;
}
// -----------------------------------------------------------------
bool ModuleCamera3D::cleanUp()
{
LOG("Camera3D: CleanUp.");
return true;
}
// -----------------------------------------------------------------
update_status ModuleCamera3D::update(float dt)
{
vec3 newPos(0, 0, 0);
float speed = 25.0f * dt;
if (app->input->getKey(SDL_SCANCODE_LSHIFT) == KEY_REPEAT)
speed = 8.0f * dt;
if (app->input->getKey(SDL_SCANCODE_R) == KEY_REPEAT) newPos.y += speed;
if (app->input->getKey(SDL_SCANCODE_F) == KEY_REPEAT) newPos.y -= speed;
if (app->input->getKey(SDL_SCANCODE_W) == KEY_REPEAT) newPos -= Z * speed;
if (app->input->getKey(SDL_SCANCODE_S) == KEY_REPEAT) newPos += Z * speed;
if (app->input->getKey(SDL_SCANCODE_A) == KEY_REPEAT) newPos -= X * speed;
if (app->input->getKey(SDL_SCANCODE_D) == KEY_REPEAT) newPos += X * speed;
position += newPos;
reference += newPos;
// Mouse motion ----------------
if (app->input->getMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT)
{
int dx = -app->input->getMouseXMotion();
int dy = -app->input->getMouseYMotion();
float Sensitivity = 0.25f;
position -= reference;
if (dx != 0)
{
float DeltaX = (float)dx * Sensitivity;
X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f));
Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f));
Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f));
}
if (dy != 0)
{
float DeltaY = (float)dy * Sensitivity;
Y = rotate(Y, DeltaY, X);
Z = rotate(Z, DeltaY, X);
if (Y.y < 0.0f)
{
Z = vec3(0.0f, Z.y > 0.0f ? 1.0f : -1.0f, 0.0f);
Y = cross(Z, X);
}
}
position = reference + Z * length(position);
}
// Recalculate matrix -------------
calculateViewMatrix();
return UPDATE_CONTINUE;
}
// -----------------------------------------------------------------
void ModuleCamera3D::look(const vec3 &_position, const vec3 &_reference, bool rotateAroundReference)
{
this->position = _position;
this->reference = _reference;
Z = normalize(position - reference);
X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
Y = cross(Z, X);
if (!rotateAroundReference)
{
this->reference = this->position;
this->position += Z * 0.05f;
}
calculateViewMatrix();
}
// -----------------------------------------------------------------
void ModuleCamera3D::lookAt( const vec3 &_spot)
{
reference = _spot;
Z = normalize(position - reference);
X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
Y = cross(Z, X);
calculateViewMatrix();
}
// -----------------------------------------------------------------
void ModuleCamera3D::move(const vec3 &_movement)
{
position += _movement;
reference += _movement;
calculateViewMatrix();
}
void ModuleCamera3D::setPos(const vec3 &_pos)
{
position = _pos;
lookAt(reference);
}
// -----------------------------------------------------------------
float* ModuleCamera3D::getViewMatrix()
{
return &viewMatrix;
}
// -----------------------------------------------------------------
void ModuleCamera3D::calculateViewMatrix()
{
viewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, position), -dot(Y, position), -dot(Z, position), 1.0f);
viewMatrixInverse = inverse(viewMatrix);
} | mit |
DkoSoftware/WebPlataform | FamintusApi/Areas/HelpPage/SampleGeneration/TextSample.cs | 887 | using System;
namespace FamintusApi.Areas.HelpPage
{
/// <summary>
/// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class.
/// </summary>
public class TextSample
{
public TextSample(string text)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
Text = text;
}
public string Text { get; private set; }
public override bool Equals(object obj)
{
TextSample other = obj as TextSample;
return other != null && Text == other.Text;
}
public override int GetHashCode()
{
return Text.GetHashCode();
}
public override string ToString()
{
return Text;
}
}
} | mit |
willdurand/Propilex | src/Propilex/View/Endpoint.php | 58 | <?php
namespace Propilex\View;
final class Endpoint
{
}
| mit |
GerMarS/gmk-user-role-test | application/models/users_model.php | 3897 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class users_model extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_users_and_roles()
{
$query = $this->db->query("select * from users");
$user_list = [];
foreach ($query->result() as $row)
{
$query_roles = $this->db->query("select * from user_role where user_id =".$row->user_id);
$roles_list = [];
foreach ($query_roles->result() as $row_role)
$roles_list[] = $row_role->role_id;
$user_list[] = [
'user_id' => $row->user_id,
'name' => $row->name,
'email' => $row->email,
'phone' => $row->phone,
'age' => $row->age,
'roles' => $roles_list,
];
}
return $user_list;
}
function get_roles()
{
$query = $this->db->query("select * from roles");
$roles = [];
foreach ($query->result() as $row)
$roles[$row->role_id] = $row->role;
return $roles;
}
function get_user_list()
{
$query = $this->db->query("select email from users");
$users = [];
foreach ($query->result() as $row)
$users[] = $row->email;
return $users;
}
function get_user_id($email)
{
$sql = "select user_id from users where email = " . $this->db->escape($email);
$query = $this->db->query($sql);
$row = $query->row();
if (!empty($row->user_id))
return $row->user_id;
return 0;
}
function can_read($email)
{
$sql = "select * from users as u
inner join user_role as ur using (user_id)
inner join roles as r using (role_id)
where r.r = 1 and email = ". $this->db->escape($email);
$query = $this->db->query($sql);
if (!empty($query->num_rows()))
return true;
return false;
}
function can_create($email)
{
$sql = "select * from users as u
inner join user_role as ur using (user_id)
inner join roles as r using (role_id)
where r.c = 1 and email = ". $this->db->escape($email);
$query = $this->db->query($sql);
if (!empty($query->num_rows()))
return true;
return false;
}
function can_update($email)
{
$sql = "select * from users as u
inner join user_role as ur using (user_id)
inner join roles as r using (role_id)
where r.u = 1 and email = ". $this->db->escape($email);
$query = $this->db->query($sql);
if (!empty($query->num_rows()))
return true;
return false;
}
function can_delete($email)
{
$sql = "select * from users as u
inner join user_role as ur using (user_id)
inner join roles as r using (role_id)
where r.d = 1 and email = ". $this->db->escape($email);
$query = $this->db->query($sql);
if (!empty($query->num_rows()))
return true;
return false;
}
function create_user($user, $roles)
{
try
{
$this->db->insert('users', $user);
$user_id = $this->db->insert_id();
foreach ($roles as $role)
{
$data_roles = [
'user_id' => $user_id,
'role_id' => $role,
];
$this->db->insert('user_role', $data_roles);
}
}
catch (Exception $e)
{
return false;
}
return true;
}
function update_user($user, $roles)
{
try
{
$user_data = [
'name' => $user['name'],
'phone' => $user['phone'],
'age' => $user['age'],
];
$user_id = $this->get_user_id($user['email']);
$this->db->where('user_id', $user_id);
$this->db->update('users', $user_data);
$this->db->where('user_id', $user_id);
$this->db->delete('user_role');
foreach ($roles as $role)
{
$data_roles = [
'user_id' => $user_id,
'role_id' => $role,
];
$this->db->insert('user_role', $data_roles);
}
}
catch (Exception $e)
{
return false;
}
return true;
}
function delete_user($email)
{
try
{
$user_id = $this->get_user_id($email);
$this->db->where('user_id', $user_id);
$this->db->delete('users');
}
catch (Exception $e)
{
return false;
}
return true;
}
} | mit |
netodeolino/curso-angular-2 | diretivas/src/app/app.module.ts | 669 | import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { DiretivaNgifComponent } from './diretiva-ngif/diretiva-ngif.component';
import { DiretivaNgswitchComponent } from './diretiva-ngswitch/diretiva-ngswitch.component';
@NgModule({
declarations: [
AppComponent,
DiretivaNgifComponent,
DiretivaNgswitchComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
| mit |
Aurelsicoko/prestashop-14 | themes/default-bootstrap/modules/blockbestsellers/translations/fr.php | 2304 | <?php
global $_MODULE;
$_MODULE = array();
$_MODULE['<{blockbestsellers}default-bootstrap>blockbestsellers_9862f1949f776f69155b6e6b330c7ee1'] = 'Bloc meilleures ventes';
$_MODULE['<{blockbestsellers}default-bootstrap>blockbestsellers_ed6476843a865d9daf92e409082b76e1'] = 'Ajoute un bloc qui affiche les meilleures ventes de la boutique.';
$_MODULE['<{blockbestsellers}default-bootstrap>blockbestsellers_c888438d14855d7d96a2724ee9c306bd'] = 'Mise à jour réussie';
$_MODULE['<{blockbestsellers}default-bootstrap>blockbestsellers_f4f70727dc34561dfde1a3c529b6205c'] = 'Paramètres';
$_MODULE['<{blockbestsellers}default-bootstrap>blockbestsellers_26986c3388870d4148b1b5375368a83d'] = 'Produits à afficher';
$_MODULE['<{blockbestsellers}default-bootstrap>blockbestsellers_2b21378492166b0e5a855e2da611659c'] = 'Définit le nombre de produits à afficher dans ce bloc';
$_MODULE['<{blockbestsellers}default-bootstrap>blockbestsellers_24ff4e4d39bb7811f6bdf0c189462272'] = 'Toujours afficher ce bloc';
$_MODULE['<{blockbestsellers}default-bootstrap>blockbestsellers_84b0c5fdef19ab8ef61cd809f9250d85'] = 'Afficher le bloc même si il n\'y a aucune meilleure vente à afficher.';
$_MODULE['<{blockbestsellers}default-bootstrap>blockbestsellers_00d23a76e43b46dae9ec7aa9dcbebb32'] = 'Activé';
$_MODULE['<{blockbestsellers}default-bootstrap>blockbestsellers_b9f5c797ebbf55adccdd8539a65a0241'] = 'Désactivé';
$_MODULE['<{blockbestsellers}default-bootstrap>blockbestsellers_c9cc8cce247e49bae79f15173ce97354'] = 'Enregistrer';
$_MODULE['<{blockbestsellers}default-bootstrap>blockbestsellers-home_09a5fe24fe0fc9ce90efc4aa507c66e7'] = 'Aucune meilleure vente à l\'heure actuelle.';
$_MODULE['<{blockbestsellers}default-bootstrap>blockbestsellers_1d0a2e1f62ccf460d604ccbc9e09da95'] = 'Voir une des meilleures ventes';
$_MODULE['<{blockbestsellers}default-bootstrap>blockbestsellers_3cb29f0ccc5fd220a97df89dafe46290'] = 'Meilleures ventes';
$_MODULE['<{blockbestsellers}default-bootstrap>blockbestsellers_eae99cd6a931f3553123420b16383812'] = 'Toutes les meilleures ventes';
$_MODULE['<{blockbestsellers}default-bootstrap>blockbestsellers_f7be84d6809317a6eb0ff3823a936800'] = 'Pas encore de meilleure vente';
$_MODULE['<{blockbestsellers}default-bootstrap>tab_d7b2933ba512ada478c97fa43dd7ebe6'] = 'Meilleures Ventes';
| mit |
joserochadocarmo/sau | app/view1/view1.js | 4969 | //'use strict';
angular.module('myApp.view1', ['ngRoute', 'ui.bootstrap'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
})
.when('/detail/:cpf', {
controller: 'DetailCtrl',
templateUrl: 'view1/detail.html'
});
}])
.factory('Pessoas', function () {
var Pessoas = {};
Pessoas.cast = [
{
nome: "josé rocha do carmo",
login_unico: "joserocha",
emails: ["tom.jrc@gmail.com", "tom.jrc1@gmail.com"],
cpf: 1161061150,
id: 1
},
{nome: "pablo leonardo", login_unico: "pablo", emails: {email: "pablo@gmail.com"}, cpf: 1161061150, id: 2},
{
nome: "ricardo borges",
login_unico: "ricardo",
emails: {email: "ricardo@gmail.com"},
cpf: 1161061150,
id: 3
},
{nome: "maria da penha", login_unico: "maria", emails: {email: ""}, cpf: 1161061151, id: 4},
{nome: "frodo bolseiro", login_unico: "frodo", emails: {email: "frodo@gmail.com"}, cpf: 1161061150, id: 6},
{nome: "bilbo bolseiro", login_unico: "bilbo", emails: {email: "bilbo@gmail.com"}, cpf: 1161061150, id: 7}
];
return Pessoas;
}
)
.controller('View1Ctrl', function ($scope, Pessoas, $modal) {
console.log("View1Ctrl - search:" + search.value);
$scope.pessoas = Pessoas;
$scope.findByType = function (search) {
var type = '';
if (!search)
return "...";
switch (defineType(search)) {
case "email":
type = "e-mail: ";
break;
case "nome":
type = "nome: ";
break;
case "loginunico":
type = "login único: ";
break;
case "cpf":
type = "cpf: ";
break;
case "cd_pessoa":
type = "identificador pessoa: ";
break;
}
return type + search;
}
$scope.open = function (size,cpf) {
var modalInstance = $modal.open({
templateUrl: 'view1/detail.html',
controller: 'DetailCtrl',
size: size,
resolve: {
cpf: function () {
return cpf;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
});
};
})
.controller('DetailCtrl', function ($scope, $modalInstance, cpf) {
console.log("cpf:" + cpf);
$scope.cpf=cpf;
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
var defineType = function (search) {
if (isNaN(search)) {
if (isEmail(search))
return "email";
else if (isNome(search))
return "nome";
else
return "loginunico";
}
else {
if (validarCPF(search))
return "cpf";
else
return "cd_pessoa";
}
console.log("returning void..." + search)
return '';
}
function isEmail(email) {
return email.indexOf("@") != -1;
}
function isNome(nome) {
return (
nome.indexOf(" ") != -1
);
}
function validarCPF(cpf) {
cpf = cpf.replace(/[^\d]+/g, '');
if (cpf == '') return false;
// Elimina CPFs invalidos conhecidos
cpf = cpf.lpad('0', 11);
//console.log(cpf);
if (cpf.length != 11 ||
cpf == "00000000000" ||
cpf == "11111111111" ||
cpf == "22222222222" ||
cpf == "33333333333" ||
cpf == "44444444444" ||
cpf == "55555555555" ||
cpf == "66666666666" ||
cpf == "77777777777" ||
cpf == "88888888888" ||
cpf == "99999999999")
return false;
// Valida 1o digito
add = 0;
for (i = 0; i < 9; i++)
add += parseInt(cpf.charAt(i)) * (10 - i);
rev = 11 - (add % 11);
if (rev == 10 || rev == 11)
rev = 0;
if (rev != parseInt(cpf.charAt(9)))
return false;
// Valida 2o digito
add = 0;
for (i = 0; i < 10; i++)
add += parseInt(cpf.charAt(i)) * (11 - i);
rev = 11 - (add % 11);
if (rev == 10 || rev == 11)
rev = 0;
if (rev != parseInt(cpf.charAt(10)))
return false;
return true;
}
//pads left
String.prototype.lpad = function (padString, length) {
var str = this;
while (str.length < length)
str = padString + str;
return str;
} | mit |
ICJIA/icjia-tvpp | statamic/core/Search/Algolia/Index.php | 3392 | <?php
namespace Statamic\Search\Algolia;
use Statamic\API\Str;
use AlgoliaSearch\Client;
use Statamic\Search\ItemResolver;
use AlgoliaSearch\AlgoliaException;
use Statamic\Events\SearchQueryPerformed;
use Statamic\Search\Index as AbstractIndex;
use Statamic\Search\IndexNotFoundException;
class Index extends AbstractIndex
{
/**
* @var Client
*/
protected $client;
/**
* @var \AlgoliaSearch\Index
*/
protected $index;
/**
* @param ItemResolver $itemResolver
* @param Client $client
*/
public function __construct(ItemResolver $itemResolver, Client $client)
{
parent::__construct($itemResolver);
$this->client = $client;
}
/**
* @inheritdoc
*/
public function insert($id, $fields)
{
$fields['objectID'] = $id;
$this->getIndex()->saveObject($fields);
}
/**
* @inheritdoc
*/
public function insertMultiple($documents)
{
$this->getIndex()->deleteObjects(array_keys($documents));
$objects = collect($documents)->map(function ($item, $id) {
$item['objectID'] = $id;
return $item;
})->values();
$this->getIndex()->saveObjects($objects);
}
/**
* @inheritdoc
*/
public function delete($id)
{
$this->getIndex()->deleteObject($id);
}
/**
* @inheritdoc
*/
public function search($query, $fields = null)
{
event(new SearchQueryPerformed($query));
$arguments = [
'restrictSearchableAttributes' => implode(',', is_array($fields) ? $fields : array($fields))
];
try {
$response = $this->getIndex()->search($query, $arguments);
} catch (AlgoliaException $e) {
$this->handleAlgoliaException($e);
\Log::error($e);
return [];
}
return collect($response['hits'])->map(function ($hit) {
$hit['id'] = $hit['objectID'];
return $hit;
});
}
/**
* @inheritdoc
*/
public function deleteIndex()
{
$this->getIndex()->clearIndex();
}
/**
* Get the Algolia index.
*
* @return \AlgoliaSearch\Index
*/
public function getIndex()
{
if (! $this->index) {
$name = str_replace('/', '_', $this->name());
$this->index = $this->client->initIndex($name);
}
return $this->index;
}
/**
* Throws a more user friendly exception.
*
* @param AlgoliaException $e
* @throws \Exception
*/
private function handleAlgoliaException($e)
{
if (Str::contains($e->getMessage(), "Index {$this->name} does not exist")) {
throw new IndexNotFoundException("Index [{$this->name}] does not exist.");
}
if (preg_match('/attribute (.*) is not in searchableAttributes/', $e->getMessage(), $matches)) {
throw new \Exception(
"Field [{$matches[1]}] does not exist in this index's searchableAttributes list."
);
}
}
/**
* @inheritdoc
*/
public function exists()
{
return null !== collect($this->client->listIndexes()['items'])->first(function ($i, $index) {
return $index['name'] == str_replace('/', '_', $this->name);
});
}
}
| mit |
haystack/eyebrowse-server | notifications/models.py | 7781 | from __future__ import unicode_literals
from __future__ import print_function
import base64
import datetime
from django.db import models
from django.db.models.query import QuerySet
from django.core.exceptions import ImproperlyConfigured
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import get_language, activate
from django.utils.encoding import python_2_unicode_compatible
from django.utils.six.moves import cPickle as pickle # pylint: disable-msg=F
from notifications.compat import AUTH_USER_MODEL, GenericForeignKey
from notifications.conf import settings
from notifications.utils import load_media_defaults, notice_setting_for_user, my_import
from notifications.backends.email import EmailBackend
NOTICE_MEDIA, NOTICE_MEDIA_DEFAULTS = load_media_defaults()
class LanguageStoreNotAvailable(Exception):
pass
@python_2_unicode_compatible
class NoticeType(models.Model):
label = models.CharField(_("label"), max_length=40, unique=True)
display = models.CharField(_("display"), max_length=50)
description = models.CharField(_("description"), max_length=100)
# by default only on for media with sensitivity less than or equal to this
# number
default = models.IntegerField(_("default"))
def __str__(self):
return self.label
class Meta:
verbose_name = _("notice type")
verbose_name_plural = _("notice types")
@classmethod
def create(cls, label, display, description, default=2, verbosity=1):
"""
Creates a new NoticeType.
This is intended to be used by other apps as a post_syncdb manangement step.
"""
try:
notice_type = cls._default_manager.get(label=label)
updated = False
if display != notice_type.display:
notice_type.display = display
updated = True
if description != notice_type.description:
notice_type.description = description
updated = True
if default != notice_type.default:
notice_type.default = default
updated = True
if updated:
notice_type.save()
if verbosity > 1:
print("Updated %s NoticeType" % label)
except cls.DoesNotExist:
cls(label=label, display=display,
description=description, default=default).save()
if verbosity > 1:
print("Created %s NoticeType" % label)
class Notification(models.Model):
recipient = models.ForeignKey(User, related_name="notification_recipient")
sender = models.ForeignKey(User, related_name="notification_sender")
date_created = models.DateTimeField(default=datetime.datetime.utcnow())
notice_type = models.ForeignKey(NoticeType)
seen = models.BooleanField(default=False)
url = models.URLField(max_length=300, blank=False, null=True)
message = models.CharField(max_length=2000, blank=False, null=True)
class NoticeSetting(models.Model):
"""
Indicates, for a given user, whether to send notifications
of a given type to a given medium.
"""
user = models.ForeignKey(AUTH_USER_MODEL, verbose_name=_("user"))
notice_type = models.ForeignKey(NoticeType, verbose_name=_("notice type"))
medium = models.CharField(_("medium"), max_length=1, choices=NOTICE_MEDIA)
send = models.BooleanField(_("send"), default=False)
scoping_content_type = models.ForeignKey(
ContentType, null=True, blank=True)
scoping_object_id = models.PositiveIntegerField(null=True, blank=True)
scoping = GenericForeignKey("scoping_content_type", "scoping_object_id")
@classmethod
def for_user(cls, user, notice_type, medium, scoping=None):
"""
Kept for backwards compatibilty but isn't used anywhere within this app
@@@ consider deprecating
"""
return notice_setting_for_user(user, notice_type, medium, scoping)
class Meta:
verbose_name = _("notice setting")
verbose_name_plural = _("notice settings")
unique_together = (
"user", "notice_type", "medium", "scoping_content_type", "scoping_object_id")
class NoticeQueueBatch(models.Model):
"""
A queued notice.
Denormalized data for a notice.
"""
pickled_data = models.TextField()
def get_notification_language(user):
"""
Returns site-specific notification language for this user. Raises
LanguageStoreNotAvailable if this site does not use translated
notifications.
"""
if settings.PINAX_NOTIFICATIONS_LANGUAGE_MODEL:
model = settings.PINAX_NOTIFICATIONS_GET_LANGUAGE_MODEL()
try:
language = model._default_manager.get(user__id__exact=user.id)
if hasattr(language, "language"):
return language.language
except (ImportError, ImproperlyConfigured, model.DoesNotExist):
raise LanguageStoreNotAvailable
raise LanguageStoreNotAvailable
def send_now(users, label, extra=None, sender=None, scoping=None):
"""
Creates a new notice.
This is intended to be how other apps create new notices.
notification.send(user, "friends_invite_sent", {
"spam": "eggs",
"foo": "bar",
)
"""
sent = False
if extra is None:
extra = {}
notice_type = NoticeType.objects.get(label=label)
current_language = get_language()
for user in users:
# get user language for user from language store defined in
# NOTIFICATION_LANGUAGE_MODULE setting
try:
language = get_notification_language(user)
except LanguageStoreNotAvailable:
language = None
if language is not None:
# activate the user's language
activate(language)
# Since we only have 1 medium, just hardcode it in (was getting some weird
# 'module' object is not callable error)
backend = EmailBackend(0)
if backend.can_send(user, notice_type, scoping=scoping):
backend.deliver(user, sender, notice_type, extra)
sent = True
# reset environment to original language
activate(current_language)
return sent
def send(*args, **kwargs):
"""
A basic interface around both queue and send_now. This honors a global
flag NOTIFICATION_QUEUE_ALL that helps determine whether all calls should
be queued or not. A per call ``queue`` or ``now`` keyword argument can be
used to always override the default global behavior.
"""
queue_flag = kwargs.pop("queue", False)
now_flag = kwargs.pop("now", False)
assert not (
queue_flag and now_flag), "'queue' and 'now' cannot both be True."
if queue_flag:
return queue(*args, **kwargs)
elif now_flag:
return send_now(*args, **kwargs)
else:
if settings.PINAX_NOTIFICATIONS_QUEUE_ALL:
return queue(*args, **kwargs)
else:
return send_now(*args, **kwargs)
def queue(users, label, extra=None, sender=None):
"""
Queue the notification in NoticeQueueBatch. This allows for large amounts
of user notifications to be deferred to a seperate process running outside
the webserver.
"""
if extra is None:
extra = {}
if isinstance(users, QuerySet):
users = [row["pk"] for row in users.values("pk")]
else:
users = [user.pk for user in users]
notices = []
for user in users:
notices.append((user, label, extra, sender))
NoticeQueueBatch(
pickled_data=base64.b64encode(pickle.dumps(notices))).save()
| mit |
ksaluja24/scratch-bench | src/scratchbench/KController.java | 3835 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package scratchbench;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import static scratchbench.Login.serverAddress;
import static scratchbench.ScratchBench.test;
/**
* FXML Controller class
*
* @author Kp Saluja
*/
public class KController extends AnchorPane implements Initializable {
@FXML
private Button loginButton;
@FXML
private TextField userNameTF;
@FXML
private Button testUserButton;
@FXML
private Label validateTrueLabel;
@FXML
private Label validateFalseLabel;
@FXML
private AnchorPane content;
public static MainMenu kmm;
public static String email="";
public static String password;
private boolean b;
private boolean emailExists;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
b=false;
}
@FXML
public void processLogin(ActionEvent event) throws InterruptedException {
login();
}
@FXML
private void continueAsTest() throws IOException
{
kmm=new MainMenu();
kmm.setVisible(true);
test.dispose();
callThreads();
}
private void continueAsRegistered() throws IOException {
callThreads();
if(b==true)
{
String email=userNameTF.getText();
if(serverAddress.existsByEmail(email)==true)
{
id.id=serverAddress.getID();
test.loadSecondFxml("enter.fxml");
System.out.println("KController: "+id.id);
password=serverAddress.getPassword();
}
else
{
test.loadSecondFxml("login.fxml");
}
}
}
@FXML
private void emailcheck(KeyEvent k)
{
String c=k.getCharacter();
if(c.equals(" "))
{
k.consume();
}
String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
if(userNameTF.getText().matches(EMAIL_REGEX))
{
validateFalseLabel.setVisible(false);
validateTrueLabel.setVisible(true);
validateTrueLabel.setText("Kindly click on Login");
b=true;
}
else
{
validateTrueLabel.setVisible(false);
validateFalseLabel.setVisible(true);
validateFalseLabel.setText("Invalid E-Mail Format");
b=false;
}
}
@FXML
private void login() {
email=userNameTF.getText();
if(email.length()==0)
{
try {
continueAsTest();
} catch (IOException ex) {
Logger.getLogger(KController.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
try {
continueAsRegistered();
} catch (IOException ex) {
Logger.getLogger(KController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void callThreads() {
Thread t1=new Thread(new Runnable(){
@Override
public void run()
{
new MyTimerTask();
}
});
Thread t2=new Thread(new Runnable(){
@Override
public void run()
{
new AutoSave();
}
});
t1.start();
t2.start();
}
} | mit |
carbon/Amazon | src/Amazon.Sqs.Tests/Requests/RecieveMessagesRequestTests.cs | 388 | namespace Amazon.Sqs.Tests
{
public class RecieveMessagesRequestTests
{
[Fact]
public void CanConstruct()
{
var request = new RecieveMessagesRequest(5, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(20));
Assert.Null(request.AttributeNames);
Assert.Null(request.MessageAttributeNames);
}
}
} | mit |
zhangqiang110/my4j | pms/src/main/java/com/swfarm/biz/product/dao/StockKeepingUnitGroupDao.java | 248 | package com.swfarm.biz.product.dao;
import com.swfarm.biz.product.bo.StockKeepingUnitGroup;
import com.swfarm.pub.framework.dao.GenericDao;
public interface StockKeepingUnitGroupDao extends
GenericDao<StockKeepingUnitGroup, Long> {
}
| mit |
TeleSign/node_telesign | examples/phoneid/2_cleansing_updated_number.js | 1428 | // note change this to the following if using npm package: require('telesignsdk);
const TeleSignSDK = require('../../src/TeleSign');
//var TeleSignSDK = require('telesignsdk');
const customerId = "customer_id"; // Todo: find in portal.telesign.com
const apiKey = "dGVzdCBhcGkga2V5IGZvciBzZGsgZXhhbXBsZXM="; // Todo: find in portal.telesign.com
const rest_endpoint = "https://rest-api.telesign.com"; // Todo: Enterprise customer, change this!
const timeout = 10*1000; // 10 secs
const client = new TeleSignSDK( customerId,
apiKey,
rest_endpoint,
timeout // optional
// userAgent
);
const phoneNumber = "phone_number";
console.log("## PhoneIDClient.phoneID ##");
function messageCallback(error, responseBody) {
if (error === null) {
console.log(`PhoneID response for phone number: ${phoneNumber} ` +
`=> code: ${responseBody['status']['code']}, ` +
`description: ${responseBody['status']['description']}`);
if (responseBody['status']['code'] === 200) {
const cc = responseBody['numbering']['cleansing']['call']['country_code'];
const pn = responseBody['numbering']['cleansing']['call']['phone_number'];
console.log("Cleansed phone number has country code $cc and phone number is $pn.")
}
} else {
console.error("Unable to get PhoneID. $error");
}
}
client.phoneid.phoneID(messageCallback, phoneNumber);
| mit |
ezrondre/bootstrap_forms | lib/bootstrap_forms/bootstrap_form_helper.rb | 1586 |
module BootstrapForms
module BootstrapFormHelper
ALERT_TYPES = [:danger, :info, :success, :warning] unless const_defined?(:ALERT_TYPES)
def bootstrap_flash(messages = nil)
flash_messages = []
(messages || flash).each do |type, message|
# Skip empty messages, e.g. for devise messages set to nothing in a locale file.
next if message.blank?
type = type.to_sym
type = :info if type == :notice
type = :danger if type == :error
next unless ALERT_TYPES.include?(type)
Array(message).each do |msg|
text = content_tag(:div,
content_tag(:button, raw("×"), :class => "close", "data-dismiss" => "alert") +
msg, :class => "alert fade in alert-#{type} alert-dismissible")
flash_messages << text if msg
end
end
flash_messages.join("\n").html_safe
end
def error_messages_for(record)
return unless record
messages = {error: []}
errors_obj = record.is_a?(ActiveModel::Errors) ? record : record.errors
errors_obj.full_messages.each do |message|
messages[:error] << message
end
bootstrap_flash(messages)
end
def bootstrap_form_for(*args, &block)
args << {} unless args.last.is_a?(Hash)
options = args.last
options[:html] ||= {}
options[:html].merge!(:class => "bootsrap_form"){|key,val1,val2| val1.to_s+' '+val2 }
options.merge!({:builder => Youmix::BootstrapFormBuilder})
form_for(*args, &block)
end
end
end
| mit |
nudesign/media_magick | spec/dummy/app/uploaders/post_uploader.rb | 479 | # encoding: utf-8
require "media_magick/image/dimensions"
class PostUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
include MediaMagick::Image::Dimensions
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# process :resize_to_fill => [960, 544]
version :thumb do
process :resize_to_fit => [250, 136]
end
version :big do
process :resize_to_limit => [864, 489]
end
end
| mit |
concord-consortium/energy3d | src/main/java/org/concord/energy3d/undo/ChangeFoundationSolarReflectorOpticalEfficiencyCommand.java | 1654 | package org.concord.energy3d.undo;
import java.util.List;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import org.concord.energy3d.model.Foundation;
import org.concord.energy3d.model.SolarReflector;
public class ChangeFoundationSolarReflectorOpticalEfficiencyCommand extends MyAbstractUndoableEdit {
private static final long serialVersionUID = 1L;
private final double[] oldValues;
private double[] newValues;
private final Foundation foundation;
private final List<SolarReflector> reflectors;
public ChangeFoundationSolarReflectorOpticalEfficiencyCommand(final Foundation foundation, final Class<?> c) {
this.foundation = foundation;
reflectors = foundation.getSolarReflectors(c);
final int n = reflectors.size();
oldValues = new double[n];
for (int i = 0; i < n; i++) {
oldValues[i] = reflectors.get(i).getOpticalEfficiency();
}
}
public Foundation getFoundation() {
return foundation;
}
@Override
public void undo() throws CannotUndoException {
super.undo();
final int n = reflectors.size();
newValues = new double[n];
for (int i = 0; i < n; i++) {
newValues[i] = reflectors.get(i).getOpticalEfficiency();
reflectors.get(i).setOpticalEfficiency(oldValues[i]);
}
}
@Override
public void redo() throws CannotRedoException {
super.redo();
final int n = reflectors.size();
for (int i = 0; i < n; i++) {
reflectors.get(i).setOpticalEfficiency(newValues[i]);
}
}
@Override
public String getPresentationName() {
return "Optical Efficiency Change for All " + reflectors.get(0).getClass().getSimpleName() + "s on Selected Foundation";
}
}
| mit |
fredericcormier/WesternMusicElements | WesternMusicElements/Ruby/WMRubyData.rb | 3782 | module WMRubyData
FILE_HEADER = <<HEADER
//
// WMData.h
// WesternMusicElements
//
// Created by Cormier Frederic on 06/03/12.
// Copyright (c) 2012 International MicrOondes. All rights reserved.
//
HEADER
CHORDS = {
"Major" => [0,4,7],
"Major 6" => [0,4,7,9 ],
"Major 7" => [0,4,7,11],
"Major 9" => [0,4,7,11,14],
"Major 69"=> [0,4,7,9,14],
"Major 11" => [0,4,7,11,14,17],
"Major 13" => [0,4,7,11,14,17,21],
"Minor" => [0,3,7],
"Minor 6" => [0,3,7,9],
"Minor 7" => [0,3,7,10],
"Minor 9" => [0,3,7,10,14],
"Minor 69" => [0,3,7,9,14],
"Minor 11" => [0,3,7,10,14,17],
"Minor 13" => [0,3,7,10,14,17,21],
"Dominant 7"=> [0,4,7,10],
"Ninth" => [0,4,7,10,14],
"Eleventh" => [0,4,7,10,14,17],
"Thirteenth" => [0,4,7,10,14,17,21],
"Diminished" => [0,3,6],
"Half Diminished 7" => [0,3,6,10],
"Diminished 7" => [0,3,6,9],
"Augmented" => [0,4,8],
"Augmented 7" => [0,4,8,10],
"Sus4" => [0,5,7],
"Seventh sus4" => [0,5,7,10],
"Minor major" => [0,3,7,11]
}
SCALES = {
"Chromatic" => [0,1,2,3,4,5,6,7,8,9,10,11,12],
"Major" => [0,2,4,5,7,9,11,12],
"Natural Minor" => [0,2,3,5,7,8,10,12],
"Harmonic Minor" => [0,2,3,5,7,8,11,12],
"Melodic Minor" => [0,2,3,5,7,9,11,12],
"Ionian" => [0,2,4,5,7,9,11,12],
"Dorian" => [0,2,3,5,7,9,10,12],
"Phrygian" => [0,1,3,5,7,8,10,12],
"Lydian" => [0,2,4,6,7,9,11,12],
"Mixolydian" => [0,2,4,5,7,9,10,12],
"Aeolian" => [0,2,3,5,7,8,10,12],
"Locrian" => [0,1,3,5,6,8,10,12],
"Gypsy Minor" => [0,2,3,6,7,8,11,12],
"Whole Tone" => [0,2,4,6,8,10,12],
"Major Pentatonic" => [0,2,4,7,9,12],
"Minor Pentatonic" => [0,3,5,7,10,12],
"Major Bebop" => [0,2,4,5,7,8,9,11,12],
"Altered Scale" => [0,1,3,4,6,8,10,12],
"Dorian Bebop"=> [0,2,3,4,5,7,9,10,12],
"Mixolydian Bebop"=> [0,2,4,5,7,9,10,11,12],
"Blues Scale"=> [0,3,5,6,7,10,12],
"Diminished Whole Half"=>[0,2,3,5,6,8,9,11,12],
"Diminished Half Whole" =>[0,1,3,4,6,7,9,10,12],
"Neapolitan Major" => [0,1,3,5,7,9,11,12],
"Hungarian Major" => [0,3,4,6,7,9,10,12],
"Harmonic Major" => [0,2,4,5,7,8,11,12],
"Hungarian Minor" => [0,2,3,6,7,8,11,12],
"Lydian Minor" => [0,2,4,6,7,8,10,12],
"Neapolitan Minor" => [0,1,3,5,7,8,11,12],
"Major Locrian" => [0,2,4,5,6,8,10,12],
"Leading Whole Tone" => [0,2,4,6,8,10,11,12],
"Six Tone Symmetrical" => [0,1,4,5,8,9,11,12],
"Arabian" => [0,2,4,5,6,8,10,12],
"Balinese" => [0,1,3,7,8,12],
"Byzantine" => [0,1,3,5,7,8,11,12],
"Hungarian Gypsy"=> [0,2,4,6,7,8,10,12],
"Persian" => [0,1,4,5,6,8,11,12],
"East Indian Purvi" => [0,1,4,6,7,8,11,12],
"Oriental" => [0,1,4,5,6,9,10,12],
"Double Harmonic" => [0,1,4,5,7,8,11,12],
"Enigmatic" => [0,1,4,6,8,10,11,12],
"Overtone" => [0,2,4,6,7,9,10,12],
"Eight Tone Spanish" => [0,1,3,4,5,6,8,10,12],
"Prometheus" => [0,2,4,6,9,10,12],
"GAGAKU Rittsu Sen Pou" => [0,2,5,7,9,10,12],
"GAGAKU Ryo Sen Pou" => [0,2,4,7,9,12],
"ZOKUGAKU Yo Sen Pou" => [0,3,5,7,10,12],
"In Sen Pou" => [0,1,5,2,8,12],
"Okinawa" => [0,4,5,7,11,12]
}
end | mit |
nfqakademija/indigo | src/Indigo/MainBundle/Resources/public/js/demo.js | 18484 |
// Polyfills
//
(function() {
// Array indexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement, fromIndex) {
if ( this === undefined || this === null ) {
throw new TypeError( '"this" is null or not defined' );
}
var length = this.length >>> 0; // Hack to convert object.length to a UInt32
fromIndex = +fromIndex || 0;
if (Math.abs(fromIndex) === Infinity) {
fromIndex = 0;
}
if (fromIndex < 0) {
fromIndex += length;
if (fromIndex < 0) {
fromIndex = 0;
}
}
for (;fromIndex < length; fromIndex++) {
if (this[fromIndex] === searchElement) {
return fromIndex;
}
}
return -1;
};
}
// Event listener
if (!Event.prototype.preventDefault) {
Event.prototype.preventDefault=function() {
this.returnValue=false;
};
}
if (!Event.prototype.stopPropagation) {
Event.prototype.stopPropagation=function() {
this.cancelBubble=true;
};
}
if (!Element.prototype.addEventListener) {
var eventListeners=[];
var addEventListener=function(type,listener /*, useCapture (will be ignored) */) {
var self=this;
var wrapper=function(e) {
e.target=e.srcElement;
e.currentTarget=self;
if (listener.handleEvent) {
listener.handleEvent(e);
} else {
listener.call(self,e);
}
};
if (type=="DOMContentLoaded") {
var wrapper2=function(e) {
if (document.readyState=="complete") {
wrapper(e);
}
};
document.attachEvent("onreadystatechange",wrapper2);
eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper2});
if (document.readyState=="complete") {
var e=new Event();
e.srcElement=window;
wrapper2(e);
}
} else {
this.attachEvent("on"+type,wrapper);
eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper});
}
};
var removeEventListener=function(type,listener /*, useCapture (will be ignored) */) {
var counter=0;
while (counter<eventListeners.length) {
var eventListener=eventListeners[counter];
if (eventListener.object==this && eventListener.type==type && eventListener.listener==listener) {
if (type=="DOMContentLoaded") {
this.detachEvent("onreadystatechange",eventListener.wrapper);
} else {
this.detachEvent("on"+type,eventListener.wrapper);
}
break;
}
++counter;
}
};
Element.prototype.addEventListener=addEventListener;
Element.prototype.removeEventListener=removeEventListener;
if (HTMLDocument) {
HTMLDocument.prototype.addEventListener=addEventListener;
HTMLDocument.prototype.removeEventListener=removeEventListener;
}
if (Window) {
Window.prototype.addEventListener=addEventListener;
Window.prototype.removeEventListener=removeEventListener;
}
}
})();
// Demo
//
(function() {
var storageSupported = (typeof(window.Storage)!=="undefined");
// Functions
//
var reloadPage = function () {
location.reload();
}
var testTheme = function (name) {
for (var j=0; j<demo_themes.length; j++) {
if (demo_themes[j].name === name) {
return demo_themes[j].name;
}
}
return 'default';
}
var loadDemoSettings = function () {
var result = {
fixed_navbar: false,
fixed_menu: false,
rtl: false,
menu_right: false,
theme: 'default'
};
if (storageSupported) {
try {
result.fixed_navbar = (window.localStorage.demo_fixed_navbar && window.localStorage.demo_fixed_navbar === '1');
result.fixed_menu = (window.localStorage.demo_fixed_menu && window.localStorage.demo_fixed_menu === '1');
result.rtl = (window.localStorage.demo_rtl && window.localStorage.demo_rtl === '1');
result.menu_right = (window.localStorage.demo_menu_right && window.localStorage.demo_menu_right === '1');
result.theme = testTheme((window.localStorage.demo_theme) ? window.localStorage.demo_theme : '');
return result;
} catch (e) {}
}
var key, val, pos, demo_cookies = document.cookie.split(';');
for (var i=0, l=demo_cookies.length; i < l; i++) {
pos = demo_cookies[i].indexOf('=');
key = demo_cookies[i].substr(0, pos).replace(/^\s+|\s+$/g, '');
val = demo_cookies[i].substr(pos + 1).replace(/^\s+|\s+$/g, '');
if (key === 'demo_fixed_navbar') {
result.fixed_navbar = (val === '1') ? true : false;
} else if (key === 'demo_fixed_menu') {
result.fixed_menu = (val === '1') ? true : false;
} else if (key === 'demo_rtl') {
result.rtl = (val === '1') ? true : false;
} else if (key === 'demo_menu_right') {
result.menu_right = (val === '1') ? true : false;
} else if (key === 'demo_theme') {
result.theme = testTheme(val);
}
}
return result;
}
var saveDemoSettings = function () {
if (storageSupported) {
try {
window.localStorage.demo_fixed_navbar = escape((demo_settings.fixed_navbar) ? '1' : '0');
window.localStorage.demo_fixed_menu = escape((demo_settings.fixed_menu) ? '1' : '0');
window.localStorage.demo_rtl = escape((demo_settings.rtl) ? '1' : '0');
window.localStorage.demo_menu_right = escape((demo_settings.menu_right) ? '1' : '0');
window.localStorage.demo_theme = escape(demo_settings.theme);
return;
} catch (e) {}
}
document.cookie = 'demo_fixed_navbar=' + escape((demo_settings.fixed_navbar) ? '1' : '0');
document.cookie = 'demo_fixed_menu=' + escape((demo_settings.fixed_menu) ? '1' : '0');
document.cookie = 'demo_rtl=' + escape((demo_settings.rtl) ? '1' : '0');
document.cookie = 'demo_menu_right=' + escape((demo_settings.menu_right) ? '1' : '0');
document.cookie = 'demo_theme=' + escape(demo_settings.theme);
}
var getThemesTemplate = function () {
result = '';
for (var i=0, l=demo_themes.length-1; i <= l; i++) {
if (i % 2 == 0) {
result = result + '<div class="demo-themes-row">';
result = result + '<a href="#" class="demo-theme" data-theme="' + demo_themes[i].name + '"><div class="theme-preview"><img src="' + demo_themes[i].img + '" alt=""></div><div class="overlay"></div><span>' + demo_themes[i].title + '</span></a>';
} else {
result = result + '<a href="#" class="demo-theme" data-theme="' + demo_themes[i].name + '"><div class="theme-preview"><img src="' + demo_themes[i].img + '" alt=""></div><div class="overlay"></div><span>' + demo_themes[i].title + '</span></a>';
result = result + '</div>';
}
if (i == l && i % 2 == 0) {
result = result + '<div class="demo-theme"></div></div>';
}
}
return result;
}
var activateTheme = function (btns) {
document.body.className = document.body.className.replace(/theme\-[a-z0-9\-\_]+/ig, 'theme-' + demo_settings.theme);
if (! btns) return;
btns.removeClass('dark');
if (demo_settings.theme != 'clean' && demo_settings.theme != 'white') {
btns.addClass('dark');
}
}
// Load and apply settings
//
var panel_width = 260;
var demo_themes = [
{ name: 'default', title: 'Default', img: '/bundles/indigomain/images/demo/themes/default.png' },
{ name: 'asphalt', title: 'Asphalt', img: '/bundles/indigomain/images/demo/themes/asphalt.png' },
{ name: 'purple-hills', title: 'Purple Hills', img: '/bundles/indigomain/images/demo/themes/purple-hills.png' },
{ name: 'adminflare', title: 'Adminflare', img: '/bundles/indigomain/images/demo/themes/adminflare.png' },
{ name: 'dust', title: 'Dust', img: '/bundles/indigomain/images/demo/themes/dust.png' },
{ name: 'frost', title: 'Frost', img: '/bundles/indigomain/images/demo/themes/frost.png' },
{ name: 'fresh', title: 'Fresh', img: '/bundles/indigomain/images/demo/themes/fresh.png' },
{ name: 'silver', title: 'Silver', img: '/bundles/indigomain/images/demo/themes/silver.png' },
{ name: 'clean', title: 'Clean', img: '/bundles/indigomain/images/demo/themes/clean.png' },
{ name: 'white', title: 'White', img: '/bundles/indigomain/images/demo/themes/white.png' }
];
var demo_settings = loadDemoSettings();
if (demo_settings.fixed_navbar) {
document.body.className = document.body.className + ' main-navbar-fixed';
}
if (demo_settings.fixed_menu) {
document.body.className = document.body.className + ' main-menu-fixed';
}
if (demo_settings.rtl) {
document.body.className = document.body.className + ' right-to-left';
}
if (demo_settings.menu_right) {
document.body.className = document.body.className + ' main-menu-right';
}
activateTheme();
// Templates
//
var demo_styles = [
'#demo-themes {',
' display: table;',
' table-layout: fixed;',
' width: 100%;',
' border-bottom-left-radius: 5px;',
' overflow: hidden;',
'}',
'#demo-themes .demo-themes-row {',
' display: block;',
'}',
'#demo-themes .demo-theme {',
' display: block;',
' float: left;',
' text-align: center;',
' width: 50%;',
' padding: 25px 0;',
' color: #888;',
' position: relative;',
' overflow: hidden;',
'}',
'#demo-themes .demo-theme:hover {',
' color: #fff;',
'}',
'#demo-themes .theme-preview {',
' width: 100%;',
' position: absolute;',
' top: 0;',
' left: 0;',
' bottom: 0;',
' overflow: hidden !important;',
'}',
'#demo-themes .theme-preview img {',
' width: 100%;',
' position: absolute;',
' display: block;',
' top: 0;',
' left: 0;',
'}',
'#demo-themes .demo-theme .overlay {',
' background: #1d1d1d;',
' background: rgba(0,0,0,.8);',
' position: absolute;',
' top: 0;',
' bottom: 0;',
' left: -100%;',
' width: 100%;',
'}',
'#demo-themes .demo-theme span {',
' position: relative;',
' color: #fff;',
' color: rgba(255,255,255,0);',
'}',
'#demo-themes .demo-theme span,',
'#demo-themes .demo-theme .overlay {',
' -webkit-transition: all .3s;',
' -moz-transition: all .3s;',
' -ms-transition: all .3s;',
' -o-transition: all .3s;',
' transition: all .3s;',
'}',
'#demo-themes .demo-theme.active span,',
'#demo-themes .demo-theme:hover span {',
' color: #fff;',
' color: rgba(255,255,255,1);',
'}',
'#demo-themes .demo-theme.active .overlay,',
'#demo-themes .demo-theme:hover .overlay {',
' left: 0;',
'}',
'#demo-settings {',
' position: fixed;',
' right: -' + (panel_width + 10) + 'px;',
' width: ' + (panel_width + 10) + 'px;',
' top: 70px;',
' padding-right: 10px; ',
' background: #333;',
' border-radius: 5px;',
' -webkit-transition: all .3s;',
' -moz-transition: all .3s;',
' -ms-transition: all .3s;',
' -o-transition: all .3s;',
' transition: all .3s;',
' -webkit-touch-callout: none;',
' -webkit-user-select: none;',
' -khtml-user-select: none;',
' -moz-user-select: none;',
' -ms-user-select: none;',
' user-select: none;',
' z-index: 999998;',
'}',
'#demo-settings.open {',
' right: -10px;',
'}',
'#demo-settings > .header {',
' position: relative;',
' z-index: 100000;',
' line-height: 20px;',
' background: #444;',
' color: #fff;',
' font-size: 11px;',
' font-weight: 600;',
' padding: 10px 20px;',
' margin: 0;',
'}',
'#demo-settings > div {',
' position: relative;',
' z-index: 100000;',
' background: #282828;',
' border-bottom-right-radius: 5px;',
' border-bottom-left-radius: 5px;',
'}',
'#demo-settings-toggler {',
' font-size: 21px;',
' width: 50px;',
' height: 40px;',
' padding-right: 10px;',
' position: absolute;',
' left: -40px;',
' top: 0;',
' background: #444;',
' text-align: center;',
' line-height: 40px;',
' color: #fff;',
' border-radius: 5px;',
' z-index: 99999;',
' text-decoration: none !important;',
' -webkit-transition: color .3s;',
' -moz-transition: color .3s;',
' -ms-transition: color .3s;',
' -o-transition: color .3s;',
' transition: color .3s;',
'}',
'#demo-settings.open #demo-settings-toggler {',
' font-size: 16px;',
' color: #888;',
'}',
'#demo-settings.open #demo-settings-toggler:hover {',
' color: #fff;',
'}',
'#demo-settings.open #demo-settings-toggler:before {',
' content: "\\f00d";',
'}',
'#demo-settings-list {',
' padding: 0;',
' margin: 0;',
'}',
'#demo-settings-list li {',
' padding: 0;',
' margin: 0;',
' list-style: none;',
' position: relative;',
'}',
'#demo-settings-list li > span {',
' line-height: 20px;',
' color: #fff;',
' display: block;',
' padding: 12px 20px;',
' cursor: pointer;',
'}',
'#demo-settings-list li + li {',
' border-top: 1px solid #333;',
'}',
'#demo-settings .demo-checkbox {',
' position: absolute;',
' right: 20px;',
' top: 12px;',
'}',
'.right-to-left #demo-settings {',
' left: -270px;',
' right: auto;',
' padding-right: 0;',
' padding-left: 10px;',
'}',
'.right-to-left #demo-settings.open {',
' left: -10px;',
' right: auto;',
'}',
'.right-to-left #demo-settings-toggler {',
' padding-left: 10px;',
' padding-right: 0;',
' left: auto;',
' right: -40px;',
'}',
'.right-to-left #demo-settings .demo-checkbox {',
' right: auto;',
' left: 20px;',
'}'
];
var demo_template = [
'<div id="demo-settings">',
' <a href="#" id="demo-settings-toggler" class="fa fa-cogs"></a>',
' <h5 class="header">SETTINGS</h5>',
' <div>',
' <ul id="demo-settings-list">',
' <li class="clearfix">',
' <span>Fixed navbar</span>',
' <div class="demo-checkbox"><input type="checkbox" id="demo-fixed-navbar" class="demo-settings-switcher" data-class="switcher-sm"' + ((demo_settings.fixed_navbar) ? ' checked="checked"' : '' ) + '></div>',
' </li>',
' <li class="clearfix">',
' <span>Fixed main menu</span>',
' <div class="demo-checkbox"><input type="checkbox" id="demo-fixed-menu" class="demo-settings-switcher" data-class="switcher-sm"' + ((demo_settings.fixed_menu) ? ' checked="checked"' : '' ) + '></div>',
' </li>',
' <li class="clearfix">',
' <span>Right-to-left direction</span>',
' <div class="demo-checkbox"><input type="checkbox" id="demo-rtl" class="demo-settings-switcher" data-class="switcher-sm"' + ((demo_settings.rtl) ? ' checked="checked"' : '' ) + '></div>',
' </li>',
' <li class="clearfix">',
' <span>Main menu on the right</span>',
' <div class="demo-checkbox"><input type="checkbox" id="demo-menu-rigth" class="demo-settings-switcher" data-class="switcher-sm"' + ((demo_settings.menu_right) ? ' checked="checked"' : '' ) + '></div>',
' </li>',
' <li class="clearfix">',
' <span>Hide main menu</span>',
' <div class="demo-checkbox"><input type="checkbox" id="demo-no-menu" class="demo-settings-switcher" data-class="switcher-sm"></div>',
' </li>',
' </ul>',
' </div>',
' <h5 class="header">THEMES</h5>',
' <div id="demo-themes">',
getThemesTemplate(),
' </div>',
'</div>'
];
// Initialize
//
window.addEventListener("load", function () {
activateTheme($('#main-menu .btn-outline'));
$('head').append($('<style>\n' + demo_styles.join('\n') + '\n</style>'));
$('body').append($(demo_template.join('\n')));
// Activate theme
$('#demo-themes .demo-theme[data-theme="' + demo_settings.theme + '"]').addClass('active');
// Add callbacks
//
// Initialize switchers
$('.demo-settings-switcher').switcher({
theme: 'square',
on_state_content: '<span class="fa fa-check" style="font-size:11px;"></span>',
off_state_content: '<span class="fa fa-times" style="font-size:11px;"></span>'
});
// Demo panel toggle
$('#demo-settings-toggler').click(function () {
$('#demo-settings').toggleClass('open');
return false;
});
// Toggle switchers on label click
$('#demo-settings-list li > span').click(function () {
$(this).parents('li').find('.switcher').click();
});
// Fix/unfix main navbar
$('#demo-fixed-navbar').on($('html').hasClass('ie8') ? "propertychange" : "change", function () {
var uncheck_menu_chk = (! $(this).is(':checked') && $('#demo-fixed-menu').is(':checked')) ? true : false;
demo_settings.fixed_navbar = $(this).is(':checked');
if (uncheck_menu_chk) {
$('#demo-fixed-menu').switcher('off');
} else {
saveDemoSettings();
reloadPage();
}
});
// Fix/unfix main menu
$('#demo-fixed-menu').on($('html').hasClass('ie8') ? "propertychange" : "change", function () {
var check_navbar_chk = ($(this).is(':checked') && ! $('#demo-fixed-navbar').is(':checked')) ? true : false;
demo_settings.fixed_menu = $(this).is(':checked');
if (check_navbar_chk) {
$('#demo-fixed-navbar').switcher('on');
} else {
saveDemoSettings();
reloadPage();
}
});
// RTL
$('#demo-rtl').on($('html').hasClass('ie8') ? "propertychange" : "change", function () {
demo_settings.rtl = $(this).is(':checked');
saveDemoSettings();
reloadPage();
});
// Fix/unfix main menu
$('#demo-menu-rigth').on($('html').hasClass('ie8') ? "propertychange" : "change", function () {
demo_settings.menu_right = $(this).is(':checked');
saveDemoSettings();
reloadPage();
});
// Hide/show main menu
$('#demo-no-menu').on($('html').hasClass('ie8') ? "propertychange" : "change", function () {
if ($(this).is(':checked')) {
$('body').addClass('no-main-menu');
} else {
$('body').removeClass('no-main-menu');
}
});
// Change theme
$('#demo-themes .demo-theme').on('click', function () {
if ($(this).hasClass('active')) return;
$('#demo-themes .active').removeClass('active');
$(this).addClass('active');
demo_settings.theme = $(this).attr('data-theme');
saveDemoSettings();
activateTheme($('#main-menu .btn-outline'));
return false;
});
// Custom menu content demo
//
$('#menu-content-demo .close').click(function () {
var $p = $(this).parents('.menu-content');
$p.addClass('fadeOut');
setTimeout(function () {
$p.css({ height: $p.outerHeight(), overflow: 'hidden' }).animate({'padding-top': 0, height: $('#main-navbar').outerHeight()}, 500, function () {
$p.remove();
});
}, 300);
return false;
});
});
})();
| mit |
ChangFeng2015/leetcode | src/main/java/leetCode/designPattern/state/OpenningState.java | 350 | package leetCode.designPattern.state;
/**
* @Author:Dave
* @Description:
* @Date: 2017/9/12 17:22
*/
public class OpenningState extends LiftState{
public void open() {
System.out.println("the lift is opening!");
}
public void close() {
// supe
}
public void run() {
}
public void stop() {
}
}
| mit |
pushbullet/engineer | vendor/google.golang.org/genproto/googleapis/ads/googleads/v2/enums/tracking_code_type.pb.go | 6436 | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/ads/googleads/v2/enums/tracking_code_type.proto
package enums
import (
fmt "fmt"
math "math"
proto "github.com/golang/protobuf/proto"
_ "google.golang.org/genproto/googleapis/api/annotations"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
// The type of the generated tag snippets for tracking conversions.
type TrackingCodeTypeEnum_TrackingCodeType int32
const (
// Not specified.
TrackingCodeTypeEnum_UNSPECIFIED TrackingCodeTypeEnum_TrackingCodeType = 0
// Used for return value only. Represents value unknown in this version.
TrackingCodeTypeEnum_UNKNOWN TrackingCodeTypeEnum_TrackingCodeType = 1
// The snippet that is fired as a result of a website page loading.
TrackingCodeTypeEnum_WEBPAGE TrackingCodeTypeEnum_TrackingCodeType = 2
// The snippet contains a JavaScript function which fires the tag. This
// function is typically called from an onClick handler added to a link or
// button element on the page.
TrackingCodeTypeEnum_WEBPAGE_ONCLICK TrackingCodeTypeEnum_TrackingCodeType = 3
// For embedding on a mobile webpage. The snippet contains a JavaScript
// function which fires the tag.
TrackingCodeTypeEnum_CLICK_TO_CALL TrackingCodeTypeEnum_TrackingCodeType = 4
// The snippet that is used to replace the phone number on your website with
// a Google forwarding number for call tracking purposes.
TrackingCodeTypeEnum_WEBSITE_CALL TrackingCodeTypeEnum_TrackingCodeType = 5
)
var TrackingCodeTypeEnum_TrackingCodeType_name = map[int32]string{
0: "UNSPECIFIED",
1: "UNKNOWN",
2: "WEBPAGE",
3: "WEBPAGE_ONCLICK",
4: "CLICK_TO_CALL",
5: "WEBSITE_CALL",
}
var TrackingCodeTypeEnum_TrackingCodeType_value = map[string]int32{
"UNSPECIFIED": 0,
"UNKNOWN": 1,
"WEBPAGE": 2,
"WEBPAGE_ONCLICK": 3,
"CLICK_TO_CALL": 4,
"WEBSITE_CALL": 5,
}
func (x TrackingCodeTypeEnum_TrackingCodeType) String() string {
return proto.EnumName(TrackingCodeTypeEnum_TrackingCodeType_name, int32(x))
}
func (TrackingCodeTypeEnum_TrackingCodeType) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_bc3aa75f0cf51f59, []int{0, 0}
}
// Container for enum describing the type of the generated tag snippets for
// tracking conversions.
type TrackingCodeTypeEnum struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *TrackingCodeTypeEnum) Reset() { *m = TrackingCodeTypeEnum{} }
func (m *TrackingCodeTypeEnum) String() string { return proto.CompactTextString(m) }
func (*TrackingCodeTypeEnum) ProtoMessage() {}
func (*TrackingCodeTypeEnum) Descriptor() ([]byte, []int) {
return fileDescriptor_bc3aa75f0cf51f59, []int{0}
}
func (m *TrackingCodeTypeEnum) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_TrackingCodeTypeEnum.Unmarshal(m, b)
}
func (m *TrackingCodeTypeEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_TrackingCodeTypeEnum.Marshal(b, m, deterministic)
}
func (m *TrackingCodeTypeEnum) XXX_Merge(src proto.Message) {
xxx_messageInfo_TrackingCodeTypeEnum.Merge(m, src)
}
func (m *TrackingCodeTypeEnum) XXX_Size() int {
return xxx_messageInfo_TrackingCodeTypeEnum.Size(m)
}
func (m *TrackingCodeTypeEnum) XXX_DiscardUnknown() {
xxx_messageInfo_TrackingCodeTypeEnum.DiscardUnknown(m)
}
var xxx_messageInfo_TrackingCodeTypeEnum proto.InternalMessageInfo
func init() {
proto.RegisterEnum("google.ads.googleads.v2.enums.TrackingCodeTypeEnum_TrackingCodeType", TrackingCodeTypeEnum_TrackingCodeType_name, TrackingCodeTypeEnum_TrackingCodeType_value)
proto.RegisterType((*TrackingCodeTypeEnum)(nil), "google.ads.googleads.v2.enums.TrackingCodeTypeEnum")
}
func init() {
proto.RegisterFile("google/ads/googleads/v2/enums/tracking_code_type.proto", fileDescriptor_bc3aa75f0cf51f59)
}
var fileDescriptor_bc3aa75f0cf51f59 = []byte{
// 340 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x50, 0xd1, 0x4a, 0xf3, 0x30,
0x18, 0xfd, 0xdb, 0xfd, 0x2a, 0x64, 0xca, 0x6a, 0xd5, 0x1b, 0x71, 0x17, 0xdb, 0x03, 0xa4, 0x50,
0xc1, 0x8b, 0x78, 0xd5, 0xd6, 0x38, 0xca, 0x46, 0x57, 0x58, 0xb7, 0x81, 0x14, 0x4a, 0x5d, 0x42,
0x28, 0x6e, 0x49, 0x59, 0xba, 0xc9, 0x9e, 0xc2, 0x77, 0xf0, 0xd2, 0x47, 0xf1, 0x51, 0xf6, 0x14,
0xd2, 0x64, 0xdb, 0xc5, 0x40, 0x6f, 0xc2, 0xc9, 0xf7, 0x9d, 0x73, 0xf8, 0xce, 0x01, 0x0f, 0x4c,
0x08, 0x36, 0xa7, 0x4e, 0x4e, 0xa4, 0xa3, 0x61, 0x8d, 0xd6, 0xae, 0x43, 0xf9, 0x6a, 0x21, 0x9d,
0x6a, 0x99, 0xcf, 0xde, 0x0a, 0xce, 0xb2, 0x99, 0x20, 0x34, 0xab, 0x36, 0x25, 0x85, 0xe5, 0x52,
0x54, 0xc2, 0x6e, 0x6b, 0x32, 0xcc, 0x89, 0x84, 0x07, 0x1d, 0x5c, 0xbb, 0x50, 0xe9, 0x6e, 0xef,
0xf6, 0xb6, 0x65, 0xe1, 0xe4, 0x9c, 0x8b, 0x2a, 0xaf, 0x0a, 0xc1, 0xa5, 0x16, 0x77, 0x3f, 0x0c,
0x70, 0x9d, 0xec, 0x9c, 0x03, 0x41, 0x68, 0xb2, 0x29, 0x29, 0xe6, 0xab, 0x45, 0xf7, 0x1d, 0x58,
0xc7, 0x73, 0xbb, 0x05, 0x9a, 0xe3, 0x68, 0x14, 0xe3, 0x20, 0x7c, 0x0e, 0xf1, 0x93, 0xf5, 0xcf,
0x6e, 0x82, 0xb3, 0x71, 0xd4, 0x8f, 0x86, 0xd3, 0xc8, 0x32, 0xea, 0xcf, 0x14, 0xfb, 0xb1, 0xd7,
0xc3, 0x96, 0x69, 0x5f, 0x81, 0xd6, 0xee, 0x93, 0x0d, 0xa3, 0x60, 0x10, 0x06, 0x7d, 0xab, 0x61,
0x5f, 0x82, 0x0b, 0x05, 0xb3, 0x64, 0x98, 0x05, 0xde, 0x60, 0x60, 0xfd, 0xb7, 0x2d, 0x70, 0x3e,
0xc5, 0xfe, 0x28, 0x4c, 0xb0, 0x9e, 0x9c, 0xf8, 0x5b, 0x03, 0x74, 0x66, 0x62, 0x01, 0xff, 0x4c,
0xe5, 0xdf, 0x1c, 0x1f, 0x17, 0xd7, 0x71, 0x62, 0xe3, 0xc5, 0xdf, 0xe9, 0x98, 0x98, 0xe7, 0x9c,
0x41, 0xb1, 0x64, 0x0e, 0xa3, 0x5c, 0x85, 0xdd, 0xb7, 0x5a, 0x16, 0xf2, 0x97, 0x92, 0x1f, 0xd5,
0xfb, 0x69, 0x36, 0x7a, 0x9e, 0xf7, 0x65, 0xb6, 0x7b, 0xda, 0xca, 0x23, 0x12, 0x6a, 0x58, 0xa3,
0x89, 0x0b, 0xeb, 0x82, 0xe4, 0xf7, 0x7e, 0x9f, 0x7a, 0x44, 0xa6, 0x87, 0x7d, 0x3a, 0x71, 0x53,
0xb5, 0xdf, 0x9a, 0x1d, 0x3d, 0x44, 0xc8, 0x23, 0x12, 0xa1, 0x03, 0x03, 0xa1, 0x89, 0x8b, 0x90,
0xe2, 0xbc, 0x9e, 0xaa, 0xc3, 0xee, 0x7f, 0x02, 0x00, 0x00, 0xff, 0xff, 0xf1, 0xf8, 0x40, 0x53,
0xfc, 0x01, 0x00, 0x00,
}
| mit |
rs/rest-layer | schema/dict_example_test.go | 524 | package schema_test
import "github.com/rs/rest-layer/schema"
func ExampleDict() {
_ = schema.Schema{
Fields: schema.Fields{
"dict": schema.Field{
Validator: &schema.Dict{
// Limit dict keys to foo and bar keys only
KeysValidator: &schema.String{
Allowed: []string{"foo", "bar"},
},
// Allow either string or integer as dict value
Values: schema.Field{
Validator: &schema.AnyOf{
0: &schema.String{},
1: &schema.Integer{},
},
},
},
},
},
}
}
| mit |
allForMoney/SysMng | frontsrc/src/configs/index.js | 114 | // AJAX 请求超时时间,单位秒
export const REQUEST_TIMEOUT = 20;
export ERROR_CODE from './ERROR_CODE';
| mit |
robin-solutions/spree-refinery | app/decorators/refinery_user_decorator.rb | 657 | Refinery::User.class_eval do
class DestroyWithOrdersError < StandardError; end
include Spree::UserAddress
include Spree::UserPaymentSource
before_validation :copy_username_from_email
before_destroy :check_completed_orders
has_many :orders, class_name: 'Spree::Order'
def store_admin?
has_spree_role?('admin')
end
def add_spree_role(role_name)
role = Spree::Role.find_by(name: role_name)
self.spree_roles << role if role
end
private
def copy_username_from_email
self.username ||= self.email if self.email
end
def check_completed_orders
raise DestroyWithOrdersError if orders.complete.present?
end
end | mit |
Karasiq/scalajs-highcharts | src/main/scala/com/highcharts/config/PlotOptionsBubbleStatesHoverMarkerStates.scala | 2076 | /**
* Automatically generated file. Please do not edit.
* @author Highcharts Config Generator by Karasiq
* @see [[http://api.highcharts.com/highcharts]]
*/
package com.highcharts.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code>plotOptions-bubble-states-hover-marker-states</code>
*/
@js.annotation.ScalaJSDefined
class PlotOptionsBubbleStatesHoverMarkerStates extends com.highcharts.HighchartsGenericObject {
/**
* <p>The normal state of a single point marker. Currently only used
* for setting animation when returning to normal state from hover.</p>
*/
val normal: js.Any = js.undefined
/**
* <p>The hover state for a single point marker.</p>
*/
val hover: js.Any = js.undefined
/**
* <p>The appearance of the point marker when selected. In order to
* allow a point to be selected, set the <code>series.allowPointSelect</code>
* option to true.</p>
*/
val select: js.Any = js.undefined
}
object PlotOptionsBubbleStatesHoverMarkerStates {
/**
* @param normal <p>The normal state of a single point marker. Currently only used. for setting animation when returning to normal state from hover.</p>
* @param hover <p>The hover state for a single point marker.</p>
* @param select <p>The appearance of the point marker when selected. In order to. allow a point to be selected, set the <code>series.allowPointSelect</code>. option to true.</p>
*/
def apply(normal: js.UndefOr[js.Any] = js.undefined, hover: js.UndefOr[js.Any] = js.undefined, select: js.UndefOr[js.Any] = js.undefined): PlotOptionsBubbleStatesHoverMarkerStates = {
val normalOuter: js.Any = normal
val hoverOuter: js.Any = hover
val selectOuter: js.Any = select
com.highcharts.HighchartsGenericObject.toCleanObject(new PlotOptionsBubbleStatesHoverMarkerStates {
override val normal: js.Any = normalOuter
override val hover: js.Any = hoverOuter
override val select: js.Any = selectOuter
})
}
}
| mit |
bkahlert/seqan-research | raw/pmsb13/pmsb13-data-20130530/sources/130wu1dgzoqmxyu2/2013-04-11T10-12-03.179+0200/sandbox/my_sandbox/apps/first_app/first_app.cpp | 863 | #include <iostream>
#include <seqan/align.h>
#include <seqan/sequence.h>
#include <seqan/seq_io.h>
#include <seqan/index.h>
using namespace seqan;
using namespace std;
void assignmentIndex2(){
String<char> text = "TTATTAAGCGTATAGCCCTATAAATATAA";
StringSet<char> set;
String<char> pattern1 = "TA";
String<char> pattern2 = "GCG";
String<char> pattern3 = "GCC";
appendValue(set, pattern1);
appendValue(set, pattern2);
appendValue(set, pattern3);
Index<String<char>, IndexEsa<> > esaIndex(text);
Finder<Index<String<char>, IndexEsa<> > > esaFinder(esaIndex);
typedef Iterator<StringSet<char> >::Type TStringSetIterator;
for (TStringSetIterator it = begin(set); it != end(set); ++it){
clear(esaFinder);
while(find(esaFinder, getValue(it))){
std::cout<<position(esaFinder)<<std::endl;
}
}
}
int main(){
assignmentIndex2();
return 0;
}
| mit |
jeanklann/M3PlusMicrocontrollerSimulator | CircuitSimulator/Components/Digital/Gates/XnorGate.cs | 323 | namespace CircuitSimulator
{
public class XnorGate : Gate
{
public XnorGate(int inputQuantity = 2, string name = "Xnor Gate") : base(name, inputQuantity + 1)
{
}
protected internal override float Operation(Pin pin)
{
return Output.Xnor(pin);
}
}
} | mit |
tenpercent/gauss-invert | multiplication.cpp | 2986 | int simpleMatrixMultiply(double* const a, double* const b, double* const out, int p, int q, int r) {
//умножение двух блоков PxQ * QxR
int m, i, j;
double *pc, *pb, *pa;
double s10, s11, s00, s01;
for (m = 0; m < p * r; ++m) {
out[m] = 0.;
}
if ( !(p&1) ) {
if ( !(r&1) ) {
for (m = 0, pc = out; m < r; m += 2, pc += 2) {
for(i = 0, pb = b + m; i < p; i += 2) {
pa = a + i * q;
//s00=s01=s10=s11=0.;
s00 = 0.;
s01 = 0.;
s10 = 0.;
s11 = 0.;
for (j = 0; j < q; ++j, ++pa) {
s00 += pa[0] * pb[j * r];
s01 += pa[0] * pb[j * r + 1];
s10 += pa[q] * pb[j * r];
s11 += pa[q] * pb[j * r + 1];
}
pc[i * r] += s00;
pc[i * r + 1] += s01;
pc[(i + 1) * r] += s10;
pc[(i + 1) * r + 1] += s11;
}//for i
}//for m
} else {//p чётно, r нечётно
for (m = 0, pc = out; m < r - 1; m += 2, pc += 2) {
for(i = 0, pb = b + m; i < p; i += 2) {
pa = a + i * q;
//s00=s01=s10=s11=0.;
s00 = 0.;
s01 = 0.;
s10 = 0.;
s11 = 0.;
for (j = 0; j < q; j++, pa++){
s00+=pa[0]*pb[j*r];
s01+=pa[0]*pb[j*r+1];
s10+=pa[q]*pb[j*r];
s11+=pa[q]*pb[j*r+1];
}
pc[i*r]+=s00;
pc[i*r+1]+=s01;
pc[(i+1)*r]+=s10;
pc[(i+1)*r+1]+=s11;
}//for i
}//for m
for (i=0; i<p; i++){
for (j=0; j<q; j++){
out[i*r+r-1]+=a[i*q+j]*b[j*r+r-1];
}
}
}
}
else{
if(!(r&1)){//p нечетно, r четно
for (m=0, pc=out; m<r; m+=2, pc+=2){
for(i=0, pb=b+m; i<p-1; i+=2){
pa = a+i*q;
//s00=s01=s10=s11=0.;
s00=0.;
s10=0.;
s01=0.;
s11=0.;
for (j=0; j<q; j++, pa++){
s00+=pa[0]*pb[j*r];
s01+=pa[0]*pb[j*r+1];
s10+=pa[q]*pb[j*r];
s11+=pa[q]*pb[j*r+1];
}
pc[i*r]+=s00;
pc[i*r+1]+=s01;
pc[(i+1)*r]+=s10;
pc[(i+1)*r+1]+=s11;
}//for i
}//for m
for (i=0; i<r; i++){
for(j=0; j<q; j++){
out[(p-1)*r+i]+=a[(p-1)*q+j]*b[j*r+i];
}
}
}
else{//p нечётно, r нечётно
for (m=0, pc=out; m<r-1; m+=2, pc+=2){
for(i=0, pb=b+m; i<p-1; i+=2){
pa = a+i*q;
//s00=s01=s10=s11=0.;
s00=0.;
s01=0.;
s10=0.;
s11=0.;
for (j=0; j<q; j++, pa++){
s00+=pa[0]*pb[j*r];
s01+=pa[0]*pb[j*r+1];
s10+=pa[q]*pb[j*r];
s11+=pa[q]*pb[j*r+1];
}
pc[i*r]+=s00;
pc[i*r+1]+=s01;
pc[(i+1)*r]+=s10;
pc[(i+1)*r+1]+=s11;
}//for i
}//for m
for (i=0; i<r; i++){
for(j=0; j<q; j++){
out[(p-1)*r+i]+=a[(p-1)*q+j]*b[j*r+i];
}
}
for (i=0; i<p-1; i++){
for (j=0; j<q; j++){
out[i*r+r-1]+=a[i*q+j]*b[j*r+r-1];
}
}
}
}
return 0;
}
| mit |
brainless/intown | intown/apps/institutions/urls.py | 153 | from django.conf.urls import url
from .views import RegisterInstitutionView
urlpatterns = [
url(r'^register/$', RegisterInstitutionView.as_view())
]
| mit |
yun90/hrs | manage.py | 345 | import os
from app import create_app, db
import app.models
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
| mit |
project-sothis/project-sothis | app/shared/helpers/selectors/logAnalyzerSelectors.js | 349 | import _ from 'lodash'
export function getLogHeader (state) {
return state.logAnalyzer.data.header
}
export function getLogFilename (state) {
return state.logAnalyzer.data.filename
}
export function getLogEntries (state) {
const entries = state.logAnalyzer.data.entries
const entriesKey = _.keys(entries)
return [entries, entriesKey]
}
| mit |
ekoeppen/gdcl | nsof/nsof.go | 12418 | package nsof
import (
"fmt"
"io"
"strconv"
"unicode/utf16"
)
type Data []byte
type Writer interface {
WriteNSOF(*Data)
}
type Reader interface {
ReadNSOF(*Data, *ObjectStream) Object
}
type Object interface {
fmt.Stringer
Reader
Writer
}
type ObjectStream []Object
func (data Data) PeekXLong() int32 {
var r int32
r = int32(data[0])
if r > 254 {
r = ((int32(data[1])<<8+int32(data[2]))<<8+int32(data[3]))<<8 + int32(data[4])
}
return r
}
func (data *Data) SkipXLong() {
if (*data)[0] < 255 {
*data = (*data)[1:]
} else {
*data = (*data)[5:]
}
}
func (data *Data) DecodeXLong() int32 {
r := data.PeekXLong()
data.SkipXLong()
return r
}
func (data *Data) EncodeXLong(value int32) {
nsof := *data
if value < 255 && value >= 0 {
nsof = append(nsof, byte(value))
} else {
nsof = append(nsof, 255, byte(value>>24), byte(value>>16), byte(value>>8), byte(value))
}
*data = nsof
}
const (
IMMEDIATE = 0
CHARACTER = 1
UNICODECHARACTER = 2
BINARYOBJECT = 3
ARRAY = 4
PLAINARRAY = 5
FRAME = 6
SYMBOL = 7
STRING = 8
PRECEDENT = 9
NIL = 10
SMALLRECT = 11
LARGEBINARY = 12
)
type Character struct {
value uint16
}
func NewCharacter() *Character {
return &Character{value: 0}
}
func (character *Character) ReadNSOF(data *Data, objectStream *ObjectStream) Object {
value := data.PeekXLong()
if value&0xf == 6 {
character.value = uint16(value >> 4)
data.SkipXLong()
*objectStream = append(*objectStream, character)
} else {
character = nil
}
return character
}
func (character *Character) WriteNSOF(data *Data) {
*data = append(*data, IMMEDIATE)
data.EncodeXLong((int32(character.value) << 4) | 6)
}
func (character *Character) String() string {
return fmt.Sprintf("%c", character.value)
}
type True struct {
}
func (t *True) ReadNSOF(data *Data, objectStream *ObjectStream) Object {
value := data.PeekXLong()
if value == 0x1a {
data.SkipXLong()
*objectStream = append(*objectStream, t)
} else {
t = nil
}
return t
}
func (t *True) String() string {
return "true"
}
func (t *True) WriteNSOF(data *Data) {
*data = append(*data, IMMEDIATE)
data.EncodeXLong(0x1a)
}
type Nil struct {
}
func NewNil() *Nil {
return &Nil{}
}
func (n *Nil) ReadNSOF(data *Data, objectStream *ObjectStream) Object {
value := data.PeekXLong()
if value == 0x2 {
data.SkipXLong()
*objectStream = append(*objectStream, n)
} else {
n = nil
}
return n
}
func (n *Nil) String() string {
return "NIL"
}
func (n *Nil) WriteNSOF(data *Data) {
data.EncodeXLong(NIL)
}
type MagicPointer struct {
value int32
}
func (pointer *MagicPointer) ReadNSOF(data *Data, objectStream *ObjectStream) Object {
value := data.PeekXLong()
if value&0x3 == 3 {
pointer.value = (value >> 4) & 0xffff
data.SkipXLong()
*objectStream = append(*objectStream, pointer)
} else {
pointer = nil
}
return pointer
}
func (pointer *MagicPointer) String() string {
return fmt.Sprintf("@%d", pointer.value)
}
func (pointer *MagicPointer) WriteNSOF(data *Data) {
*data = append(*data, IMMEDIATE)
data.EncodeXLong((pointer.value << 4) | 6)
}
type Integer struct {
value int32
}
func NewInteger() *Integer {
return &Integer{}
}
func (integer *Integer) ReadNSOF(data *Data, objectStream *ObjectStream) Object {
value := data.PeekXLong()
if value&0x3 == 0 {
integer.value = value >> 2
data.SkipXLong()
*objectStream = append(*objectStream, integer)
} else {
integer = nil
}
return integer
}
func (integer *Integer) WriteNSOF(data *Data) {
*data = append(*data, IMMEDIATE)
data.EncodeXLong(integer.value << 2)
}
func (integer *Integer) String() string {
return strconv.Itoa(int(integer.value))
}
func NewImmediate(data *Data, objectStream *ObjectStream) Object {
var r Object
value := data.PeekXLong()
if value&0x3 == 0 {
r = &Integer{value >> 2}
} else if value&0x3 == 3 {
r = &MagicPointer{(value >> 4) & 0xffff}
} else if value&0xf == 6 {
r = &Character{uint16(value >> 4)}
} else if value == 0x1a {
r = &True{}
} else if value == 0x2 {
r = &Nil{}
}
if r != nil {
data.SkipXLong()
*objectStream = append(*objectStream, r)
} else {
panic(fmt.Sprintf("Parsing immediate %d not implemented. Data: %x\n", value, (*data)[:10]))
}
return r
}
type Slot struct {
key Object
value Object
}
type Frame struct {
slots []Slot
}
func NewFrame() *Frame {
return &Frame{}
}
func (frame *Frame) ReadNSOF(data *Data, objectStream *ObjectStream) Object {
*objectStream = append(*objectStream, frame)
elements := data.DecodeXLong()
frame.slots = make([]Slot, elements)
for i, _ := range frame.slots {
frame.slots[i] = Slot{data.DecodeObject(objectStream), nil}
}
for i, _ := range frame.slots {
frame.slots[i].value = data.DecodeObject(objectStream)
}
return frame
}
func (frame *Frame) WriteNSOF(data *Data) {
*data = append(*data, FRAME)
data.EncodeXLong(int32(len(frame.slots)))
for _, slot := range frame.slots {
slot.key.WriteNSOF(data)
}
for _, slot := range frame.slots {
slot.value.WriteNSOF(data)
}
}
func (frame *Frame) String() string {
return "{}"
}
func (frame *Frame) WriteTo(writer io.Writer) (n int64, err error) {
var n0 int
var err0 error
n0, err0 = writer.Write([]byte{'{'})
return int64(n0), err0
}
type Symbol struct {
value string
}
func (symbol *Symbol) ReadNSOF(data *Data, objectStream *ObjectStream) Object {
*objectStream = append(*objectStream, symbol)
length := data.DecodeXLong()
symbol.value = string((*data)[:length])
*data = (*data)[length:]
return symbol
}
func (symbol *Symbol) WriteNSOF(data *Data) {
*data = append(*data, SYMBOL)
data.EncodeXLong(int32(len(symbol.value)))
*data = append(*data, symbol.value...)
}
func (symbol *Symbol) String() string {
return symbol.value
}
func NewSymbol() *Symbol {
return &Symbol{}
}
type PlainArray struct {
objects []Object
}
func (plainArray *PlainArray) ReadNSOF(data *Data, objectStream *ObjectStream) Object {
*objectStream = append(*objectStream, plainArray)
for length := data.DecodeXLong(); length > 0; length-- {
plainArray.objects = append(plainArray.objects, data.DecodeObject(objectStream))
}
return plainArray
}
func (plainArray *PlainArray) WriteNSOF(data *Data) {
*data = append(*data, PLAINARRAY)
data.EncodeXLong(int32(len(plainArray.objects)))
for _, object := range plainArray.objects {
object.WriteNSOF(data)
}
}
func (plainArray *PlainArray) String() string {
return fmt.Sprintf("%v", plainArray.objects)
}
func NewPlainArray() *PlainArray {
return &PlainArray{}
}
type Precedent struct {
reference int32
}
func (precedent *Precedent) ReadNSOF(data *Data, objectStream *ObjectStream) Object {
precedent.reference = data.DecodeXLong()
return precedent
}
func (precedent *Precedent) WriteNSOF(data *Data) {
*data = append(*data, PRECEDENT)
data.EncodeXLong(precedent.reference)
}
func (precedent *Precedent) String() string {
return fmt.Sprintf("%d", precedent.reference)
}
func NewPrecedent() *Precedent {
return &Precedent{}
}
type String struct {
value []rune
}
func (str *String) ReadNSOF(data *Data, objectStream *ObjectStream) Object {
var i int32
*objectStream = append(*objectStream, str)
length := data.DecodeXLong()
chars := make([]uint16, length/2)
for i = 0; i < length/2; i++ {
chars[i] = uint16((*data)[i*2])*256 + uint16((*data)[i*2+1])
}
str.value = utf16.Decode(chars)
*data = (*data)[length:]
return str
}
func (str *String) WriteNSOF(data *Data) {
*data = append(*data, STRING)
data.EncodeXLong(int32(len(str.value) * 2))
s := utf16.Encode(str.value)
for i := 0; i < len(s); i++ {
*data = append(*data, byte(s[i]>>8), byte(s[i]))
}
}
func (str *String) String() string {
return string(str.value)
}
func NewString() *String {
return &String{}
}
type BinaryObject struct {
value []byte
class Object
}
func (binaryObject *BinaryObject) ReadNSOF(data *Data, objectStream *ObjectStream) Object {
*objectStream = append(*objectStream, binaryObject)
length := data.DecodeXLong()
binaryObject.class = data.DecodeObject(objectStream)
binaryObject.value = (*data)[:length]
*data = (*data)[length:]
return binaryObject
}
func (binaryObject *BinaryObject) WriteNSOF(data *Data) {
*data = append(*data, BINARYOBJECT)
data.EncodeXLong(int32(len(binaryObject.value)))
binaryObject.class.WriteNSOF(data)
*data = append(*data, binaryObject.value...)
}
func (binaryObject *BinaryObject) String() string {
return fmt.Sprintf("%x", binaryObject.value)
}
func NewBinaryObject() *BinaryObject {
return &BinaryObject{}
}
type UnicodeCharacter struct {
value uint16
}
func NewUnicodeCharacter() *UnicodeCharacter {
return &UnicodeCharacter{value: 0}
}
func (character *UnicodeCharacter) ReadNSOF(data *Data, objectStream *ObjectStream) Object {
character.value = uint16((*data)[0])<<8 + uint16((*data)[1])
*data = (*data)[2:]
return character
}
func (character *UnicodeCharacter) WriteNSOF(data *Data) {
*data = append(*data, UNICODECHARACTER)
*data = append(*data, byte(character.value>>8), byte(character.value))
}
func (character *UnicodeCharacter) String() string {
return fmt.Sprintf("%c", character.value)
}
type Array struct {
objects []Object
class Object
}
func NewArray() *Array {
return &Array{}
}
func (array *Array) ReadNSOF(data *Data, objectStream *ObjectStream) Object {
*objectStream = append(*objectStream, array)
length := int(data.DecodeXLong())
array.class = data.DecodeObject(objectStream)
for i := 0; i < length; i++ {
array.objects = append(array.objects, data.DecodeObject(objectStream))
}
return array
}
func (array *Array) WriteNSOF(data *Data) {
*data = append(*data, ARRAY)
data.EncodeXLong(int32(len(array.objects)))
array.class.WriteNSOF(data)
for _, object := range array.objects {
object.WriteNSOF(data)
}
}
func (array *Array) String() string {
return fmt.Sprintf("%v", array.objects)
}
type SmallRect struct {
left byte
top byte
right byte
bottom byte
}
func NewSmallRect() *SmallRect {
return &SmallRect{}
}
func (smallRect *SmallRect) ReadNSOF(data *Data, objectStream *ObjectStream) Object {
*objectStream = append(*objectStream, smallRect)
smallRect.top = (*data)[0]
smallRect.left = (*data)[1]
smallRect.bottom = (*data)[2]
smallRect.right = (*data)[3]
*data = (*data)[4:]
return smallRect
}
func (smallRect *SmallRect) WriteNSOF(data *Data) {
*data = append(*data, SMALLRECT, smallRect.top, smallRect.left, smallRect.bottom, smallRect.right)
}
func (smallRect *SmallRect) String() string {
return fmt.Sprintf("%d %d %d %d", smallRect.top, smallRect.left, smallRect.bottom, smallRect.right)
}
type LargeBinary struct {
class Object
compressed bool
compander string
companderParameters string
data []byte
}
func NewLargeBinary() *LargeBinary {
return &LargeBinary{}
}
func (largeBinary *LargeBinary) ReadNSOF(data *Data, objectStream *ObjectStream) Object {
return largeBinary
}
func (largeBinary *LargeBinary) WriteNSOF(data *Data) {
}
func (largeBinary *LargeBinary) String() string {
return fmt.Sprintf("<binary, %d bytes>", len(largeBinary.data))
}
func (data *Data) DecodeObject(stream *ObjectStream) Object {
var object Object
objtype := (*data)[0]
*data = (*data)[1:]
if objtype == IMMEDIATE {
object = NewImmediate(data, stream)
} else {
switch objtype {
case FRAME:
object = NewFrame()
case SYMBOL:
object = NewSymbol()
case PLAINARRAY:
object = NewPlainArray()
case PRECEDENT:
object = NewPrecedent()
case STRING:
object = NewString()
case NIL:
object = NewNil()
case BINARYOBJECT:
object = NewBinaryObject()
case CHARACTER:
object = NewCharacter()
case UNICODECHARACTER:
object = NewUnicodeCharacter()
case ARRAY:
object = NewArray()
case SMALLRECT:
object = NewSmallRect()
case LARGEBINARY:
object = NewLargeBinary()
default:
panic(fmt.Sprintf("Parsing type %d not implemented. Data: %x\n", objtype, (*data)[:10]))
}
object.ReadNSOF(data, stream)
}
return object
}
func (data Data) Factory() ObjectStream {
objects := make(ObjectStream, 0, 100)
for len(data) > 0 {
data.DecodeObject(&objects)
}
return objects
}
func (stream ObjectStream) Print() {
for i := 0; i < len(stream); i++ {
fmt.Printf("%d: %s\n", i, stream[i].(Object).String())
}
}
| mit |
apihackers/wapps | wapps/gallery/models.py | 7069 | from django.db import models
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore.fields import RichTextField
from wagtail.wagtailcore.models import Page, Orderable
from wagtail.wagtailadmin.edit_handlers import FieldPanel, MultiFieldPanel, InlinePanel
from wagtail.wagtailimages.edit_handlers import ImageChooserPanel
from wagtail.wagtailimages import get_image_model, get_image_model_string
from wagtail.wagtailsearch import index
from modelcluster.fields import ParentalKey
from modelcluster.tags import ClusterTaggableManager
from taggit.models import TaggedItemBase
from wapps.utils import get_image_url
ImageModel = get_image_model_string()
class Gallery(Page):
intro = RichTextField(_('Introduction'), blank=True,
help_text=_('A text to be displayed before albums'))
search_fields = Page.search_fields + [
index.SearchField('intro'),
]
feed_image = models.ForeignKey(
ImageModel,
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
@property
def children(self):
return self.get_children().live().specific()
def get_context(self, request):
# Get list of live Gallery pages that are descendants of this page
pages = Album.objects.live().descendant_of(self)
# Update template context
context = super(Gallery, self).get_context(request)
context['pages'] = pages
context['albums'] = pages
return context
class Meta:
verbose_name = _('Gallery')
type_icon = 'fa-picture-o'
subpage_types = [
'gallery.Album',
'gallery.ManualAlbum'
]
content_panels = [
FieldPanel('title', classname="full title"),
FieldPanel('intro', classname="full")
]
promote_panels = [
MultiFieldPanel(Page.promote_panels, _('SEO and metadata')),
ImageChooserPanel('feed_image'),
]
def __jsonld__(self, context):
request = context['request']
data = {
'@type': 'CollectionPage',
'@id': self.full_url,
'url': self.full_url,
'name': self.seo_title or self.title,
}
if self.first_published_at:
# Prevent pre wagtail 1.11 pages to fail
date_modified = self.last_published_at or self.first_published_at
data.update({
'datePublished': self.first_published_at.isoformat(),
'dateModified': date_modified.isoformat(),
})
if self.feed_image:
data['image'] = request.site.root_url + self.feed_image.get_rendition('original').url
data['hasPart'] = [album.__jsonld__(context) for album in self.children]
return data
class AlbumTag(TaggedItemBase):
content_object = ParentalKey(
'gallery.Album', related_name='tagged_items'
)
class Album(Page):
tags = ClusterTaggableManager(through=AlbumTag, blank=True)
intro = RichTextField(_('Introduction'), blank=True,
help_text=_('A text to be displayed before images'))
show_details = models.BooleanField(_('Display details'), default=True,
help_text=_('Display image title and details'))
ANIMATIONS_TYPES = [
('slide', _('Slide')),
('fade', _('Fade')),
]
animation = models.CharField(_('Animation'), max_length=8, choices=ANIMATIONS_TYPES, default='slide')
image = models.ForeignKey(
ImageModel,
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+',
verbose_name=_('Image'),
help_text=_('The image seen on gallery browser and when sharing this album')
)
@property
def gallery(self):
# Find closest ancestor which is a Gallery index
return self.get_ancestors().type(Gallery).specific().last()
def get_context(self, request):
context = super(Album, self).get_context(request)
context['images'] = self.get_images(request)
return context
def get_images(self, request):
tags = self.tags.all()
# Be compatible with swappable image model
model = get_image_model()
# Creating empty Queryset from Wagtail image model
return model.objects.filter(tags__in=tags).distinct()
class Meta:
verbose_name = _('Album')
content_panels = [
FieldPanel('title', classname="full title"),
FieldPanel('intro'),
FieldPanel('tags'),
MultiFieldPanel([
FieldPanel('show_details'),
FieldPanel('animation'),
], _('Options')),
]
promote_panels = [
MultiFieldPanel(Page.promote_panels, _('SEO and metadata')),
ImageChooserPanel('image'),
]
search_fields = Page.search_fields + [
index.SearchField('intro'),
]
# parent_page_types = []
subpage_types = []
type_icon = 'fa-picture-o'
def __jsonld__(self, context):
request = context['request']
data = {
'@type': 'ImageGallery',
'@id': self.full_url,
'url': self.full_url,
'name': self.seo_title or self.title,
'associatedMedia': []
}
if self.first_published_at:
# Prevent pre wagtail 1.11 pages to fail
date_modified = self.last_published_at or self.first_published_at
data.update({
'datePublished': self.first_published_at.isoformat(),
'dateModified': date_modified.isoformat(),
})
if self.image:
data['image'] = request.site.root_url + self.image.get_rendition('original').url
for image in self.get_images(request):
image = getattr(image, 'image', image)
media = {
'@type': 'ImageObject',
'name': image.title,
'contentUrl': get_image_url(image, 'original'),
'thumbnail': {
'@type': 'ImageObject',
'contentUrl': get_image_url(image, 'fill-300x300'),
'width': 300,
'height': 300,
}
}
if image.details:
media['description'] = image.details
data['associatedMedia'].append(media)
return data
class ManualAlbumImage(Orderable, models.Model):
page = ParentalKey('gallery.ManualAlbum', related_name='images')
image = models.ForeignKey(
ImageModel,
null=False,
blank=False,
on_delete=models.CASCADE,
related_name='+'
)
panels = [
ImageChooserPanel('image'),
]
class ManualAlbum(Album):
def get_images(self, request):
return [i.image for i in self.images.all()]
class Meta:
verbose_name = _('Manual album')
template = 'gallery/album.html'
content_panels = Album.content_panels + [
InlinePanel('images', label=_('Images')),
]
| mit |
Pomona/Pomona | tests/Pomona.UnitTests/TestResources/TestResourcePostForm.cs | 3133 | #region License
// Pomona is open source software released under the terms of the LICENSE specified in the
// project's repository, or alternatively at http://pomona.io/
#endregion
using System.Collections.Generic;
using Pomona.Common.Proxies;
namespace Pomona.UnitTests.TestResources
{
public class TestResourcePostForm : PostResourceBase, ITestResource
{
private static readonly PropertyWrapper<ITestResource, IList<ITestResource>> childrenPropWrapper =
new PropertyWrapper<ITestResource, IList<ITestResource>>("Children");
private static readonly PropertyWrapper<ITestResource, IDictionary<string, string>> dictionaryPropWrapper =
new PropertyWrapper<ITestResource, IDictionary<string, string>>("Dictionary");
private static readonly PropertyWrapper<ITestResource, IDictionary<string, object>> attributesPropWrapper =
new PropertyWrapper<ITestResource, IDictionary<string, object>>("Attributes");
private static readonly PropertyWrapper<ITestResource, ITestResource> friendPropWrapper =
new PropertyWrapper<ITestResource, ITestResource>("Friend");
private static readonly PropertyWrapper<ITestResource, int> idPropWrapper =
new PropertyWrapper<ITestResource, int>("Id");
private static readonly PropertyWrapper<ITestResource, string> infoPropWrapper =
new PropertyWrapper<ITestResource, string>("Info");
private static readonly PropertyWrapper<ITestResource, ITestResource> spousePropWrapper =
new PropertyWrapper<ITestResource, ITestResource>("Spouse");
private static readonly PropertyWrapper<ITestResource, ISet<ITestResource>> setPropWrapper =
new PropertyWrapper<ITestResource, ISet<ITestResource>>("Set");
public IDictionary<string, object> Attributes
{
get { return OnGet(attributesPropWrapper); }
set { OnSet(attributesPropWrapper, value); }
}
public IList<ITestResource> Children
{
get { return OnGet(childrenPropWrapper); }
set { OnSet(childrenPropWrapper, value); }
}
public IDictionary<string, string> Dictionary
{
get { return OnGet(dictionaryPropWrapper); }
set { OnSet(dictionaryPropWrapper, value); }
}
public ITestResource Friend
{
get { return OnGet(friendPropWrapper); }
set { OnSet(friendPropWrapper, value); }
}
public int Id
{
get { return OnGet(idPropWrapper); }
set { OnSet(idPropWrapper, value); }
}
public string Info
{
get { return OnGet(infoPropWrapper); }
set { OnSet(infoPropWrapper, value); }
}
public ISet<ITestResource> Set
{
get { return OnGet(setPropWrapper); }
set { OnSet(setPropWrapper, value); }
}
public ITestResource Spouse
{
get { return OnGet(spousePropWrapper); }
set { OnSet(spousePropWrapper, value); }
}
}
} | mit |
paulfitz/sheetsite | sheetsite/destination/csv_ss.py | 373 | import csv
def write_destination_csv(params, state):
workbook = state['workbook']
output_file = params['output_file']
for sheet in workbook.worksheets():
title = sheet.title
rows = sheet.get_all_values()
with open(output_file, 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(rows)
return True
| mit |
Bitblade-org/mgsim | cli/lookup.cpp | 1415 | #include "commands.h"
#include <sstream>
using namespace std;
bool DoCommand(vector<string>& args, cli_context& ctx)
{
bool match = false;
bool quit = false;
stringstream backup;
backup.copyfmt(cout);
for (const command_descriptor *p = &command_table[0]; p->prefix[0] != 0; ++p)
{
// First check that the start of the command matches.
size_t i;
match = true;
for (i = 0; p->prefix[i] != 0; ++i)
{
if (i >= args.size() || args[i] != p->prefix[i])
{
match = false;
break;
}
}
if (!match)
continue;
// We have a match. Check the number of arguments.
// here i points to the first non-command argument
size_t n_remaining_args = args.size() - i;
if ((int)n_remaining_args < p->min_args)
continue;
if (p->max_args >= 0 && (int)n_remaining_args > p->max_args)
continue;
// We have a match for both the command and the arguments.
// Get the command separately.
vector<string> command(args.begin(), args.begin() + i);
args.erase(args.begin(), args.begin() + i);
quit = p->handler(command, args, ctx);
cout << endl;
break;
}
cout.copyfmt(backup);
if (!match)
cout << "Unknown command." << endl;
return quit;
}
| mit |
axelpale/tresdb | client/components/Entry/CommentFormAdmin/index.js | 2068 | /* eslint-disable max-statements */
// Form for comment creation and edit
var ui = require('georap-ui');
var emitter = require('component-emitter');
var RemoveView = require('../Remove');
var ErrorView = require('../Error');
var template = require('./template.ejs');
var entryApi = tresdb.stores.entries;
module.exports = function (entry, comment) {
// Parameters
// entry
// entry object
// comment
// comment object. The comment must be created.
//
// Setup
var $mount = null;
var children = {};
var $elems = {};
var self = this;
emitter(self);
// Short alias
var entryId = entry._id;
self.bind = function ($mountEl) {
$mount = $mountEl;
$mount.html(template());
// Cancel button
$elems.cancel = $mount.find('.comment-form-cancel');
$elems.cancel.click(function () {
self.emit('exit');
});
// Init error view
$elems.error = $mount.find('.comment-form-error');
children.error = new ErrorView();
children.error.bind($elems.error);
// Comment deletion button and form
$elems.remove = $mount.find('.comment-remove-container');
$elems.removeOpen = $mount.find('.comment-remove-open');
$elems.removeOpen.click(function () {
ui.toggleHidden($elems.remove);
});
children.remove = new RemoveView({
info: 'This will delete the comment and its attachments if any.',
});
children.remove.bind($elems.remove);
children.remove.on('submit', function () {
entryApi.removeComment({
entryId: entryId,
commentId: comment.id,
}, function (err) {
if (err) {
children.remove.reset(); // hide progress
children.error.update(err.message);
return;
}
// Global location_entry_comment_removed will cause unbind
// and $mount removal.
});
});
};
self.unbind = function () {
if ($mount) {
ui.unbindAll(children);
children = {};
ui.offAll($elems);
$elems = {};
$mount.empty();
$mount = null;
}
};
};
| mit |
adrn/gary | gala/dynamics/mockstream/tests/test_df.py | 3276 | # Third-party
import astropy.units as u
import numpy as np
import pytest
# Custom
from ....integrate import DOPRI853Integrator
from ....potential import (Hamiltonian, HernquistPotential, MilkyWayPotential,
ConstantRotatingFrame)
from ....units import galactic
from ...core import PhaseSpacePosition
# Project
from ..df import StreaklineStreamDF, FardalStreamDF, LagrangeCloudStreamDF
_DF_CLASSES = [StreaklineStreamDF, FardalStreamDF, LagrangeCloudStreamDF]
_DF_KWARGS = [{}, {}, {'v_disp': 1*u.km/u.s}]
_TEST_POTENTIALS = [HernquistPotential(m=1e12, c=5, units=galactic),
MilkyWayPotential()]
@pytest.mark.parametrize('DF,DF_kwargs', zip(_DF_CLASSES, _DF_KWARGS))
@pytest.mark.parametrize('pot', _TEST_POTENTIALS)
def test_init_sample(DF, DF_kwargs, pot):
H = Hamiltonian(pot)
orbit = H.integrate_orbit([10., 0, 0, 0, 0.2, 0], dt=1., n_steps=100)
n_times = len(orbit.t)
# Different ways to initialize successfully:
df = DF(**DF_kwargs)
o = df.sample(orbit, 1e4*u.Msun)
assert len(o.x) == 2 * n_times
df = DF(lead=False, **DF_kwargs)
o = df.sample(orbit, 1e4*u.Msun)
assert len(o.x) == n_times
df = DF(trail=False, **DF_kwargs)
o = df.sample(orbit, 1e4*u.Msun)
assert len(o.x) == n_times
df1 = DF(random_state=np.random.RandomState(42), **DF_kwargs)
o1 = df1.sample(orbit, 1e4*u.Msun)
df2 = DF(random_state=np.random.RandomState(42), **DF_kwargs)
o2 = df2.sample(orbit, 1e4*u.Msun)
assert u.allclose(o1.xyz, o2.xyz)
assert u.allclose(o1.v_xyz, o2.v_xyz)
assert len(o1.x) == 2 * n_times
@pytest.mark.parametrize('DF,DF_kwargs', zip(_DF_CLASSES, _DF_KWARGS))
def test_expected_failure(DF, DF_kwargs):
# Expected failure:
with pytest.raises(ValueError):
DF(lead=False, trail=False, **DF_kwargs)
def test_rotating_frame():
DF = _DF_CLASSES[0]
H_static = Hamiltonian(_TEST_POTENTIALS[0])
w0 = PhaseSpacePosition(pos=[10., 0, 0]*u.kpc,
vel=[0, 220, 0.]*u.km/u.s,
frame=H_static.frame)
int_kwargs = dict(w0=w0, dt=1, n_steps=100,
Integrator=DOPRI853Integrator)
orbit_static = H_static.integrate_orbit(**int_kwargs)
rframe = ConstantRotatingFrame([0, 0, -40] * u.km/u.s/u.kpc,
units=galactic)
H_rotating = Hamiltonian(_TEST_POTENTIALS[0],
frame=rframe)
orbit_rotating = H_rotating.integrate_orbit(**int_kwargs)
_o = orbit_rotating.to_frame(H_static.frame)
assert u.allclose(_o.xyz, orbit_static.xyz, atol=1e-13*u.kpc)
assert u.allclose(_o.v_xyz, orbit_static.v_xyz, atol=1e-13*u.km/u.s)
df_static = DF(trail=False)
xvt_static = df_static.sample(orbit_static, 1e6*u.Msun)
df_rotating = DF(trail=False)
xvt_rotating = df_rotating.sample(orbit_rotating, 1e6*u.Msun)
xvt_rotating_static = xvt_rotating.to_frame(H_static.frame,
t=xvt_rotating.release_time)
assert u.allclose(xvt_static.xyz, xvt_rotating_static.xyz,
atol=1e-9*u.kpc)
assert u.allclose(xvt_static.v_xyz, xvt_rotating_static.v_xyz,
atol=1e-9*u.kpc/u.Myr)
| mit |
Papipo/locomotivecms-search | lib/locomotive/search/engine.rb | 678 | module Locomotive::Search
class Engine < ::Rails::Engine
initializer "locomotive.search.concerns", before: "locomotive.content_types" do |app|
require "locomotive/search/content_type_reindexer"
require "locomotive/search/concerns"
app.config.autoload_paths += %W(#{config.root}/app/services/locomotive)
Locomotive::PartialsCell.add_template(:custom_fields_form, "searchable")
Locomotive::PartialsCell.add_template(:page_form, "searchable")
end
initializer "locomotive.search.assets.precompile", group: :all do |app|
app.config.assets.precompile += ['locomotive/search_bar.css', 'locomotive/search_bar.js']
end
end
end | mit |
KlusterKite/KlusterKite | Docs/Doxygen/html/dir_44a57085ea6129e28033f3819d38a708.js | 632 | var dir_44a57085ea6129e28033f3819d38a708 =
[
[ "Installer.cs", "_kluster_kite_8_security_2_kluster_kite_8_security_8_session_redis_2_installer_8cs.html", [
[ "Installer", "class_kluster_kite_1_1_security_1_1_session_redis_1_1_installer.html", "class_kluster_kite_1_1_security_1_1_session_redis_1_1_installer" ]
] ],
[ "RedisSessionTokenManager.cs", "_redis_session_token_manager_8cs.html", [
[ "RedisSessionTokenManager", "class_kluster_kite_1_1_security_1_1_session_redis_1_1_redis_session_token_manager.html", "class_kluster_kite_1_1_security_1_1_session_redis_1_1_redis_session_token_manager" ]
] ]
]; | mit |
BathHacked/wheelmap-stats | grab_counts.php | 1125 | <?php
//This should be run on cron.
include_once('config.php');
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$timeNow = gmdate("Y-m-d H:i:s");
$saved = 0;
for( $categoryId = 0; $categoryId <= 12; $categoryId++ ){
foreach( ['yes','limited','no','unknown'] as $wheelchair_filter ){
$categoriesUrlFragment = ($categoryId >= 1) ? "categories/".$categoryId."/" : "";
$json = json_decode(file_get_contents("https://wheelmap.org/api/".$categoriesUrlFragment."nodes?api_key=$wheelmap_api_key&bbox=-2.413769,51.363902,-2.310473,51.415048&wheelchair=$wheelchair_filter"), true);
$item_count = $json['meta']['item_count_total'];
$success = $mysqli->query("INSERT INTO venue_counts (`category`,`wheelchair`,`time`,`count`) VALUES ('$categoryId','$wheelchair_filter','$timeNow','$item_count')");
if( !$success ){
die( $mysqli->error );
}
else{
$saved++;
}
}
}
echo "Saved $saved rows to DB."; | mit |
rainforestapp/circlemator | spec/spec_helper.rb | 1009 | # frozen_string_literal: true
require 'vcr'
require 'simplecov'
require 'simplecov-lcov'
SimpleCov::Formatter::LcovFormatter.config.report_with_single_file = true
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new(
[SimpleCov::Formatter::LcovFormatter, SimpleCov::Formatter::HTMLFormatter]
)
SimpleCov.start do
add_filter(%r{/spec/})
end
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.filter_run :focus
config.run_all_when_everything_filtered = true
config.disable_monkey_patching!
config.warnings = true
if config.files_to_run.one?
config.default_formatter = 'doc'
end
config.profile_examples = 10
config.order = :random
Kernel.srand config.seed
end
VCR.configure do |config|
config.cassette_library_dir = 'fixtures/vcr_cassettes'
config.hook_into :webmock
end
| mit |
ZhouHengYi/https---github.com-ZhouHengYi-RenRen_react-starter-kit | src/components/Banner/USA/Banner/Banner.js | 6335 | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { PropTypes } from 'react';
import styles from './Banner.less';
import withStyles from '../../../../decorators/withStyles';
import Link from '../../../../utils/Link';
import $ from 'jquery';
var CSlider = require('react-slick');
var Select = require('rc-select');
var Option = Select.Option;
@withStyles(styles)
class Banner {
render() {
var settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
autoplay: false,
};
return (
<section className="banner">
<div id="da-slider" className="slideshow da-slider">
<CSlider {...settings}>
<div className="da-slide usa-banner1">
<h2>
<img src="http://new.rrliuxue.com/WebResources/Default/images/banner/USA/statue-of-liberty.png" /></h2>
<div className="da-img">
<img src="http://new.rrliuxue.com/WebResources/Default/images/banner/USA/text.png" />
</div>
</div>
<div className="da-slide usa-banner1">
<h2>
<img src="http://new.rrliuxue.com/WebResources/Default/images/banner/USA/statue-of-liberty.png" /></h2>
<div className="da-img">
<img src="http://new.rrliuxue.com/WebResources/Default/images/banner/USA/text.png" />
</div>
</div>
<div className="da-slide usa-banner1">
<h2>
<img src="http://new.rrliuxue.com/WebResources/Default/images/banner/USA/statue-of-liberty.png" /></h2>
<div className="da-img">
<img src="http://new.rrliuxue.com/WebResources/Default/images/banner/USA/text.png" />
</div>
</div>
</CSlider>
<div className="bgShadow"></div>
</div>
<div className="plan-box">
<form id="planForm" method="post" action="#" autocomplete="off">
<h1>免费获取美国留学方案</h1>
<input type="hidden" id="planCountry" data-country="USA" />
<ul>
<li>
<Select value="计划出国时间" style={{width:270,height:45}} optionFilterProp="desc" renderDropdownToBody={true} onChange={this.handleChange}>
<Option value="计划出国时间" desc="计划出国时间">计划出国时间</Option>
<Option value="2015" desc="2015 ">2015</Option>
<Option value="2014" desc="2014">2014</Option>
<Option value="2013" desc="2013">2013</Option>
</Select>
</li>
<li>
<Select value="目前就读年级" style={{width:270,height:45}} optionFilterProp="desc" renderDropdownToBody={true} onChange={this.handleChange}>
<Option value="目前就读年级" desc="目前就读年级">目前就读年级</Option>
<Option selected="selected" value="本科大四">本科大四</Option>
<Option value="本科大三">本科大三</Option>
<Option value="本科大二">本科大二</Option>
<Option value="本科大一">本科大一</Option>
<Option value="大专大三">大专大三</Option>
<Option value="大专大二">大专大二</Option>
<Option value="大专大一">大专大一</Option>
<Option value="高三">高三</Option>
<Option value="高二">高二</Option>
<Option value="高一">高一</Option>
<Option value="初三">初三</Option>
<Option value="初二">初二</Option>
<Option value="初一">初一</Option>
<Option value="硕士毕业已工作">硕士毕业已工作</Option>
<Option value="硕士在读">硕士在读</Option>
<Option value="本科毕业已工作">本科毕业已工作</Option>
<Option value="大专毕业三年以上">大专毕业三年以上</Option>
<Option value="大专毕业三年以下">大专毕业三年以下</Option>
<Option value="高三毕业已工作">高三毕业已工作</Option>
</Select>
</li>
<li>
<button className="btn-plan" type="submit">获取留学方案</button>
</li>
</ul>
<div className="bottom">
<p>人人留学为什么免费? </p>
<div className="message">
已有<span>2036</span>位小伙伴加入<br />
人人留学, <a href="/register.aspx">我要加入</a>
</div>
</div>
</form>
</div>
</section>
);
}
componentDidMount() {
$(".bgShadow").hide();
}
}
export default Banner;
/**
* Created by XiaoKangZheng on 2015/7/28.
*/
| mit |
pranavmaneriker/template-creator | db/migrate/20141125165935_add_resume_filename_to_resume_relations.rb | 198 | class AddResumeFilenameToResumeRelations < ActiveRecord::Migration
def change
add_column :resume_relations, :resume_filename, :string
add_index :resume_relations, :resume_filename
end
end
| mit |
dispyfree/xhstt | constraint/ClusterBusyTimesConstraint.cpp | 812 | /*
* File: ClusterBusyTimesConstraint.cpp
*
*/
#include "ClusterBusyTimesConstraint.h"
#include "Instance.h"
#include "CostFunction.h"
#include "ObjectCreation.h"
using namespace khe;
using cbtc = ClusterBusyTimesConstraint;
cbtc::ClusterBusyTimesConstraint(Instance inst, const std::string &id, const std::string &name,
bool required, int weight, const CostFunction &cf, int min, int max){
if(!KheClusterBusyTimesConstraintMake(inst, Util::sTc(id), Util::sTc(name), required,
weight, cf, min, max, &constr))
throw ObjectCreation("Unable to create ClusterBusyTimesConstraint");
}
int cbtc::getMinimum() const{
return KheClusterBusyTimesConstraintMinimum(constr);
}
int cbtc::getMaximum() const{
return KheClusterBusyTimesConstraintMaximum(constr);
}
| mit |
ArekkuusuJerii/Solar | src/main/java/arekkuusu/implom/common/theorem/ModTheorems.java | 894 | /*
* Arekkuusu / Improbable plot machine. 2018
*
* This project is licensed under the MIT.
* The source code is available on github:
* https://github.com/ArekkuusuJerii/Improbable-plot-machine
*/
package arekkuusu.implom.common.theorem;
import arekkuusu.implom.api.research.Theorem;
import arekkuusu.implom.common.lib.LibMod;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.RegistryBuilder;
/**
* Created by <Arekkuusu> on 19/03/2018.
* It's distributed as part of Improbable plot machine.
*/
public final class ModTheorems {
public static final ForgeRegistry<Theorem> REGISTRY = (ForgeRegistry<Theorem>) new RegistryBuilder<Theorem>()
.setName(new ResourceLocation(LibMod.MOD_ID, "theorem"))
.setType(Theorem.class)
.setIDRange(0, 255)
.create();
public static void init() {
}
}
| mit |
RononDex/Sun.Plasma | Sun.Plasma/Sun.Plasma/Settings.xaml.cs | 1563 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Sun.Plasma
{
/// <summary>
/// Interaction logic for Settings.xaml
/// </summary>
public partial class Settings : Window
{
FrameworkElement CtlMoveable;
public Settings()
{
this.Loaded += OnLoaded;
InitializeComponent();
this.DataContext = new Sun.Plasma.ViewModel.ViewModelSettings();
}
public void OnLoaded(object sender, EventArgs e)
{
// Enable moving the window when clicking on the control CtlMoveable
this.CtlMoveable = (FrameworkElement)this.Template.FindName("CtlMoveable", this);
if (null != this.CtlMoveable)
{
this.CtlMoveable.MouseLeftButtonDown += new MouseButtonEventHandler(OnMoveableClick);
}
// Make this window resizable
ResizableWindow.MakeWindowResizable(this);
}
public void OnMoveableClick(object sender, MouseButtonEventArgs e)
{
// Make window moveable when clicking on it
if (e.LeftButton == MouseButtonState.Pressed)
DragMove();
}
}
}
| mit |
QoboLtd/cakephp-search | webroot/js/exporter.js | 2083 | ;(function ($, document, window) {
'use strict';
/**
* Exporter plugin.
*/
function Exporter(element, options)
{
this.element = element;
this.options = options;
var pages = Math.ceil(this.options.count / this.options.limit);
this.init(1, pages);
}
Exporter.prototype = {
/**
* Initialize method
*
* @return {undefined}
*/
init: function (page, pages) {
var that = this;
$.ajax({
url: this.options.url,
type: 'get',
data: {
page: page,
limit: this.options.limit
},
dataType: 'json',
contentType: 'application/json',
headers: {
'Authorization': 'Bearer ' + this.options.token
},
success: function (data) {
if (data.success) {
// next page
page++;
if (page <= pages) {
$.event.trigger({
type: "progress.search.export",
percent: (page / pages) * 100
});
that.init(page, pages);
} else {
$.event.trigger({
type: "completed.search.export",
link: data.data.path
});
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
}
};
$.fn.exporter = function (options) {
return this.each(function () {
new Exporter(this, options);
});
};
})(jQuery, document, window);
| mit |
lanyudhy/Halite-II | environment/networking/Networking.cpp | 25652 | #include "Networking.hpp"
#include "BotInputError.hpp"
#include <exception>
#include <sstream>
#include <thread>
#include <core/hlt.hpp>
std::mutex coutMutex;
std::string serializeMapSize(const hlt::Map& map) {
std::string returnString = "";
std::ostringstream oss;
oss << map.map_width << ' ' << map.map_height << ' ';
returnString = oss.str();
return returnString;
}
std::string Networking::serialize_map(const hlt::Map& map) {
std::string returnString = "";
std::ostringstream oss;
// Encode individual ships
oss << ' ' << player_count();
oss << std::setprecision(SERIALIZATION_PRECISION);
oss << std::fixed;
for (hlt::PlayerId player_id = 0; player_id < player_count();
player_id++) {
oss << ' ' << (int) player_id;
auto num_ships = map.ships[player_id].size();
oss << ' ' << num_ships;
auto player_ships = std::vector<std::pair<hlt::EntityIndex, hlt::Ship>>(
map.ships[player_id].begin(),
map.ships[player_id].end());
std::sort(player_ships.begin(), player_ships.end(),
[](const std::pair<hlt::EntityIndex, hlt::Ship> s1,
const std::pair<hlt::EntityIndex, hlt::Ship> s2) -> bool {
return s1.first < s2.first;
});
for (const auto& pair : player_ships) {
const auto& ship = pair.second;
oss << ' ' << pair.first;
oss << ' ' << ship.location.pos_x;
oss << ' ' << ship.location.pos_y;
oss << ' ' << ship.health;
oss << ' ' << ship.velocity.vel_x;
oss << ' ' << ship.velocity.vel_y;
oss << ' ' << static_cast<int>(ship.docking_status);
oss << ' ' << static_cast<int>(ship.docked_planet);
oss << ' ' << ship.docking_progress;
oss << ' ' << ship.weapon_cooldown;
}
}
auto num_planets = std::count_if(
map.planets.begin(),
map.planets.end(),
[](const hlt::Planet& planet) -> bool {
return planet.is_alive();
}
);
oss << ' ' << num_planets;
for (hlt::EntityIndex planet_id = 0; planet_id < map.planets.size();
planet_id++) {
const auto& planet = map.planets[planet_id];
if (!planet.is_alive()) continue;
oss << ' ' << planet_id;
oss << ' ' << planet.location.pos_x;
oss << ' ' << planet.location.pos_y;
oss << ' ' << planet.health;
oss << ' ' << planet.radius;
oss << ' ' << planet.docking_spots;
oss << ' ' << planet.current_production;
oss << ' ' << planet.remaining_production;
if (planet.owned) {
oss << ' ' << 1 << ' ' << (int) planet.owner;
}
else {
oss << ' ' << 0 << ' ' << 0;
}
oss << ' ' << planet.docked_ships.size();
for (const auto docked : planet.docked_ships) {
oss << ' ' << docked;
}
}
returnString = oss.str();
return returnString;
}
auto is_valid_move_character(const char& c) -> bool {
return (c >= '0' && c <= '9')
|| c == ' '
|| c == '-'
|| c == 't'
|| c == 'u'
|| c == 'd'
|| c == 'q';
}
auto eject_bot(std::string message) -> std::string {
if (!quiet_output) {
std::lock_guard<std::mutex> guard(coutMutex);
std::cout << message;
}
return message;
}
void Networking::deserialize_move_set(hlt::PlayerId player_tag,
std::string& inputString,
const hlt::Map& m,
hlt::PlayerMoveQueue& moves) {
const auto position = std::find_if(
inputString.begin(), inputString.end(),
[](const char& c) -> bool {
return !is_valid_move_character(c);
});
if (position != inputString.end()) {
const auto index = std::distance(inputString.begin(), position);
std::string message("Received invalid character '");
message += inputString;
message += *position;
message += "'.";
throw BotInputError(player_tag, inputString, message, index);
}
std::stringstream iss(inputString);
hlt::Move move;
// Keep track of how many queued commands each ship has
hlt::entity_map<int> queue_depth;
char command;
while (iss >> command) {
switch (command) {
case 't': {
move.type = hlt::MoveType::Thrust;
iss >> move.shipId;
iss >> move.move.thrust.thrust;
iss >> move.move.thrust.angle;
const auto thrust = move.move.thrust.thrust;
const auto max_accel = hlt::GameConstants::get().MAX_ACCELERATION;
if (thrust > max_accel) {
std::stringstream message;
message << "Invalid thrust " << move.move.thrust.thrust
<< " for ship " << move.shipId
<< " (maximum is " << max_accel << ").";
throw BotInputError(player_tag, inputString, message.str(), iss.tellg());
}
break;
}
case 'd': {
move.type = hlt::MoveType::Dock;
iss >> move.shipId;
iss >> move.move.dock_to;
break;
}
case 'u': {
move.type = hlt::MoveType::Undock;
iss >> move.shipId;
break;
}
case 'q': {
if (is_single_player()) {
// allow early abort in single-player mode
// (used for evaluating partial games for tutorial mode)
throw hlt::GameAbort { 0 };
}
// fall through to default
}
default:
std::stringstream message;
message << "Unknown command " << command << " for ship " << move.shipId;
throw BotInputError(player_tag, inputString, message.str(), iss.tellg());
}
if (queue_depth.count(move.shipId) == 0) {
queue_depth[move.shipId] = 0;
}
auto queue_index = queue_depth.at(move.shipId);
if (queue_index < hlt::MAX_QUEUED_MOVES) {
moves.at(queue_index)[move.shipId] = move;
queue_depth.at(move.shipId)++;
} else {
std::stringstream message;
message << "Tried to queue too many commands for ship " << move.shipId;
throw BotInputError(player_tag, inputString, message.str(), iss.tellg());
}
move = {};
}
}
void Networking::send_string(hlt::PlayerId player_tag,
std::string& sendString) {
// End message with newline character
sendString += '\n';
#ifdef _WIN32
WinConnection connection = connections[player_tag];
DWORD charsWritten;
bool success;
success = WriteFile(connection.write, sendString.c_str(), sendString.length(), &charsWritten, NULL);
if(!success || charsWritten == 0) {
if(!quiet_output) std::cout << "Problem writing to pipe\n";
throw 1;
}
#else
UniConnection connection = connections[player_tag];
ssize_t charsWritten =
write(connection.write, sendString.c_str(), sendString.length());
if (charsWritten == -1) {
std::stringstream error_msg;
if (errno == EWOULDBLOCK || errno == EAGAIN) {
error_msg
<< "Could not send map to bot: blocked writing to pipe.\n"
<< "This usually happens if the bot is not reading STDIN,\n"
<< "or is accidentally putting all commands on newlines.";
}
else {
error_msg
<< "Encountered an error while writing to pipe: " << errno;
}
throw BotInputError(player_tag, "", error_msg.str(), 0);
}
else if (charsWritten < sendString.length()) {
if (!quiet_output) std::cout << "Problem writing to pipe\n";
throw 1;
}
#endif
}
std::string Networking::get_string(hlt::PlayerId player_tag,
unsigned int timeout_millis) {
std::string newString;
int timeoutMillisRemaining = timeout_millis;
std::chrono::high_resolution_clock::time_point
tp = std::chrono::high_resolution_clock::now();
#ifdef _WIN32
WinConnection connection = connections[player_tag];
DWORD charsRead;
bool success;
char buffer;
// Keep reading char by char until a newline
while(true) {
timeoutMillisRemaining = timeout_millis - std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - tp).count();
if(timeoutMillisRemaining < 0) throw newString;
// Check to see that there are bytes in the pipe before reading
// Throw error if no bytes in alloted time
// Check for bytes before sampling clock, because reduces latency (vast majority the pipe is alread full)
DWORD bytesAvailable = 0;
PeekNamedPipe(connection.read, NULL, 0, NULL, &bytesAvailable, NULL);
if(bytesAvailable < 1) {
std::chrono::high_resolution_clock::time_point initialTime = std::chrono::high_resolution_clock::now();
while (bytesAvailable < 1) {
if(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - initialTime).count() > timeoutMillisRemaining) throw newString;
PeekNamedPipe(connection.read, NULL, 0, NULL, &bytesAvailable, NULL);
}
}
success = ReadFile(connection.read, &buffer, 1, &charsRead, NULL);
if(!success || charsRead < 1) {
if(!quiet_output) {
std::string errorMessage = "Bot #" + std::to_string(player_tag) + " timed out or errored (Windows)\n";
std::lock_guard<std::mutex> guard(coutMutex);
std::cout << errorMessage;
}
throw newString;
}
if(buffer == '\n') break;
else newString += buffer;
}
#else
UniConnection connection = connections[player_tag];
fd_set set;
FD_ZERO(&set); /* clear the set */
if (connection.read > FD_SETSIZE) assert(false);
FD_SET(connection.read, &set); /* add our file descriptor to the set */
char buffer;
// Keep reading char by char until a newline
while (true) {
// Check if there are bytes in the pipe
timeoutMillisRemaining = timeout_millis
- std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - tp).count();
if (timeoutMillisRemaining < 0) throw newString;
struct timeval timeout;
timeout.tv_sec = timeoutMillisRemaining / 1000.0;
timeout.tv_usec = (timeoutMillisRemaining % 1000) * 1000;
int selectionResult =
select(connection.read + 1, &set, NULL, NULL, &timeout);
if (selectionResult > 0) {
const size_t bytes_read = read(connection.read, &buffer, 1);
if (bytes_read != 1) {
throw BotInputError(player_tag, newString, std::string(
"Panic: select() was positive but read() for 1 byte did not return 1."), 0);
}
if (buffer == '\n') break;
else newString += buffer;
}
else {
std::stringstream error_msg;
error_msg << "Timeout reading commands for bot; select() result: "
<< selectionResult
<< " (max time: " << timeout_millis << " milliseconds).";
throw BotInputError(player_tag, newString, error_msg.str(), 0);
}
}
#endif
// Python turns \n into \r\n
if (newString.back() == '\r') newString.pop_back();
return newString;
}
std::string Networking::read_trailing_input(hlt::PlayerId player_tag, long max_lines) {
std::string error_string = "";
for(int line = 0; line < max_lines; line++) {
try {
error_string += get_string(player_tag, 0);
} catch (const BotInputError& exc) {
break;
} catch (const std::string& s) {
error_string += s;
break;
} catch (...) {
break;
}
}
return error_string;
}
void Networking::launch_bot(std::string command) {
#ifdef _WIN32
command = "/C " + command;
WinConnection parentConnection, childConnection;
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// Child stdout pipe
if(!CreatePipe(&parentConnection.read, &childConnection.write, &saAttr, 0)) {
if(!quiet_output) std::cout << "Could not create pipe\n";
throw 1;
}
if(!SetHandleInformation(parentConnection.read, HANDLE_FLAG_INHERIT, 0)) throw 1;
// Child stdin pipe
if(!CreatePipe(&childConnection.read, &parentConnection.write, &saAttr, 0)) {
if(!quiet_output) std::cout << "Could not create pipe\n";
throw 1;
}
if(!SetHandleInformation(parentConnection.write, HANDLE_FLAG_INHERIT, 0)) throw 1;
// MAKE SURE THIS MEMORY IS ERASED
PROCESS_INFORMATION piProcInfo;
ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
STARTUPINFO siStartInfo;
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = childConnection.write;
siStartInfo.hStdOutput = childConnection.write;
siStartInfo.hStdInput = childConnection.read;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
// C:/xampp/htdocs/Halite/Halite/Debug/ExampleBot.exe
// C:/Users/Michael/Anaconda3/python.exe
// C:/Program Files/Java/jre7/bin/java.exe -cp C:/xampp/htdocs/Halite/AIResources/Java MyBot
bool success = CreateProcess(
"C:\\windows\\system32\\cmd.exe",
LPSTR(command.c_str()), // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
0, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo
); // receives PROCESS_INFORMATION
if(!success) {
if(!quiet_output) std::cout << "Could not start process\n";
throw 1;
}
else {
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
processes.push_back(piProcInfo.hProcess);
connections.push_back(parentConnection);
}
#else
if (!quiet_output) std::cout << command << std::endl;
pid_t pid;
int writePipe[2];
int readPipe[2];
if (pipe(writePipe)) {
if (!quiet_output) std::cout << "Error creating pipe\n";
throw 1;
}
if (pipe(readPipe)) {
if (!quiet_output) std::cout << "Error creating pipe\n";
throw 1;
}
// Make the write pipe nonblocking
fcntl(writePipe[1], F_SETFL, O_NONBLOCK);
pid_t ppid_before_fork = getpid();
// Fork a child process
pid = fork();
if (pid == 0) { // This is the child
setpgid(getpid(), getpid());
#ifdef __linux__
// install a parent death signal
// http://stackoverflow.com/a/36945270
int r = prctl(PR_SET_PDEATHSIG, SIGTERM);
if (r == -1)
{
if(!quiet_output) std::cout << "Error installing parent death signal\n";
throw 1;
}
if (getppid() != ppid_before_fork)
exit(1);
#endif
dup2(writePipe[0], STDIN_FILENO);
dup2(readPipe[1], STDOUT_FILENO);
dup2(readPipe[1], STDERR_FILENO);
execl("/bin/sh", "sh", "-c", command.c_str(), (char*) NULL);
//Nothing past the execl should be run
exit(1);
} else if (pid < 0) {
if (!quiet_output) std::cout << "Fork failed\n";
throw 1;
}
UniConnection connection;
connection.read = readPipe[0];
connection.write = writePipe[1];
connections.push_back(connection);
processes.push_back(pid);
#endif
player_logs.push_back(std::string());
}
int Networking::handle_init_networking(hlt::PlayerId player_tag,
const hlt::Map& m,
bool ignoreTimeout,
std::string* playerName) {
const int ALLOTTED_MILLIS = ignoreTimeout ? 2147483647 : 60000;
std::string response;
nlohmann::json init_log_json;
try {
std::string playerTagString = std::to_string(player_tag),
mapSizeString = serializeMapSize(m), mapString = serialize_map(m);
send_string(player_tag, playerTagString);
send_string(player_tag, mapSizeString);
send_string(player_tag, mapString);
std::string outMessage =
"Init Message sent to player " + std::to_string(int(player_tag))
+ ".\n";
if (!quiet_output) std::cout << outMessage;
std::chrono::high_resolution_clock::time_point
initialTime = std::chrono::high_resolution_clock::now();
response = get_string(player_tag, ALLOTTED_MILLIS);
unsigned int millisTaken =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now()
- initialTime).count();
init_log_json["Time"] = millisTaken;
init_log_json["Turn"] = 0;
*playerName = response.substr(0, 30);
if (!quiet_output) {
std::string inMessage = "Init Message received from player "
+ std::to_string(int(player_tag)) + ", " + *playerName + ".\n";
std::cout << inMessage;
}
player_logs_json[player_tag]["Frames"] += init_log_json;
player_logs_json[player_tag]["PlayerID"] = player_tag;
player_logs_json[player_tag]["PlayerName"] = *playerName;
return millisTaken;
}
catch (BotInputError err) {
if (!quiet_output) {
std::lock_guard<std::mutex> guard(coutMutex);
std::cout << err.what() << std::endl;
}
player_logs_json[player_tag]["Error"]["Message"] = err.what();
player_logs_json[player_tag]["Error"]["Turn"] = 0;
*playerName =
"Bot #" + std::to_string(player_tag) + "; timed out during Init";
}
catch (std::string s) {
player_logs_json[player_tag]["Error"]["Message"] = "ERRORED! Response received (if any): " + s;
player_logs_json[player_tag]["Error"]["Turn"] = 0;
*playerName =
"Bot #" + std::to_string(player_tag) + "; timed out during Init";
}
catch (...) {
player_logs_json[player_tag]["Error"]["Message"] = "ERRORED! Response received (if any): " + response;
player_logs_json[player_tag]["Error"]["Turn"] = 0;
*playerName =
"Bot #" + std::to_string(player_tag) + "; timed out during Init";
}
player_logs_json[player_tag]["Frames"] += init_log_json;
return -1;
}
int Networking::handle_frame_networking(hlt::PlayerId player_tag,
const unsigned short& turnNumber,
const hlt::Map& m,
bool ignoreTimeout,
hlt::PlayerMoveQueue& moves) {
const int ALLOTTED_MILLIS = ignoreTimeout ? 2147483647 : 2000;
std::string response;
nlohmann::json log_json;
try {
if (is_process_dead(player_tag)) {
return -1;
}
//Send this bot the game map and the messages addressed to this bot
std::string mapString = serialize_map(m);
send_string(player_tag, mapString);
std::chrono::high_resolution_clock::time_point
initialTime = std::chrono::high_resolution_clock::now();
response = get_string(player_tag, ALLOTTED_MILLIS);
const auto millisTaken =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now()
- initialTime).count();
log_json["Time"] = millisTaken;
deserialize_move_set(player_tag, response, m, moves);
player_logs_json[player_tag]["Frames"] += log_json;
return millisTaken;
}
catch (BotInputError err) {
if (!quiet_output) {
std::lock_guard<std::mutex> guard(coutMutex);
std::cout << err.what() << std::endl;
}
std::string error_string = response + read_trailing_input(player_tag);
player_logs_json[player_tag]["Error"]["Message"] = "ERRORED! Got Exception (if any): " + std::string(err.what()) + "; Response received (if any): " + error_string;
player_logs_json[player_tag]["Error"]["Turn"] = turnNumber;
}
catch (std::string s) {
player_logs_json[player_tag]["Error"]["Message"] = "ERRORED! Response received (if any): " + s;
player_logs_json[player_tag]["Error"]["Turn"] = turnNumber;
}
catch (hlt::GameAbort) {
throw; // propogate early termination
}
catch (...) {
player_logs_json[player_tag]["Error"]["Message"] = "ERRORED! Response received (if any): " + response;
player_logs_json[player_tag]["Error"]["Turn"] = turnNumber;
}
player_logs_json[player_tag]["Frames"] += log_json;
return -1;
}
void Networking::kill_player(hlt::PlayerId player_tag) {
if (is_process_dead(player_tag)) return;
std::string newString;
const int PER_CHAR_WAIT = 10; // millis
const int MAX_READ_TIME = 1000; // millis
#ifdef _WIN32
// Try to read entire contents of pipe.
WinConnection connection = connections[player_tag];
DWORD charsRead;
bool success;
char buffer;
std::chrono::high_resolution_clock::time_point tp = std::chrono::high_resolution_clock::now();
while(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - tp).count() < MAX_READ_TIME) {
DWORD bytesAvailable = 0;
PeekNamedPipe(connection.read, NULL, 0, NULL, &bytesAvailable, NULL);
if(bytesAvailable < 1) {
std::chrono::high_resolution_clock::time_point initialTime = std::chrono::high_resolution_clock::now();
while(bytesAvailable < 1) {
if(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - initialTime).count() > PER_CHAR_WAIT) break;
PeekNamedPipe(connection.read, NULL, 0, NULL, &bytesAvailable, NULL);
}
if(bytesAvailable < 1) break; // Took too long to get a character; breaking.
}
success = ReadFile(connection.read, &buffer, 1, &charsRead, NULL);
if(!success || charsRead < 1) {
if(!quiet_output) {
std::string errorMessage = "Bot #" + std::to_string(player_tag) + " timed out or errored (Windows)\n";
std::lock_guard<std::mutex> guard(coutMutex);
std::cout << errorMessage;
}
break;
}
newString += buffer;
}
HANDLE process = processes[player_tag];
TerminateProcess(process, 0);
processes[player_tag] = NULL;
connections[player_tag].read = NULL;
connections[player_tag].write = NULL;
std::string deadMessage = "Player " + std::to_string(player_tag) + " is dead\n";
if(!quiet_output) std::cout << deadMessage;
#else
// Try to read entire contents of pipe.
UniConnection connection = connections[player_tag];
fd_set set;
FD_ZERO(&set); /* clear the set */
FD_SET(connection.read, &set); /* add our file descriptor to the set */
char buffer;
std::chrono::high_resolution_clock::time_point
tp = std::chrono::high_resolution_clock::now();
while (std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - tp).count()
< MAX_READ_TIME) {
struct timeval timeout;
timeout.tv_sec = PER_CHAR_WAIT / 1000;
timeout.tv_usec = (PER_CHAR_WAIT % 1000) * 1000;
int selectionResult =
select(connection.read + 1, &set, NULL, NULL, &timeout);
if (selectionResult > 0) {
const size_t bytes_read = read(connection.read, &buffer, 1);
if (bytes_read != 1) {
break;
}
newString += buffer;
} else break;
}
kill(-processes[player_tag], SIGKILL);
processes[player_tag] = -1;
connections[player_tag].read = -1;
connections[player_tag].write = -1;
#endif
if (!newString.empty()) {
if (!quiet_output) {
std::cout << "Bot " << (int) player_tag << " was killed.\n";
std::cout << "Here is the rest of its output (if any):\n";
std::cout << newString;
if (newString.back() != '\n') {
std::cout << '\n';
}
std::cout << "--- End bot output ---\n";
}
}
}
bool Networking::is_process_dead(hlt::PlayerId player_tag) {
#ifdef _WIN32
return processes[player_tag] == NULL;
#else
return processes.at(player_tag) == -1;
#endif
}
int Networking::player_count() {
#ifdef _WIN32
return connections.size();
#else
return connections.size();
#endif
}
| mit |
marcosgambeta/Qt5xHb | codegen/QtSerialPort/QtSerialPortVersion.cpp | 934 | %%
%% Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5
%%
%% Copyright (C) 2020 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
%%
$project=Qt5xHb
$module=QtSerialPort
$header
#include <QtCore/Qt>
#ifndef __XHARBOUR__
#if (QT_VERSION >= QT_VERSION_CHECK(5,1,0))
#include <QtSerialPort/QtSerialPortVersion>
#endif
#endif
#include "qt5xhb_common.h"
#include "qt5xhb_macros.h"
#include "qt5xhb_utils.h"
#ifdef __XHARBOUR__
#if (QT_VERSION >= QT_VERSION_CHECK(5,1,0))
#include <QtSerialPort/QtSerialPortVersion>
#endif
#endif
HB_FUNC( QTSERIALPORT_VERSION_STR )
{
#if (QT_VERSION >= QT_VERSION_CHECK(5,1,0))
hb_retc( (const char *) QTSERIALPORT_VERSION_STR );
#else
hb_retc( (const char *) "" );
#endif
}
HB_FUNC( QTSERIALPORT_VERSION )
{
#if (QT_VERSION >= QT_VERSION_CHECK(5,1,0))
hb_retni( QTSERIALPORT_VERSION );
#else
hb_retni( 0 );
#endif
}
| mit |
l33tdaima/l33tdaima | pr1220h/count_vowel_permutation.py | 416 | class Solution:
def countVowelPermutation(self, n: int) -> int:
a, e, i, o, u = 1, 1, 1, 1, 1
for _ in range(n - 1):
a, e, i, o, u = e + i + u, a + i, e + o, i, i + o
return (a + e + i + o + u) % (10 ** 9 + 7)
# TESTS
for n, expected in [
(1, 5),
(2, 10),
(5, 68),
]:
sol = Solution()
actual = sol.countVowelPermutation(n)
assert actual == expected
| mit |
flyelmos/Software-University | 04. C# Advanced/03. Matrices Exercises/07. Lego Blocks/LegoBlocks.cs | 3216 | namespace _07.Lego_Blocks
{
using System;
using System.Linq;
public class LegoBlocks
{
public static void Main()
{
/*
This program recieves two jagged arrays. Each array represents a Lego block containing integers.
After that it reverses the second jagged array and then checks if it would fit perfectly in the first jagged array.
*/
int rows = int.Parse(Console.ReadLine());
int[][] firstMatrix = new int[rows][];
int[][] secondMatrix = new int[rows][];
for (int currRow = 0; currRow < rows; currRow++)
{
int[] elements = Console.ReadLine()
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
firstMatrix[currRow] = new int[elements.Length];
for (int currCol = 0; currCol < elements.Length; currCol++)
{
firstMatrix[currRow][currCol] = elements[currCol];
}
}
for (int currRow = 0; currRow < rows; currRow++)
{
int[] elements = Console.ReadLine()
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
secondMatrix[currRow] = new int[elements.Length];
for (int currCol = 0; currCol < elements.Length; currCol++)
{
secondMatrix[currRow][currCol] = elements[currCol];
}
}
int[][] combinedMatrix = new int[rows][];
int totalCols = 0;
for (int currRow = 0; currRow < rows; currRow++)
{
combinedMatrix[currRow] = new int[firstMatrix[currRow].Length + secondMatrix[currRow].Length];
for (int mFirstCol = 0; mFirstCol < firstMatrix[currRow].Length; mFirstCol++)
{
combinedMatrix[currRow][mFirstCol] = firstMatrix[currRow][mFirstCol];
}
int reversedIndex = secondMatrix[currRow].Length - 1;
for (int mSecondCol = 0; mSecondCol < secondMatrix[currRow].Length; mSecondCol++)
{
int continueIndex = firstMatrix[currRow].Length + mSecondCol;
combinedMatrix[currRow][continueIndex] = secondMatrix[currRow][reversedIndex];
reversedIndex--;
}
totalCols += combinedMatrix[currRow].Length;
}
if (totalCols % combinedMatrix[0].Length == 0)
{
for (int currRow = 0; currRow < combinedMatrix.Length; currRow++)
{
Console.Write("[");
Console.Write(string.Join(", ", combinedMatrix[currRow]));
Console.Write("]");
Console.WriteLine();
}
}
else
{
Console.WriteLine($"The total number of cells is: {totalCols}");
}
}
}
}
| mit |
AspectCore/Abstractions | src/AspectCore.Abstractions/DependencyInjection/IManyEnumerable.cs | 254 | using System.Collections;
using System.Collections.Generic;
using AspectCore.DynamicProxy;
namespace AspectCore.DependencyInjection
{
[NonAspect, NonCallback]
public interface IManyEnumerable<out T> : IEnumerable<T>, IEnumerable
{
}
} | mit |
cinhtau/kaffee-pelion | lang/src/test/java/net/cinhtau/demo/MathDemoTest.java | 2364 | package net.cinhtau.demo;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public class MathDemoTest {
private MathDemo mathDemo;
@Before
public void setUp() {
this.mathDemo = new MathDemo();
}
@Test
public void testGetEvenNumbers() throws Exception {
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < 100; i++) {
numbers.add(i);
}
List<Integer> resultList = mathDemo.getEvenNumbers(numbers);
assertThat("only even numbers", resultList.size(), is(50));
}
@Test
public void testSimple() {
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < 10_000_000; i++) {
numbers.add((int) Math.round(Math.random() * 100));
}
//This will use just a single thread
for (int i = 0; i < 100; i++) {
long start = System.currentTimeMillis();
List<Integer> even = numbers.stream()
.mapToInt(n -> n)
.filter(n -> n % 2 == 0)
.sorted()
.boxed()
.collect(toList());
System.out.printf("%d elements computed in %5d msecs with %d threads\n", even.size(),
System.currentTimeMillis() - start,
Thread.activeCount());
}
}
@Test
public void testParallel() {
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < 10_000_000; i++) {
numbers.add((int) Math.round(Math.random() * 100));
}
//Automatically select the optimum number of threads
for (int i = 0; i < 100; i++) {
long start = System.currentTimeMillis();
List<Integer> even = numbers.parallelStream()
.mapToInt(n -> n)
.filter(n -> n % 2 == 0)
.sorted()
.boxed()
.collect(toList());
System.out.printf("%d elements computed in %5d msecs with %d threads\n", even.size(),
System.currentTimeMillis() - start,
Thread.activeCount());
}
}
} | mit |
Telerik-Homework-ValentinRangelov/Homework | C#/C# 2/Homework Numeral Systems/Problem 7. One system to any other/Program.cs | 2994 | using System;
using System.Linq;
//Write a program to convert from any numeral system of given base s to any other numeral system of base d (2 ≤ s, d ≤ 16).
class OneSystemToAnyOther
{
static void Main()
{
Console.Write("Number's base X: ");
int baseX = int.Parse(Console.ReadLine());
if (baseX < 2) throw new ArgumentOutOfRangeException();
Console.Write("\nEnter a non-negative integer number [base {0}]: ", baseX);
string number = StringParse();
Console.Write("\nConvert to base Y: ");
int baseY = int.Parse(Console.ReadLine());
if (baseY < 2 || baseY > 16) throw new ArgumentOutOfRangeException();
string result = ConvertFromDecimalToBaseY(ConvertToDecimal(number.ToArray(), baseX), baseY);
if (IsValidInput(number, result, baseX, baseY))
{
Console.Write("\nResult -> {0} [base {1}] converted to [base {2}] => {3}\n\n", number, baseX, baseY, result);
}
else
{
Console.WriteLine("\n-> You have entered an invalid number!\n");
}
}
static string StringParse()
{
string number = Console.ReadLine();
// Check for incorrect number
if (number.Any(t => t < 'A' && t > 'Z' && t < 'a' && t > 'z' && t < '0' && t > '9'))
{
throw new ArgumentException();
}
number = MakeAllLettersLarge(number);
return number;
}
// aff == AFF => valid input number
static string MakeAllLettersLarge(string number)
{
char[] digits = number.ToArray();
for (int i = 0; i < digits.Length; i++)
digits[i] = char.ToUpper(number[i]);
return string.Join("", digits);
}
#region [Essential Part - Conversion]
// Convert number [base X] to number [base 10]
static int ConvertToDecimal(char[] number, int baseX)
{
int result = 0;
for (int i = number.Length - 1, pow = 1; i >= 0; i--, pow *= baseX)
result += (number[i] >= 'A') ? (number[i] - 'A' + 10) * pow : (number[i] - '0') * pow;
return result;
}
// Convert number [base 10] to number [base Y]
static string ConvertFromDecimalToBaseY(int number, int baseY)
{
string result = string.Empty;
while (number > 0)
{
int remainder = number % baseY;
result = remainder >= 10 ? (char)('A' + remainder - 10) + result : remainder + result;
number /= baseY;
}
return result;
}
#endregion
// Convert the result from BaseY to baseX and compare the new result with the old result (baseX to baseY)
static bool IsValidInput(string number, string result, int baseX, int baseY)
{
return String.CompareOrdinal(ConvertFromDecimalToBaseY(ConvertToDecimal(result.ToArray(), baseY), baseX), number) == 0;
}
} | mit |
liruqi/bigfoot | Interface/AddOns/Collector/Widget/PlanItem.lua | 3690 |
BuildEnv(...)
local PlanItem = Addon:NewClass('PlanItem', GUI:GetClass('ItemButton'))
function PlanItem:Constructor()
local Icon = self:CreateTexture(nil, 'ARTWORK') do
Icon:SetPoint('LEFT', 4, 0)
Icon:SetSize(38, 38)
Icon:SetTexture([[Interface\ICONS\Achievement_BG_winbyten]])
end
local Bg = self:CreateTexture(nil, 'BACKGROUND') do
Bg:SetPoint('LEFT', Icon, 'RIGHT', 4, 0)
Bg:SetPoint('TOPRIGHT')
Bg:SetPoint('BOTTOMRIGHT')
Bg:SetAtlas('PetList-ButtonBackground')
end
local Highlight = self:CreateTexture(nil, 'HIGHLIGHT') do
Highlight:SetAllPoints(Bg)
Highlight:SetAtlas('PetList-ButtonHighlight')
end
local Checked = self:CreateTexture(nil, 'OVERLAY') do
Checked:SetAllPoints(Bg)
Checked:SetAtlas('PetList-ButtonSelect')
self:SetCheckedTexture(Checked)
end
local State = self:CreateFontString(nil, 'ARTWORK', 'GameFontNormalRight') do
State:SetPoint('RIGHT', Bg, 'RIGHT', -10, 0)
end
local Text = self:CreateFontString(nil, 'ARTWORK', 'GameFontNormalLeft') do
Text:SetPoint('LEFT', Bg, 'LEFT', 10, 0)
Text:SetPoint('RIGHT', State, 'LEFT', -5, 0)
Text:SetWordWrap(false)
self:SetFontString(Text)
end
local ExtraIcon = self:CreateTexture(nil, 'BORDER') do
ExtraIcon:SetSize(46, 44)
ExtraIcon:SetPoint('BOTTOMRIGHT', -1, 1)
end
local Track = self:CreateTexture(nil, 'BORDER') do
Track:Hide()
Track:SetSize(16, 16)
Track:SetPoint('TOPRIGHT', Bg)
Track:SetTexture([[Interface\BUTTONS\UI-CheckBox-Check]])
end
-- local StatusBar = CreateFrame('StatusBar', nil, self) do
-- StatusBar:SetPoint('BOTTOMLEFT', Bg, 'BOTTOMLEFT', 2, 0)
-- StatusBar:SetPoint('BOTTOMRIGHT', Bg, 'BOTTOMRIGHT', -2, 0)
-- StatusBar:SetHeight(3)
-- StatusBar:SetMinMaxValues(0, 100)
-- StatusBar:SetValue(50)
-- StatusBar:SetStatusBarTexture([[Interface\TargetingFrame\UI-StatusBar]], 'BACKGROUND')
-- end
-- local StatusBarText = StatusBar:CreateFontString(nil, 'ARTWORK') do
-- StatusBarText:SetPoint('BOTTOMRIGHT', 0, 3)
-- StatusBarText:SetFont(ChatFontNormal:GetFont(), 12)
-- end
self.Icon = Icon
self.State = State
self.StatusBar = StatusBar
self.StatusBarText = StatusBarText
self.ExtraIcon = ExtraIcon
self.Track = Track
self:SetScript('OnSizeChanged', self.OnSizeChanged)
end
function PlanItem:SetIcon(icon)
self.Icon:SetTexture(icon)
end
function PlanItem:SetExtraTexture(texture, l, r, t, b)
if not texture then
self.ExtraIcon:Hide()
else
self.ExtraIcon:SetTexture(texture)
self.ExtraIcon:SetTexCoord(l or 0, r or 1, t or 0, b or 1)
self.ExtraIcon:Show()
end
end
function PlanItem:SetExtraSize(w, h)
self.ExtraIcon:SetSize(w, h)
end
function PlanItem:SetPlan(plan)
local item = plan:GetObject()
self:SetText(item:GetName())
self:SetIcon(item:GetIcon())
self:SetExtraTexture(item:GetTypeTexture())
self:SetExtraSize(item:GetTypeSize())
self.Track:SetShown(item:IsInTrack())
local state = item:IsCanKill()
local text
local color
if state == true then
text = BOSS_ALIVE
color = GREEN_FONT_COLOR
elseif state == false then
text = BOSS_DEAD
color = RED_FONT_COLOR
end
self.State:SetText(text)
if color then
self.State:SetTextColor(color.r, color.g, color.b)
end
end | mit |
DemSquirrel/Le_Coinflip | www/js/admin/stathandler.js | 1432 | var socket = io()
var statHandler = {
getToken: function () {
swal({
title: "The token i gave you, I need",
text: "",
type: "input",
imageUrl: "https://monomythic.files.wordpress.com/2015/12/yoda-main-clean.jpg",
showCancelButton: false,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Yoda"
},
function(inputValue){
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
var myToken = statHandler.validateToken(inputValue)
socket.on('validToken', function (token) {
if(token == myToken){
swal.close()
}else {
window.location.replace("http://localhost:3000/")
}
})
})
},
validateToken: function (token) {
var tokenChecked = token
socket.emit('checkToken', token)
return tokenChecked
},
sortUserser: function (users) {
var swapped;
do {
swapped = false;
for (var i=0; i < users.length-1; i++) {
if (users[i] > users[i+1]) {
var temp = users[i];
users[i] = users[i+1];
users[i+1] = temp;
swapped = true;
}
}
} while (swapped);
return users
}
}
window.onload = function () {
statHandler.getToken()
}
| mit |
thekosmix/interview-street | oprp/_php/init_student.php | 662 | <?php
require_once("config.php");
require_once("functions.php");
require_once("database.php");
require_once("session.php");
require_once("user.php");
require_once("branch.php");
require_once("student.php");
require_once("announcement.php");
require_once("acad_be.php");
require_once("acad_me.php");
require_once("acad_mba.php");
require_once("proj.php");
require_once("recruiter.php");
require_once("company.php");
require_once("application.php");
require_once("forum_topic.php");
require_once("forum_comment.php");
require_once("forum_subs.php");
$session->moveNotStudent();
date_default_timezone_set('Asia/Calcutta');
?> | mit |
david-driscoll/bike-computer | services/PathService.ts | 771 | import {Observable} from 'rxjs';
import {Injectable} from '@angular/core';
import _ from 'lodash';
import angles from 'angles';
import {DistanceService} from './DistanceService';
import {LocationService, LngLatArray} from './LocationService';
@Injectable()
export class PathService {
private _trip: Observable<LngLatArray[]>;
constructor(distanceService: DistanceService, locationService: LocationService) {
this._trip = distanceService.trip
.auditTime(2000)
.withLatestFrom(locationService.current)
.scan<LngLatArray[]>((acc, [, lngLat]) => {
acc.push([lngLat[0], lngLat[1]]);
return acc;
}, [])
.share();
}
public get trip() { return this._trip; }
}
| mit |
mipmip/rspec_testlink_formatters | lib/rspec_testlink_formatters.rb | 211 | require "rspec_testlink_formatters/version"
require File.expand_path(File.dirname(__FILE__) + "/rspec_testlink_export_cases")
require File.expand_path(File.dirname(__FILE__) + "/rspec_testlink_junit_formatter")
| mit |
StevenUpForever/LeetCode_Java | src/bit_operation/Q751IPToCIDR.java | 3877 | package bit_operation;
import java.util.ArrayList;
import java.util.List;
public class Q751IPToCIDR {
//Difficulty: easy
//TAG: Airbnb
//TAG: bit operation
/**
* 751. IP to CIDR
* Given a start IP address ip and a number of ips we need to cover n, return a representation of the range as a list (of smallest possible length) of CIDR blocks.
*
* A CIDR block is a string consisting of an IP, followed by a slash, and then the prefix length. For example: "123.45.67.89/20". That prefix length "20" represents the number of common prefix bits in the specified range.
*
* Example 1:
* Input: ip = "255.0.0.7", n = 10
* Output: ["255.0.0.7/32","255.0.0.8/29","255.0.0.16/32"]
* Explanation:
* The initial ip address, when converted to binary, looks like this (spaces added for clarity):
* 255.0.0.7 -> 11111111 00000000 00000000 00000111
* The address "255.0.0.7/32" specifies all addresses with a common prefix of 32 bits to the given address,
* ie. just this one address.
*
* The address "255.0.0.8/29" specifies all addresses with a common prefix of 29 bits to the given address:
* 255.0.0.8 -> 11111111 00000000 00000000 00001000
* Addresses with common prefix of 29 bits are:
* 11111111 00000000 00000000 00001000
* 11111111 00000000 00000000 00001001
* 11111111 00000000 00000000 00001010
* 11111111 00000000 00000000 00001011
* 11111111 00000000 00000000 00001100
* 11111111 00000000 00000000 00001101
* 11111111 00000000 00000000 00001110
* 11111111 00000000 00000000 00001111
*
* The address "255.0.0.16/32" specifies all addresses with a common prefix of 32 bits to the given address,
* ie. just 11111111 00000000 00000000 00010000.
*
* In total, the answer specifies the range of 10 ips starting with the address 255.0.0.7 .
*
* There were other representations, such as:
* ["255.0.0.7/32","255.0.0.8/30", "255.0.0.12/30", "255.0.0.16/32"],
* but our answer was the shortest possible.
*
* Also note that a representation beginning with say, "255.0.0.7/30" would be incorrect,
* because it includes addresses like 255.0.0.4 = 11111111 00000000 00000000 00000100
* that are outside the specified range.
* Note:
* ip will be a valid IPv4 address.
* Every implied address ip + x (for x < n) will be a valid IPv4 address.
* n will be an integer in the range [1, 1000].
*/
/*
Solution:
1. combine ip address to an integer
2. loop until range is filled
2.1 find the rightmost 1 by x & -x
2.2 right shift the 1 to <= current range, means fill with shortest prefix as much as possible
2.3 convert current x append with length to res
2.4 increase x by step to next possible shortest prefix
2.5 minus steps in range so that we know how much range left
*/
public List<String> ipToCIDR(String ip, int range) {
long x = 0;
String[] ips = ip.split("\\.");
for (int i = 0; i < ips.length; ++i) {
x = Integer.parseInt(ips[i]) + x * 256;
}
List<String> ans = new ArrayList<>();
while (range > 0) {
long step = x & -x;
while (step > range) step >>= 1;
ans.add(longToIP(x, (int)step));
x += step;
range -= step;
}
return ans;
}
String longToIP(long x, int step) {
int[] ans = new int[4];
ans[0] = (int) (x & 255); x >>= 8;
ans[1] = (int) (x & 255); x >>= 8;
ans[2] = (int) (x & 255); x >>= 8;
ans[3] = (int) x;
int len = 33;
while (step > 0) {
len--;
step >>= 2;
}
return ans[3] + "." + ans[2] + "." + ans[1] + "." + ans[0] + "/" + len;
}
}
| mit |
piiswrong/dec | caffe/src/caffe/test/test_entropy_t_loss_layer.cpp | 6205 | #include <cmath>
#include <cstdlib>
#include <cstring>
#include <vector>
#include "gtest/gtest.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/vision_layers.hpp"
#include "caffe/test/test_caffe_main.hpp"
#include "caffe/test/test_gradient_check_util.hpp"
namespace caffe {
const int M_ = 10;
const int K_ = 10;
const int N_ = 4;
template <typename TypeParam>
class EntropyTLossLayerTest : public MultiDeviceTest<TypeParam> {
typedef typename TypeParam::Dtype Dtype;
protected:
EntropyTLossLayerTest()
: blob_bottom_data_(new Blob<Dtype>(M_, 1, 1, K_)),
blob_bottom_label_(new Blob<Dtype>(M_, 1, 1, N_)),
blob_top_loss_(new Blob<Dtype>()),
blob_top_std_(new Blob<Dtype>()),
blob_top_ind_(new Blob<Dtype>()),
blob_top_dist_(new Blob<Dtype>()) {
// fill the values
FillerParameter filler_param;
filler_param.set_value(0);
GaussianFiller<Dtype> filler(filler_param);
filler.Fill(this->blob_bottom_data_);
Dtype *cpu_label = blob_bottom_label_->mutable_cpu_data();
caffe_rng_uniform(blob_bottom_label_->count(), Dtype(0), Dtype(1), cpu_label);
for (int i = 0; i < M_; i++) {
Dtype norm = Dtype(0);
for (int j = 0; j < N_; j++) {
norm += cpu_label[i*N_+j];
}
for (int j = 0; j < N_; j++) {
cpu_label[i*N_+j] /= norm;
}
}
blob_bottom_vec_.push_back(blob_bottom_data_);
blob_bottom_vec_.push_back(blob_bottom_label_);
blob_top_vec_.push_back(blob_top_loss_);
blob_top_vec_.push_back(blob_top_std_);
blob_top_vec_.push_back(blob_top_ind_);
blob_top_vec_.push_back(blob_top_dist_);
}
virtual ~EntropyTLossLayerTest() {
delete blob_bottom_data_;
delete blob_bottom_label_;
delete blob_top_loss_;
delete blob_top_ind_;
delete blob_top_std_;
delete blob_top_dist_;
}
void TestForward() {
// Get the loss without a specified objective weight -- should be
// equivalent to explicitly specifiying a weight of 1.
LayerParameter layer_param;
layer_param.mutable_multi_t_loss_param()->set_num_center(N_);
EntropyTLossLayer<Dtype> layer_weight_1(layer_param);
layer_weight_1.SetUp(this->blob_bottom_vec_, &this->blob_top_vec_);
layer_weight_1.Forward(this->blob_bottom_vec_, &this->blob_top_vec_);
FillerParameter filler_param;
GaussianFiller<Dtype> filler2(filler_param);
filler2.Fill(layer_weight_1.blobs()[0].get());
caffe_rng_uniform(layer_weight_1.blobs()[1]->count(), Dtype(0.9), Dtype(1.1), layer_weight_1.blobs()[1]->mutable_cpu_data());
layer_weight_1.SetUp(this->blob_bottom_vec_, &this->blob_top_vec_);
const Dtype loss_weight_1 =
layer_weight_1.Forward(this->blob_bottom_vec_, &this->blob_top_vec_);
// Get the loss again with a different objective weight; check that it is
// scaled appropriately.
const Dtype kLossWeight = 3.7;
LayerParameter layer_param2;
layer_param2.mutable_multi_t_loss_param()->set_num_center(N_);
layer_param2.add_loss_weight(kLossWeight);
EntropyTLossLayer<Dtype> layer_weight_2(layer_param2);
layer_weight_2.SetUp(this->blob_bottom_vec_, &this->blob_top_vec_);
layer_weight_2.Forward(this->blob_bottom_vec_, &this->blob_top_vec_);
caffe_copy(layer_weight_2.blobs()[0]->count(), layer_weight_1.blobs()[0]->cpu_data(),
layer_weight_2.blobs()[0]->mutable_cpu_data());
caffe_copy(layer_weight_2.blobs()[1]->count(), layer_weight_1.blobs()[1]->cpu_data(),
layer_weight_2.blobs()[1]->mutable_cpu_data());
layer_weight_2.SetUp(this->blob_bottom_vec_, &this->blob_top_vec_);
const Dtype loss_weight_2 =
layer_weight_2.Forward(this->blob_bottom_vec_, &this->blob_top_vec_);
const Dtype kErrorMargin = 1e-3;
EXPECT_NEAR(loss_weight_1 * kLossWeight, loss_weight_2, kErrorMargin);
// Make sure the loss is non-trivial.
const Dtype kNonTrivialAbsThresh = 1e-1;
EXPECT_GE(fabs(loss_weight_1), kNonTrivialAbsThresh);
int m = M_, n = layer_param.multi_t_loss_param().num_center(), p = K_;
Blob<Dtype> *distance = layer_weight_1.distance();
const Dtype *cpu_data = blob_bottom_data_->cpu_data();
const Dtype *cpu_dist = distance->cpu_data();
const Dtype *cpu_center = layer_weight_1.blobs()[0]->cpu_data();
const Dtype *cpu_sigma = layer_weight_1.blobs()[1]->cpu_data();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
Dtype acc = Dtype(0);
for (int k = 0; k < p; ++k) {
acc += (cpu_data[i*p + k] - cpu_center[k*n + j])*(cpu_data[i*p + k] - cpu_center[k*n + j])*cpu_sigma[k*n+j];
}
EXPECT_NEAR(acc, cpu_dist[i*n + j], kErrorMargin) << i << " " << j;
}
}
}
Blob<Dtype>* const blob_bottom_data_;
Blob<Dtype>* const blob_bottom_label_;
Blob<Dtype>* const blob_top_loss_;
Blob<Dtype>* const blob_top_std_;
Blob<Dtype>* const blob_top_ind_;
Blob<Dtype>* const blob_top_dist_;
vector<Blob<Dtype>*> blob_bottom_vec_;
vector<Blob<Dtype>*> blob_top_vec_;
};
TYPED_TEST_CASE(EntropyTLossLayerTest, TestDtypesAndDevices);
TYPED_TEST(EntropyTLossLayerTest, TestForward) {
this->TestForward();
}
TYPED_TEST(EntropyTLossLayerTest, TestGradient) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
const Dtype kLossWeight = 1.0;
layer_param.add_loss_weight(kLossWeight);
layer_param.mutable_multi_t_loss_param()->set_num_center(N_);
EntropyTLossLayer<Dtype> layer(layer_param);
layer.SetUp(this->blob_bottom_vec_, &this->blob_top_vec_);
layer.Forward(this->blob_bottom_vec_, &this->blob_top_vec_);
FillerParameter filler_param;
filler_param.set_value(0);
GaussianFiller<Dtype> filler(filler_param);
filler.Fill(this->blob_bottom_data_);
filler.Fill(layer.blobs()[0].get());
//caffe_rng_uniform(layer.blobs()[1]->count(), Dtype(0.9), Dtype(1.1), layer.blobs()[1]->mutable_cpu_data());
//layer.SetUp(this->blob_bottom_vec_, &this->blob_top_vec_);
GradientChecker<Dtype> checker(1e-2, 1e-2, 1701);
checker.CheckGradientSingle(&layer, &(this->blob_bottom_vec_),
&(this->blob_top_vec_), 0, 0, 0);
}
} // namespace caffe
| mit |
zekewang918/QuitSmoking | bbs/source/class/extend/extend_thread_rushreply.php | 5555 | <?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: extend_thread_rushreply.php 33048 2013-04-12 08:50:27Z zhangjie $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class extend_thread_rushreply extends extend_thread_base {
public function before_newthread($parameters) {
if($this->group['allowpostrushreply']) {
$_GET['rushreplyfrom'] = strtotime($_GET['rushreplyfrom']);
$_GET['rushreplyto'] = strtotime($_GET['rushreplyto']);
$_GET['rewardfloor'] = trim($_GET['rewardfloor']);
$_GET['stopfloor'] = intval($_GET['stopfloor']);
$_GET['replylimit'] = intval($_GET['replylimit']);
$_GET['creditlimit'] = $_GET['creditlimit'] == '' ? '-996' : intval($_GET['creditlimit']);
if($_GET['rushreplyfrom'] > $_GET['rushreplyto'] && !empty($_GET['rushreplyto'])) {
showmessage('post_rushreply_timewrong');
}
if(($_GET['rushreplyfrom'] > TIMESTAMP) || (!empty($_GET['rushreplyto']) && $_GET['rushreplyto'] < TIMESTAMP) || ($_GET['stopfloor'] == 1) ) {
$this->param['closed'] = true;
}
if(!empty($_GET['rewardfloor']) && !empty($_GET['stopfloor'])) {
$floors = explode(',', $_GET['rewardfloor']);
if(!empty($floors) && is_array($floors)) {
foreach($floors AS $key => $floor) {
if(strpos($floor, '*') === false) {
if(intval($floor) == 0) {
unset($floors[$key]);
} elseif($floor > $_GET['stopfloor']) {
unset($floors[$key]);
}
}
}
$_GET['rewardfloor'] = implode(',', $floors);
}
}
$parameters['tstatus'] = setstatus(3, 1, $parameters['tstatus']);
$parameters['tstatus'] = setstatus(1, 1, $parameters['tstatus']);
$this->param['tstatus'] = $parameters['tstatus'];
}
}
public function after_newthread() {
if($this->group['allowpostrushreply']) {
$rushdata = array('tid' => $this->tid, 'stopfloor' => $_GET['stopfloor'], 'starttimefrom' => $_GET['rushreplyfrom'], 'starttimeto' => $_GET['rushreplyto'], 'rewardfloor' => $_GET['rewardfloor'], 'creditlimit' => $_GET['creditlimit'], 'replylimit' => $_GET['replylimit']);
C::t('forum_threadrush')->insert($rushdata);
}
}
public function before_newreply() {
global $_G, $rushinfo;
if(getstatus($this->thread['status'], 3) && $rushinfo['replylimit'] > 0) {
$replycount = C::t('forum_post')->count_by_tid_invisible_authorid($this->thread['tid'], $_G['uid']);
if($replycount >= $rushinfo['replylimit']) {
showmessage('noreply_replynum_error');
}
}
}
public function after_newreply() {
global $rushinfo;
if(getstatus($this->thread['status'], 3) && $this->param['maxposition']) {
$rushstopfloor = $rushinfo['stopfloor'];
if($rushstopfloor > 0 && $this->thread['closed'] == 0 && $this->param['maxposition'] >= $rushstopfloor) {
$this->param['updatethreaddata'] = array_merge((array)$this->param['updatethreaddata'], array('closed' => 1));
}
}
}
public function before_editpost($parameters) {
global $_G, $rushreply;
$isfirstpost = $this->post['first'] ? 1 : 0;
if($isfirstpost) {
if($rushreply) {
$_GET['rushreplyfrom'] = strtotime($_GET['rushreplyfrom']);
$_GET['rushreplyto'] = strtotime($_GET['rushreplyto']);
$_GET['rewardfloor'] = trim($_GET['rewardfloor']);
$_GET['stopfloor'] = intval($_GET['stopfloor']);
$_GET['replylimit'] = intval($_GET['replylimit']);
$_GET['creditlimit'] = $_GET['creditlimit'] == '' ? '-996' : intval($_GET['creditlimit']);
if($_GET['rushreplyfrom'] > $_GET['rushreplyto'] && !empty($_GET['rushreplyto'])) {
showmessage('post_rushreply_timewrong');
}
$maxposition = C::t('forum_post')->fetch_maxposition_by_tid($this->thread['posttableid'], $this->thread['tid']);
if($this->thread['closed'] == 1 && ((!$_GET['rushreplyfrom'] && !$_GET['rushreplyto']) || ($_GET['rushreplyfrom'] < $_G['timestamp'] && $_GET['rushreplyto'] > $_G['timestamp']) || (!$_GET['rushreplyfrom'] && $_GET['rushreplyto'] > $_G['timestamp']) || ($_GET['stopfloor'] && $_GET['stopfloor'] > $maxposition) )) {
$this->param['threadupdatearr']['closed'] = 0;
} elseif($this->thread['closed'] == 0 && (($_GET['rushreplyfrom'] && $_GET['rushreplyfrom'] > $_G['timestamp']) || ($_GET['rushreplyto'] && $_GET['rushreplyto'] && $_GET['rushreplyto'] < $_G['timestamp']) || ($_GET['stopfloor'] && $_GET['stopfloor'] <= $maxposition) )) {
$this->param['threadupdatearr']['closed'] = 1;
}
if(!empty($_GET['rewardfloor']) && !empty($_GET['stopfloor'])) {
$floors = explode(',', $_GET['rewardfloor']);
if(!empty($floors)) {
foreach($floors AS $key => $floor) {
if(strpos($floor, '*') === false) {
if(intval($floor) == 0) {
unset($floors[$key]);
} elseif($floor > $_GET['stopfloor']) {
unset($floors[$key]);
}
}
}
}
$_GET['rewardfloor'] = implode(',', $floors);
}
$rushdata = array('stopfloor' => $_GET['stopfloor'], 'starttimefrom' => $_GET['rushreplyfrom'], 'starttimeto' => $_GET['rushreplyto'], 'rewardfloor' => $_GET['rewardfloor'], 'creditlimit' => $_GET['creditlimit'], 'replylimit' => $_GET['replylimit']);
C::t('forum_threadrush')->update($this->thread['tid'], $rushdata);
}
}
}
public function before_deletepost() {
global $rushreply;
if($rushreply) {
showmessage('post_edit_delete_rushreply_nopermission', NULL);
}
}
}
?> | mit |
drem-darios/heartbeat | src/main/java/com/drem/heartbeat/common/EventListenerList.java | 10080 | /*
* %W% %E%
*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.drem.heartbeat.common;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.EventListener;
/**
* A class that holds a list of EventListeners. A single instance can be used to
* hold all listeners (of all types) for the instance using the list. It is the
* responsiblity of the class using the EventListenerList to provide type-safe
* API (preferably conforming to the JavaBeans spec) and methods which dispatch
* event notification methods to appropriate Event Listeners on the list. The
* main benefits that this class provides are that it is relatively cheap in the
* case of no listeners, and it provides serialization for event-listener lists
* in a single place, as well as a degree of MT safety (when used correctly).
* Usage example: Say one is defining a class that sends out FooEvents, and one
* wants to allow users of the class to register FooListeners and receive
* notification when FooEvents occur. The following should be added to the class
* definition:
*
* <pre>
* EventListenerList listenerList = new EventListenerList();
* FooEvent fooEvent = null;
*
* public void addFooListener(FooListener l) {
* listenerList.add(FooListener.class, l);
* }
*
* public void removeFooListener(FooListener l) {
* listenerList.remove(FooListener.class, l);
* }
*
* // Notify all listeners that have registered interest for
* // notification on this event type. The event instance
* // is lazily created using the parameters passed into
* // the fire method.
*
* protected void fireFooXXX() {
* // Guaranteed to return a non-null array
* Object[] listeners = listenerList.getListenerList();
* // Process the listeners last to first, notifying
* // those that are interested in this event
* for (int i = listeners.length - 2; i >= 0; i -= 2) {
* if (listeners[i] == FooListener.class) {
* // Lazily create the event:
* if (fooEvent == null)
* fooEvent = new FooEvent(this);
* ((FooListener) listeners[i + 1]).fooXXX(fooEvent);
* }
* }
* }
* </pre>
*
* foo should be changed to the appropriate name, and fireFooXxx to the
* appropriate method name. One fire method should exist for each notification
* method in the FooListener interface.
* <p>
* <strong>Warning:</strong> Serialized objects of this class will not be
* compatible with future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running the
* same version of Swing. As of 1.4, support for long term storage of all
* JavaBeans<sup><font size="-2">TM</font></sup> has been added to the
* <code>java.beans</code> package. Please see {@link java.beans.XMLEncoder}.
*
* @version %I% %G%
* @author Georges Saab
* @author Hans Muller
* @author James Gosling
*/
public class EventListenerList implements Serializable {
private static final long serialVersionUID = -374845298068852567L;
/* A null array to be shared by all empty listener lists */
private final static Object[] NULL_ARRAY = new Object[0];
/* The list of ListenerType - Listener pairs */
protected transient Object[] listenerList = NULL_ARRAY;
/**
* Passes back the event listener list as an array of ListenerType-listener
* pairs. Note that for performance reasons, this implementation passes back
* the actual data structure in which the listener data is stored
* internally! This method is guaranteed to pass back a non-null array, so
* that no null-checking is required in fire methods. A zero-length array of
* Object should be returned if there are currently no listeners. WARNING!!!
* Absolutely NO modification of the data contained in this array should be
* made -- if any such manipulation is necessary, it should be done on a
* copy of the array returned rather than the array itself.
*/
public Object[] getListenerList() {
return listenerList;
}
/**
* Return an array of all the listeners of the given type.
*
* @return all of the listeners of the specified type.
* @exception ClassCastException if the supplied class is not assignable to
* EventListener
* @since 1.3
*/
@SuppressWarnings("unchecked")
public <T extends EventListener> T[] getListeners(Class<T> t) {
Object[] lList = listenerList;
int n = getListenerCount(lList, t);
T[] result = (T[]) Array.newInstance(t, n);
int j = 0;
for (int i = lList.length - 2; i >= 0; i -= 2) {
if (lList[i] == t) {
result[j++] = (T) lList[i + 1];
}
}
return result;
}
/**
* Returns the total number of listeners for this listener list.
*/
public int getListenerCount() {
return listenerList.length / 2;
}
/**
* Returns the total number of listeners of the supplied type for this
* listener list.
*/
public int getListenerCount(Class<?> t) {
Object[] lList = listenerList;
return getListenerCount(lList, t);
}
@SuppressWarnings("rawtypes")
private int getListenerCount(Object[] list, Class t) {
int count = 0;
for (int i = 0; i < list.length; i += 2) {
if (t == (Class) list[i])
count++;
}
return count;
}
/**
* Adds the listener as a listener of the specified type.
*
* @param t the type of the listener to be added
* @param l the listener to be added
*/
public synchronized <T extends EventListener> void add(Class<T> t, T l) {
if (l == null) {
// In an ideal world, we would do an assertion here
// to help developers know they are probably doing
// something wrong
return;
}
if (!t.isInstance(l)) {
throw new IllegalArgumentException("Listener " + l +
" is not of type " + t);
}
if (listenerList == NULL_ARRAY) {
// if this is the first listener added,
// initialize the lists
listenerList = new Object[] {
t, l
};
} else {
// Otherwise copy the array and add the new listener
int i = listenerList.length;
Object[] tmp = new Object[i + 2];
System.arraycopy(listenerList, 0, tmp, 0, i);
tmp[i] = t;
tmp[i + 1] = l;
listenerList = tmp;
}
}
/**
* Removes the listener as a listener of the specified type.
*
* @param t the type of the listener to be removed
* @param l the listener to be removed
*/
public synchronized <T extends EventListener> void remove(Class<T> t, T l) {
if (l == null) {
// In an ideal world, we would do an assertion here
// to help developers know they are probably doing
// something wrong
return;
}
if (!t.isInstance(l)) {
throw new IllegalArgumentException("Listener " + l +
" is not of type " + t);
}
// Is l on the list?
int index = -1;
for (int i = listenerList.length - 2; i >= 0; i -= 2) {
if ((listenerList[i] == t) && (listenerList[i + 1].equals(l) == true)) {
index = i;
break;
}
}
// If so, remove it
if (index != -1) {
Object[] tmp = new Object[listenerList.length - 2];
// Copy the list up to index
System.arraycopy(listenerList, 0, tmp, 0, index);
// Copy from two past the index, up to
// the end of tmp (which is two elements
// shorter than the old list)
if (index < tmp.length)
System.arraycopy(listenerList, index + 2, tmp, index,
tmp.length - index);
// set the listener array to the new array or null
listenerList = (tmp.length == 0) ? NULL_ARRAY : tmp;
}
}
// Serialization support.
@SuppressWarnings("rawtypes")
private void writeObject(ObjectOutputStream s) throws IOException {
Object[] lList = listenerList;
s.defaultWriteObject();
// Save the non-null event listeners:
for (int i = 0; i < lList.length; i += 2) {
Class t = (Class) lList[i];
EventListener l = (EventListener) lList[i + 1];
if ((l != null) && (l instanceof Serializable)) {
s.writeObject(t.getName());
s.writeObject(l);
}
}
s.writeObject(null);
}
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
listenerList = NULL_ARRAY;
s.defaultReadObject();
Object listenerTypeOrNull;
while (null != (listenerTypeOrNull = s.readObject())) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
EventListener l = (EventListener) s.readObject();
add((Class<EventListener>) Class.forName((String) listenerTypeOrNull, true, cl), l);
}
}
/**
* Returns a string representation of the EventListenerList.
*/
@SuppressWarnings("rawtypes")
public String toString() {
Object[] lList = listenerList;
String s = "EventListenerList: ";
s += lList.length / 2 + " listeners: ";
for (int i = 0; i <= lList.length - 2; i += 2) {
s += " type " + ((Class) lList[i]).getName();
s += " listener " + lList[i + 1];
}
return s;
}
}
| mit |
pwnbus/scoring_engine | tests/scoring_engine/web/web_test.py | 2286 | import importlib
from flask import render_template as render_template_orig
from scoring_engine.web import app
from scoring_engine.models.team import Team
from scoring_engine.models.user import User
from tests.scoring_engine.unit_test import UnitTest
from mock import MagicMock, call
class WebTest(UnitTest):
def setup(self):
super(WebTest, self).setup()
self.app = app
self.app.config['TESTING'] = True
self.app.config['WTF_CSRF_ENABLED'] = False
self.client = self.app.test_client()
self.ctx = self.app.app_context()
self.ctx.push()
view_name = self.__class__.__name__[4:]
self.view_module = importlib.import_module('scoring_engine.web.views.' + view_name.lower(), '*')
self.view_module.render_template = MagicMock()
self.mock_obj = self.view_module.render_template
self.mock_obj.side_effect = lambda *args, **kwargs: render_template_orig(*args, **kwargs)
def teardown(self):
self.ctx.pop()
super(WebTest, self).teardown()
def build_args(self, *args, **kwargs):
return call(*args, **kwargs)
def verify_auth_required(self, path):
resp = self.client.get(path)
assert resp.status_code == 302
assert '/login?' in resp.location
def verify_auth_required_post(self, path):
resp = self.client.post(path)
assert resp.status_code == 302
assert '/login?' in resp.location
def login(self, username, password):
return self.client.post("/login", data={
"username": username,
"password": password,
}, follow_redirects=True)
def logout(self):
return self.get("/logout", follow_redirects=True)
def auth_and_get_path(self, path):
self.client.post("/login", data={
"username": 'testuser',
"password": 'testpass',
})
return self.client.get(path)
def create_default_user(self):
team1 = Team(name="Team 1", color="White")
self.session.add(team1)
user1 = User(username='testuser', password='testpass', team=team1)
self.session.add(user1)
self.session.commit()
return user1
def test_debug(self):
assert type(self.app.debug) is bool
| mit |
nuzzio/grunt-strip-code | test/fixtures/legacy_start_end.js | 174 | /* start-test-block */
// call a func that does something
/* end-test-block */
function free(a, b, c /* start-test-block */ , d /* end-test-block */) {
// do something
}
| mit |
wizawu/1c | @types/jdk/java.net.SocketOption.d.ts | 153 | declare namespace java {
namespace net {
interface SocketOption<T> {
name(): java.lang.String
type(): java.lang.Class<T>
}
}
}
| mit |
EffectHub/effecthub | application/views/mail/mailboxsend.php | 6502 | <?php $this->load->view('header') ?>
<div id="content" class="group">
<div class="notice-alert">
<h3><!-- message goes here --></h3>
<a href="http://effecthub.com/#" class="close">
<img alt="Icon-x-30-white" src="<?=base_url()?>images/icon-x-30-white.png" width="15">
</a>
</div>
<div id="main" class="main">
<?php if (!$this->session->userdata('id')){ ?>
<div class="full full-pitch group">
<h1 class="compact">
<strong>EffectHub is connecting the world's gaming designers and developers.</strong>
<a href="<?=site_url('register')?>" class="form-sub tagline-action">Sign up</a>
<a rel="tipsy" original-title="Sign up with your Twitter account" class="auth-twitter tagline-action" href="<?=site_url('login/twitter')?>"></a>
<a rel="tipsy" original-title="Sign up with your Facebook account" class="auth-facebook tagline-action" href="<?=site_url('login/facebook')?>"></a>
<a rel="tipsy" original-title="Sign up with your Weibo account" class="auth-weibo tagline-action" href="<?=site_url('login/sina')?>"></a>
</h1>
</div>
<?php }?>
<ul class="tabs">
<li class="<?php echo $feature=='Profile'?'active':'' ?>">
<a href="<?=site_url('user/'.$this->session->userdata('id'))?>" class="has-dd">My Profile</a>
</li>
<li class="<?php echo $feature=='Mailbox'?'active':'' ?>">
<a href="<?=site_url('user/checkmail/'.$this->session->userdata('id'))?>" class="has-dd">My Mail Box</a>
</li>
<li class="<?php echo $feature=='Notification'?'active':'' ?>">
<a href="<?=site_url('user/notice/'.$this->session->userdata('id'))?>" class="has-dd">Notification</a>
</li>
</ul>
<ol class="effecthubs group" style="margin-top:30px">
<form method="post" action="<?=site_url('user/operatechosedmail/0')?>">
<div class="mailstyle" name="<?php echo $this->session->userdata('id')?>">
<div class="aside" style="width:100%">
<a class="form-sub" href="<?=site_url('user/choosefollowing/'.$this->session->userdata('id'))?>">Write letter to my following</a>
<a class="form-sub" href="<?=site_url('user/showfollowing/'.$this->session->userdata('id'))?>">Go to list of my following</a>
</div>
<div class="mailmain" style="margin-top:30px">
<div class="tabs">
<a href="<?=site_url('user/checkmail/'.$this->session->userdata('id'))?>" class="junkmailstyle">Inbox(<?php echo $unreadcount; ?> unread)</a>
<a href="<?=site_url('user/checkjunkmail/'.$this->session->userdata('id'))?>" class="junkmailstyle">Junk mail(<?php echo $unreadjunkcount; ?> unread)</a>
<a href="<?=site_url('user/checksendmail/'.$this->session->userdata('id'))?>" class="inboxstyle">Outbox</a>
<!--<div style="float: right;position: relative;">
Select:
<select id="mailcatagory" name="mailcatagory">
<option value="all" selected="selected">All Mail</option>
<option value="Unread">Unread Mail</option>
<option value="read">Read Mail</option>
</select>
</div>-->
</div>
<div class="mailcontent">
<ul>
<?php foreach($mail_list as $_mail): ?>
<li id="<?php echo $_mail['id']; ?>">
<div class="picture">
<a href="<?=site_url('user/'.$_mail['sender_id'])?>"><img src="<?php echo $_mail['author_pic']; ?>" width="45px" height="45px"></a>
</div>
<div class="title">
<div class="sender">
<span class="time"><?php echo tranTime(strtotime($_mail['timestamp'])); ?></span>
<span class="from"><a href="<?=site_url('user/readmail/'.$_mail['id'].'/receiver_id')?>" style="color:#A1A1A1"><?php echo $_mail['author_name']; ?></a></span>
</div>
<div class="sender">
<span class="time">
<!--<a rel="direct" title="Move to Junk Mail?" class="operate_link" href="<?=site_url('user/movesendmail/'.$_mail['id'])?>">Move to Junk Mail</a>-->
<a title="Are you sure to delete this mail?" class="operate_link" href="<?=site_url('user/deletesendmail/'.$_mail['id'])?>" >Delete</a>
<input type="checkbox" name="choosemail[]" value="<?php echo $_mail['id']; ?>">
</span>
<span class="from"><a href="<?=site_url('user/readmail/'.$_mail['id'].'/receiver_id')?>" class="url"><?php echo $_mail['content']; ?></a></span>
</div>
</div>
</li>
<?php endforeach; ?>
</ul>
<div class='paragraphstyle' style='font-weight: bold;font-size:16px;padding:10px;margin-bottom:20px'><?php echo $this->pagination->create_links();?></div>
</div>
<div class="mailoperate">
<input type="submit" name="deletechosedmail" onclick="return confirm('Are you sure to delete choosed mail?')" value="Delete">
<!--<input type="submit" name="movechosedmail" value="Move to Junk Mail">-->
<!--<a href="<?=site_url('user/markallread/1')?>" style="margin-left:22px;">Mark all as Read</a>-->
</div>
</div>
</div>
</form>
</ol>
<div class="page">
</div>
</div> <!-- /main -->
<div class="secondary">
<div class="what-is-pro-search">
<h3>Search <span class="meta">Authors</span></h3>
<form name="author_search_form" class="gen-form" action="<?=site_url('author/authorSearch')?>" method="post" onkeydown="if(event.keyCode==13){document.author_search_form.submit();}">
<div id='main-search' class='clearfix'>
<div id='main-search-box' class='clearfix'>
<fieldset>
<input type="text" style="background: rgba(255, 255, 255, 1);" id='particle_search_field' name="search" onblur="if (this.value == '') {this.value = 'Search author';}" onfocus="if (this.value == 'Search author') {this.value = '';}" value="Search author" x-webkit-speech="" speech="">
</fieldset>
</div>
</div>
</form>
</div>
</div>
</div> <!-- /content -->
</div></div> <!-- /wrap -->
<?php $this->load->view('footer') ?> | mit |
billhj/Etoile-java | OdeApp/src/org/etoile/animation/ode/JointType.java | 1430 | /*
* The MIT License
*
* Copyright 2014 Jing Huang <gabriel.jing.huang@gmail.com or jing.huang@telecom-paristech.fr>.
*
* 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.
*/
package org.etoile.animation.ode;
/**
*
* @author Jing Huang * <gabriel.jing.huang@gmail.com or jing.huang@telecom-paristech.fr>
*/
public enum JointType {
FIXED, HINGE, UNIVERSAL, BALL;
}
| mit |
rocktavious/DevToolsLib | DTL/api/decorators.py | 6338 | import sys
import time
import cProfile
import pstats
import datetime
from functools import wraps
from DTL.api import loggingUtils, threadlib, Path
#------------------------------------------------------------
#------------------------------------------------------------
class PreAndPost(object):
__metaclass__ = loggingUtils.LoggingMetaclass
def __init__(self, func):
self.func = func
wraps(func)(self)
def __get__(self, obj, type=None):
return self.__class__(self.func.__get__(obj, type))
def __call__(self, *args, **kwds):
return self.call(*args, **kwds)
def pre_call(self, *args, **kwds):
pass
def call(self, *args, **kwds):
return self.func(*args, **kwds)
def post_call(self, *args, **kwds):
pass
def error(self, retval, *args, **kwds):
self.log.exception("")
#------------------------------------------------------------
#------------------------------------------------------------
class Safe(PreAndPost):
def __init__(self, func):
super(Safe, self).__init__(func)
def __call__(self, *args, **kwds):
retval = None
try:
self.pre_call(*args, **kwds)
retval = self.call(*args, **kwds)
except KeyboardInterrupt:
raise Exception("Keyboard interruption detected")
except:
self.error(retval, *args, **kwds)
finally:
try:
self.post_call(retval, *args, **kwds)
except:
try:
self.error(retval, *args, **kwds)
except:
pass
return retval
def error(self, retval, *args, **kwds):
if self.log.handlers :
self.log.exception("")
#------------------------------------------------------------
#------------------------------------------------------------
class Timer(Safe):
"""A decorator which times a callable but also provides some timing functions
to the func through itself being passed as a param to the function call"""
def __init__(self, func):
super(Timer, self).__init__(func)
self._name = str(self.func.__name__)
self.reset()
def reset(self):
self._starttime = datetime.datetime.now()
self._lapStack = []
self._records = []
self._laps = []
def recordLap(self, elapsed, message):
self._records.append('\tlap: {0} | {1}'.format(elapsed, message))
def startLap(self, message):
self._lapStack.append((message,datetime.datetime.now()))
return True
def stopLap(self):
if not self._lapStack:
return False
curr = datetime.datetime.now()
message, start = self._lapStack.pop()
#process the elapsed time
elapsed = str(curr - start)
if not '.' in elapsed:
elapsed += '.'
while len(elapsed) < 14 :
elapsed += '0'
self.recordLap(elapsed, message)
def newLap(self, message):
""" Convenience method to stop the current lap and create a new lap """
self.stopLap()
self.startLap(message)
def stop(self):
#stop all the laps if not stopped
while self._lapStack:
self.stopLap()
total = str(datetime.datetime.now() - self._starttime)
#output the logs
self.log.info('Time:{0} | {1} Stopwatch'.format(total,self._name))
for record in self._records :
self.log.info(record)
return True
def pre_call(self, *args, **kwds):
self.startLap(self.func.__name__)
def call(self, *args, **kwds):
return self.func(timer=self, *args, **kwds)
def post_call(self, *args, **kwds):
self.stop()
#------------------------------------------------------------
#------------------------------------------------------------
class CommandTicker(Safe):
TICKS = ['[. ]', '[.. ]', '[...]', '[ ..]', '[ .]', '[ ]']
def __init__(self, func, *args, **kwds):
"""A decorater that shows a command line progress bar for commandline operations that will take a long time"""
super(CommandTicker, self).__init__(func, *args, **kwds)
self.ticker_thread = threadlib.ThreadedProcess(*args, **kwds)
self.ticker_thread.run = self.run
def run(self):
i = 0
first = True
while self.ticker_thread.isMainloopAlive:
time.sleep(.25)
if i == len(self.TICKS):
first = False
i = 0
if not first:
sys.stderr.write("\r{0}\r".format(self.TICKS[i]))
sys.stderr.flush()
i += 1
sys.stderr.flush()
def pre_call(self, *args, **kwds):
self.ticker_thread.start()
def post_call(self, retval, *args, **kwds):
self.ticker_thread.stop()
sys.stderr.flush()
sys.stderr.write(" ")
sys.stderr.flush()
#------------------------------------------------------------
class Profile(Safe):
"""A decorator which profiles a callable."""
def __init__(self, func, sort='cumulative', strip_dirs=False):
super(Profile, self).__init__(func)
self.sort = sort
self.strip_dirs = strip_dirs
base_path = Path.getTempPath().join('profile')
base_path.makedirs()
self.profile_path = base_path.join('{0}.{1}.profile'.format(func.__module__, func.__name__))
self.stats_path = base_path.join('{0}.{1}.log'.format(func.__module__, func.__name__))
self.profile = cProfile.Profile()
def call(self, *args, **kwds):
return self.profile.runcall(self.func, *args, **kwds)
def post_call(self, retval, *args, **kwds):
stream = open(self.stats_path, 'w')
self.profile.dump_stats(self.profile_path)
stats = pstats.Stats(self.profile_path, stream=stream)
if self.strip_dirs:
stats.strip_dirs()
if isinstance(self.sort, (tuple, list)):
stats.sort_stats(*self.sort)
else:
stats.sort_stats(self.sort)
stats.print_stats()
self.profile_path.remove() | mit |
VAGAScom/basquiat | lib/basquiat/adapters/rabbitmq/requeue_strategies/dead_lettering.rb | 1630 | # frozen_string_literal: true
module Basquiat
module Adapters
class RabbitMq
class DeadLettering < BaseStrategy
class << self
attr_reader :options
def setup(opts)
@options = {
session: {
queue: {
options: {
'x-dead-letter-exchange' => opts.fetch(:exchange, 'basquiat.dlx')
}
}
},
dlx: { ttl: opts.fetch(:ttl, 1_000) }
}
end
def session_options
options.fetch :session
end
end
def initialize(session)
super
setup_dead_lettering
end
def run(message)
catch :skip_processing do
check_incoming_messages(message.props.headers)
yield
end
public_send(message.action, message)
end
private
def check_incoming_messages(headers)
headers &&
headers['x-death'][1]['queue'] != session.queue.name &&
throw(:skip_processing)
end
def options
self.class.options
end
def setup_dead_lettering
dlx = session.channel.topic('basquiat.dlx')
queue = session.channel.queue('basquiat.dlq',
arguments: { 'x-dead-letter-exchange' => session.exchange.name,
'x-message-ttl' => options[:dlx][:ttl] })
queue.bind(dlx, routing_key: '#')
end
end
end
end
end
| mit |
bredele/drag | test/drag.js | 397 |
/**
* Test dependencies.
*/
var assert = require('assert');
var drag = require('..');
var round = require('round');
describe("drag forces", function() {
describe('dry air', function() {
describe("ball", function() {
var area = 0.0001 * Math.PI * 15 * 15;
it('velocity 10 m.s-2', function() {
assert.equal(round(drag(10, 0.47, area), 6), 2.000126);
});
});
});
});
| mit |
mjrasobarnett/ucnsim | geom/source_tube/sourcetube_gaps.C | 8275 | // This is a model of the 'Real' cryoEDM sourcetube - 25/01/2010
#include "TGeoManager.h"
#include "TGLViewer.h"
#include "TGLCamera.h"
#include "TGLPerspectiveCamera.h"
#include "../../include/Units.h"
#include "../../include/Constants.h"
#include "../../include/Materials.h"
#include "../../include/GeomParameters.h"
Bool_t Build_Geom(const TGeoManager* geoManager);
Bool_t Draw_Geom(const TGeoManager* geoManager);
using namespace GeomParameters;
//__________________________________________________________________________
Int_t sourcetube_gaps()
{
// Create the geoManager
TGeoManager* geoManager = new TGeoManager("GeoManager","Geometry Manager");
// Build and write to file the simulation and visualisation geoms
Build_Geom(geoManager);
Draw_Geom(geoManager);
return 0;
}
//__________________________________________________________________________
Bool_t Build_Geom(const TGeoManager* geoManager)
{
// -------------------------------------
// BUILDING GEOMETRY
// Materials - Define the materials used. Leave the neutron properties
// to be defined on a run-by-run basis
Materials::BuildMaterials(geoManager);
TGeoMedium* beryllium = geoManager->GetMedium("Beryllium");
TGeoMedium* blackhole = geoManager->GetMedium("BlackHole");
TGeoMedium* heliumII = geoManager->GetMedium("HeliumII");
// -------------------------------------
// -- Making Top Volume
Box* topShape = new Box("Top",100,100,100);
BlackHole* top = new BlackHole("Top", topShape, blackhole);
geoManager->SetTopVolume(top);
top->SetVisibility(kFALSE);
// -- Make the boundary volume in which all the others sit
// -- This is what we will be reflecting off all the time
Double_t surfaceRoughness = 0.1;
Box* chamberShape = new Box("Chamber",10,10,10);
Boundary* chamber = new Boundary("Chamber", chamberShape, beryllium, surfaceRoughness);
chamber->SetLineColor(kOrange-7);
chamber->SetLineWidth(1);
chamber->SetVisibility(kFALSE);
chamber->SetTransparency(80);
// Add to geom
top->AddNode(chamber,1);
// -------------------------------------
// -- SOURCE TUBE
// -- Source tube has 13 segments, all of which are identical
// -- (except one which has a hole in the top)
Double_t segmentYPosition = sourceSegHalfLength;
for (Int_t segNum = 1; segNum <= 13; segNum++) {
// -- Make a SourceTube Segment
Char_t sourceMatrixName[20], sourceSegName[20], sourceGapMatrixName[20];
sprintf(sourceSegName, "SourceSeg%d", segNum);
Tube *sourceSegShape = new Tube(sourceSegName, sourceSegRMin, sourceSegRMax, sourceSegHalfLength);
TrackingVolume* sourceSeg = new TrackingVolume(sourceSegName, sourceSegShape, heliumII);
sourceSeg->SetLineColor(kAzure-4);
sourceSeg->SetLineWidth(1);
sourceSeg->SetVisibility(kTRUE);
sourceSeg->SetTransparency(20);
// -- Define SourceTube matrix
TGeoRotation segmentRot("SegmentRot",0,sourceSegAngle,0); // phi, theta, psi
TGeoTranslation segmentTra("SegmentTra",0.,segmentYPosition,0.); // x, y, z
TGeoCombiTrans segmentCom(segmentTra,segmentRot);
TGeoHMatrix segmentMat = segmentCom;
sprintf(sourceMatrixName, "SourceMatrix%d", segNum);
segmentMat.SetName(sourceMatrixName);
// Add SourceTube segment to geometry
chamber->AddNode(sourceSeg, segNum, new TGeoHMatrix(segmentMat));
// Shift next segment along by length of segment
segmentYPosition += 2.0*sourceSegHalfLength;
}
// -------------------------------------
// -- SOURCE TUBE GAPS
// -- Create 12 gaps between each source tube segment
Double_t gapYPosition = 2.0*sourceSegHalfLength;
for (Int_t segNum = 1; segNum <= 13; segNum++) {
// -- Make a Gap between Segments
Char_t sourceGapMatrixName[20], sourceSegGapName[20];
sprintf(sourceSegGapName, "SourceSegGap%d", segNum);
Tube *sourceSegGapShape = new Tube(sourceSegGapName, sourceSegGapRMin, sourceSegGapRMax, sourceSegGapHalfLength);
BlackHole* sourceSegGap = new BlackHole(sourceSegGapName, sourceSegGapShape, blackhole);
sourceSegGap->SetLineColor(kGray);
sourceSegGap->SetLineWidth(1);
sourceSegGap->SetVisibility(kTRUE);
sourceSegGap->SetTransparency(20);
// -- Define SourceTube matrix
TGeoRotation segmentGapRot("SegmentGapRot",0,sourceSegGapAngle,0); // phi, theta, psi
TGeoTranslation segmentGapTra("SegmentGapTra",0.,gapYPosition,0.); // x, y, z
TGeoCombiTrans segmentGapCom(segmentGapTra,segmentGapRot);
TGeoHMatrix segmentGapMat = segmentGapCom;
sprintf(sourceGapMatrixName, "SourceGapMatrix%d", segNum);
segmentGapMat.SetName(sourceGapMatrixName);
// Add SourceTube Gap segment to geometry
chamber->AddNode(sourceSegGap, segNum, new TGeoHMatrix(segmentGapMat));
// Shift next segment along by length of segment
gapYPosition += 2.0*sourceSegHalfLength;
}
// -------------------------------------
// -- SOURCE VALVE
// Valve entrance volume is a shorter source-tube segment-like that connects
// the valve volume to the source
Tube *valveVolEntranceShape = new Tube("ValveVolEntrance", valveVolEntranceRMin, valveVolEntranceRMax, valveVolEntranceHalfLength);
TrackingVolume* valveVolEntrance = new TrackingVolume("ValveVolEntrance", valveVolEntranceShape, heliumII);
valveVolEntrance->SetLineColor(kTeal-3);
valveVolEntrance->SetLineWidth(1);
valveVolEntrance->SetVisibility(kTRUE);
valveVolEntrance->SetTransparency(20);
// -- Define the Valve volume entrance
TGeoRotation valveVolEntranceRot("ValveVolEntranceRot",0,valveVolEntranceAngle,0);
TGeoTranslation valveVolEntranceTra("ValveVolEntranceTra",0.,valveVolEntranceYDisplacement,0.);
TGeoCombiTrans valveVolEntranceCom(valveVolEntranceTra,valveVolEntranceRot);
TGeoHMatrix valveVolEntranceMat = valveVolEntranceCom;
chamber->AddNode(valveVolEntrance, 1, new TGeoHMatrix(valveVolEntranceMat));
// -------------------------------------
// -- Close Geometry
geoManager->CloseGeometry();
// -------------------------------------
// -- Write out geometry to file
const char *fileName = "$(UCN_GEOM)/sourcetube/sourcetube_gaps.root";
cerr << "Simulation Geometry Built... Writing to file: " << fileName << endl;
geoManager->Export(fileName);
return kTRUE;
}
//__________________________________________________________________________
Bool_t Draw_Geom(const TGeoManager* geoManager)
{
// -------------------------------------
// -- Draw the vis-geometry in OpenGLViewer
TCanvas* canvas = new TCanvas("GeomCanvas","Canvas for visualisation of EDM Geom",60,40,600,600);
canvas->cd();
geoManager->GetTopVolume()->Draw("ogl");
geoManager->SetVisLevel(4); // Default draws 4 levels down volume heirarchy
geoManager->SetVisOption(0); // Default is 1, but 0 draws all the intermediate volumes not just the final bottom layer
geoManager->ViewLeaves(kTRUE);
// -- Get the GLViewer so we can manipulate the camera
TGLViewer * glViewer = dynamic_cast<TGLViewer*>(gPad->GetViewer3D());
// -- Select Draw style
glViewer->SetStyle(TGLRnrCtx::kFill); // TGLRnrCtx::kFill, TGLRnrCtx::kOutline, TGLRnrCtx::kWireFrame
// -- Set Background colour
glViewer->SetClearColor(TColor::kWhite);
// -- Set Lights - turn some off if you wish
// TGLLightSet* lightSet = glViewer->GetLightSet();
// lightSet->SetLight(TGLLightSet::kLightLeft, kFALSE);
// -- Set Camera type
// kCameraPerspXOZ, kCameraPerspYOZ, kCameraPerspXOY, kCameraOrthoXOY
// kCameraOrthoXOZ, kCameraOrthoZOY, kCameraOrthoXnOY, kCameraOrthoXnOZ, kCameraOrthoZnOY
TGLViewer::ECameraType camera = 2;
glViewer->SetCurrentCamera(camera);
glViewer->CurrentCamera().SetExternalCenter(kTRUE);
Double_t cameraCentre[3] = {0., 0., 0.};
glViewer->SetPerspectiveCamera(camera,4,100,&cameraCentre[0],0,0);
// -- Draw Reference Point, Axes
Double_t refPoint[3] = {0.,0.,0.};
// Int_t axesType = 0(Off), 1(EDGE), 2(ORIGIN), Bool_t axesDepthTest, Bool_t referenceOn, const Double_t referencePos[3]
glViewer->SetGuideState(0, kFALSE, kFALSE, refPoint);
glViewer->UpdateScene();
return kTRUE;
}
| mit |
certong0507/shoppingu | public/js/controllers/users/userprofilemain.js | 943 | 'use strict';
angular.module('mean.articles')
.controller('UserProfileMainController', ['$scope', 'Global', '$stateParams', '$state', 'fileReader', function($scope, Global, $stateParams, $state, fileReader){
$scope.global = Global;
$scope.accountMenu = [{accId: 'a1',accName: 'Profiles', accLink: "userprofile", accIcon: "icon-head"},
{accId: 'a2',accName: 'Addresses', accLink: "address", accIcon: "icon-map"},
{accId: 'a3',accName: 'Orders', accLink: "order", accIcon: "icon-bag"},
{accId: 'a4',accName: 'Posts', accLink: "post", accIcon: "icon-bag"}];
$scope.selectedMenu = function (index) {
$('#' + $scope.accountMenu[index].accId).addClass("active");
};
$scope.imageSrc = null;
$scope.$on("fileProgress", function(e, progress) {
$scope.progress = progress.loaded / progress.total;
});
}]);
| mit |
thilina01/kpi-client | src/app/pages/absenteeism/components/absenteeismTable/index.ts | 46 | export * from './absenteeismTable.component';
| mit |
danshapir/ember-bootstrap-components | app/components/bs-component.js | 77 | export { default } from 'ember-bootstrap-components/components/bs-component'; | mit |
vvlad/lita-capistrano | lib/lita/capistrano/application.rb | 1087 | require 'net/ssh'
module Lita # :nodoc:
module Capistrano # :nodoc:
class Application
attr_reader :name, :environment, :ssh
def initialize(name:, environment:, ssh: )
@name = name
@ssh = ssh
@environment = environment
end
def deploy(bot)
bot.reply "Deploying application #{name} on #{environment}"
Net::SSH.start(ssh[:server], ssh[:user], ssh[:ssh_options]) do |connection|
connection.open_channel do |ch|
ch.exec "#{name} #{environment}" do |_ch, success|
return bot.reply('could not execute command') unless success
ch.on_data do |_c, data|
Lita.logger.debug(data)
bot.reply data.force_encoding("utf-8")
end
ch.on_extended_data do |_c, _type, data|
Lita.logger.error(data)
bot.reply data.force_encoding("utf-8")
end
end
end.wait
end
bot.reply "Finished deploying #{name} on #{environment}"
end
end
end
end
| mit |
adam4813/Sigma | src/components/GLMesh.cpp | 20443 | #include "components/GLMesh.h"
#ifndef __APPLE__
#include "GL/glew.h"
#endif
#include "strutils.h"
#include <algorithm>
#include <stdexcept>
#include <fstream>
#include <iostream>
#include <sstream>
#include "resources/GLTexture.h"
#include "systems/OpenGLSystem.h"
namespace Sigma{
// static member initialization
const std::string GLMesh::DEFAULT_SHADER = "shaders/mesh_deferred";
GLMesh::GLMesh(const id_t entityID) : IGLComponent(entityID) {
memset(&this->buffers, 0, sizeof(this->buffers));
this->vao = 0;
this->drawMode = GL_TRIANGLES;
this->ElemBufIndex = 2;
this->ColorBufIndex = 1;
this->VertBufIndex = 0;
this->NormalBufIndex = 3;
this->UVBufIndex = 4;
}
void GLMesh::InitializeBuffers() {
if(!this->shader) {
assert(0 && "Shader must be loaded before buffers can be initialized.");
}
// We must create a vao and then store it in our GLMesh.
if (this->vao == 0) {
glGenVertexArrays(1, &this->vao); // Generate the VAO
}
glBindVertexArray(this->vao); // Bind the VAO
if (this->verts.size() > 0) {
if (this->buffers[this->VertBufIndex] == 0) {
glGenBuffers(1, &this->buffers[this->VertBufIndex]); // Generate the vertex buffer.
}
glBindBuffer(GL_ARRAY_BUFFER, this->buffers[this->VertBufIndex]); // Bind the vertex buffer.
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * this->verts.size(), &this->verts.front(), GL_STATIC_DRAW); // Stores the verts in the vertex buffer.
GLint posLocation = glGetAttribLocation((*shader).GetProgram(), "in_Position"); // Find the location in the shader where the vertex buffer data will be placed.
glVertexAttribPointer(posLocation, 3, GL_FLOAT, GL_FALSE, 0, 0); // Tell the VAO the vertex data will be stored at the location we just found.
glEnableVertexAttribArray(posLocation); // Enable the VAO line for vertex data.
}
if (this->texCoords.size() > 0) {
if (this->buffers[this->UVBufIndex] == 0) {
glGenBuffers(1, &this->buffers[this->UVBufIndex]); // Generate the vertex buffer.
}
glBindBuffer(GL_ARRAY_BUFFER, this->buffers[this->UVBufIndex]); // Bind the vertex buffer.
glBufferData(GL_ARRAY_BUFFER, sizeof(TexCoord) * this->texCoords.size(), &this->texCoords.front(), GL_STATIC_DRAW); // Stores the verts in the vertex buffer.
GLint uvLocation = glGetAttribLocation((*shader).GetProgram(), "in_UV"); // Find the location in the shader where the vertex buffer data will be placed.
glVertexAttribPointer(uvLocation, 2, GL_FLOAT, GL_FALSE, 0, 0); // Tell the VAO the vertex data will be stored at the location we just found.
glEnableVertexAttribArray(uvLocation); // Enable the VAO line for vertex data.
}
if (this->colors.size() > 0) {
if (this->buffers[this->ColorBufIndex] == 0) {
glGenBuffers(1, &this->buffers[this->ColorBufIndex]);
}
glBindBuffer(GL_ARRAY_BUFFER, this->buffers[this->ColorBufIndex]);
glBufferData(GL_ARRAY_BUFFER, sizeof(Color) * this->colors.size(), &this->colors.front(), GL_STATIC_DRAW);
GLint colLocation = glGetAttribLocation((*shader).GetProgram(), "in_Color");
glVertexAttribPointer(colLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(colLocation);
}
if (this->faces.size() > 0) {
if (this->buffers[this->ElemBufIndex] == 0) {
glGenBuffers(1, &this->buffers[this->ElemBufIndex]); // Generate the element buffer.
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->buffers[this->ElemBufIndex]); // Bind the element buffer.
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Face) * this->faces.size(), &this->faces.front(), GL_STATIC_DRAW); // Store the faces in the element buffer.
}
if (this->vertNorms.size() > 0) {
if (this->buffers[this->NormalBufIndex] == 0) {
glGenBuffers(1, &this->buffers[this->NormalBufIndex]);
}
glBindBuffer(GL_ARRAY_BUFFER, this->buffers[this->NormalBufIndex]);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex)*this->vertNorms.size(), &this->vertNorms[0], GL_STATIC_DRAW);
GLint normalLocation = glGetAttribLocation((*shader).GetProgram(), "in_Normal");
glVertexAttribPointer(normalLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(normalLocation);
}
glBindVertexArray(0); // Reset the buffer binding because we are good programmers.
this->shader->Use();
this->shader->AddUniform("in_Model");
this->shader->AddUniform("in_View");
this->shader->AddUniform("in_Proj");
this->shader->AddUniform("texEnabled");
this->shader->AddUniform("ambientTexEnabled");
this->shader->AddUniform("diffuseTexEnabled");
this->shader->AddUniform("texAmb");
this->shader->AddUniform("texDiff");
this->shader->AddUniform("specularHardness");
this->shader->UnUse();
}
void GLMesh::Render(glm::mediump_float *view, glm::mediump_float *proj) {
glm::mat4 modelMatrix = this->Transform()->GetMatrix();
//if(this->parentTransform != 0) {
// modelMatrix = this->parentTransform->GetMatrix() * modelMatrix;
//}
this->shader->Use();
glUniformMatrix4fv((*this->shader)("in_Model"), 1, GL_FALSE, &modelMatrix[0][0]);
glUniformMatrix4fv((*this->shader)("in_View"), 1, GL_FALSE, view);
glUniformMatrix4fv((*this->shader)("in_Proj"), 1, GL_FALSE, proj);
glBindVertexArray(this->Vao());
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->GetBuffer(this->ElemBufIndex));
if(this->cull_face == 0) {
glDisable(GL_CULL_FACE);
}
else {
glCullFace(this->cull_face);
}
glActiveTexture(GL_TEXTURE0);
size_t prev = 0;
for (int i = 0, cur = this->MeshGroup_ElementCount(0); cur != 0; prev = cur, cur = this->MeshGroup_ElementCount(++i)) {
if (this->faceGroups.size() > 0) {
Material& mat = this->mats[this->faceGroups[prev]];
if (mat.ambientMap) {
glUniform1i((*this->shader)("texEnabled"), 1);
glUniform1i((*this->shader)("ambientTexEnabled"), 1);
glUniform1i((*this->shader)("texAmb"), 1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, mat.ambientMap);
} else {
glUniform1i((*this->shader)("ambientTexEnabled"), 0);
}
if (mat.diffuseMap) {
glUniform1i((*this->shader)("texEnabled"), 1);
glUniform1i((*this->shader)("diffuseTexEnabled"), 1);
glUniform1i((*this->shader)("texDiff"), 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mat.diffuseMap);
} else {
glUniform1i((*this->shader)("diffuseTexEnabled"), 0);
}
glUniform1f((*this->shader)("specularHardness"), mat.hardness);
}
else {
glUniform1i((*this->shader)("texEnabled"), 0);
glUniform1i((*this->shader)("diffuseTexEnabled"), 0);
glUniform1i((*this->shader)("ambientTexEnabled"), 0);
}
glDrawElements(this->DrawMode(), cur, GL_UNSIGNED_INT, (void*)prev);
}
// reset defaults
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
this->shader->UnUse();
} // function Render
bool operator ==(const VertexIndices &lhs, const VertexIndices &rhs) {
return (lhs.vertex==rhs.vertex &&
lhs.normal==rhs.normal &&
lhs.uv==rhs.uv &&
lhs.color==rhs.color);
}
bool GLMesh::LoadMesh(std::string fname) {
// Extract the path from the filename.
std::string path;
if (fname.find("/") != std::string::npos) {
path = fname.substr(0, fname.find_last_of("/") + 1); // Keep the separator.
}
else {
path = fname.substr(0, fname.find_last_of("\\") + 1); // Keep the separator.
}
unsigned int current_color = 0;
std::vector<FaceIndices> temp_face_indices;
std::vector<VertexIndices> unique_vertices;
std::vector<Vertex> temp_verts;
std::vector<TexCoord> temp_uvs;
std::vector<Vertex> temp_normals;
std::vector<Color> temp_colors;
std::string currentMtlGroup = "";
std::string line;
// Attempt to load file
std::ifstream in(fname, std::ios::in);
if (!in) {
LOG_WARN << "Cannot open mesh " << fname;
return false;
}
// Default color if no material is provided is white
temp_colors.push_back(Color(1.0f, 1.0f, 1.0f));
// Parse line by line
while (getline(in, line)) {
// strip whitespace (strutils.h)
line = trim(line);
if (line.substr(0,2) == "v ") { // Vertex position
float x,y,z;
std::istringstream s(line.substr(2));
s >> x; s >> y; s >> z;
temp_verts.push_back(Vertex(x, y, z));
}
else if (line.substr(0,2) == "vt") { // Vertex tex coord
float u, v = 0.0f;
std::istringstream s(line.substr(2));
s >> u; s >> v;
temp_uvs.push_back(TexCoord(u,v));
}
else if (line.substr(0,2) == "vn") { // Vertex normal
float x, y, z;
std::istringstream s(line.substr(2));
s >> x; s >> y; s >> z;
temp_normals.push_back(Vertex(x,y,z));
}
else if (line.substr(0,2) == "f ") { // Face
FaceIndices current_face;
bool has_vert_indices=false, has_uv_indices=false, has_normal_indices=false;
short indicies[3][3];
std::string cur = line.substr(2, line.find(' ', 2) - 2);
std::string left = line.substr(line.find(' ', 2) + 1);
for (int i = 0; i < 3; ++i) { // Each face contains 3 sets of indicies. Each set is 3 indicies v/t/n.
std::string first = cur.substr(0, cur.find('/')); // Substring for the v portion
indicies[i][0] = atoi(first.c_str());
has_vert_indices=true;
if ((cur.find('/') + 1) != cur.find('/', cur.find('/') + 1)) { // Check if we have a t portion
std::string second = cur.substr(cur.find('/') + 1, cur.find('/', cur.find('/') + 1)); // Substring for the t portion
indicies[i][1] = atoi(second.c_str());
has_uv_indices=true;
}
else {
indicies[i][1] = 0;
}
if (cur.find('/', cur.find('/')) != cur.find_last_of('/')) { // Check if we have an n portion
std::string third = cur.substr(cur.find_last_of('/') + 1); // Substring for the n portion
indicies[i][2] = atoi(third.c_str());
has_normal_indices=true;
}
else {
indicies[i][2] = 0;
}
cur = left.substr(0, left.find(' '));
left = left.substr(left.find(' ') + 1);
}
if(has_vert_indices) {
GLushort a,b,c;
a = indicies[0][0] - 1; b = indicies[1][0] - 1; c = indicies[2][0] - 1;
current_face.v[0].vertex = a;
current_face.v[1].vertex = b;
current_face.v[2].vertex = c;
}
if(has_uv_indices) {
GLushort ta,tb,tc;
ta = indicies[0][1] - 1; tb = indicies[1][1] - 1; tc = indicies[2][1] - 1;
current_face.v[0].uv = ta;
current_face.v[1].uv = tb;
current_face.v[2].uv = tc;
}
if(has_normal_indices) {
GLushort na,nb,nc;
na = indicies[0][2] - 1; nb = indicies[1][2] - 1; nc = indicies[2][2] - 1;
current_face.v[0].normal = na;
current_face.v[1].normal = nb;
current_face.v[2].normal = nc;
}
// Add index to currently active color
current_face.v[0].color = current_color;
current_face.v[1].color = current_color;
current_face.v[2].color = current_color;
// Store the face
temp_face_indices.push_back(current_face);
}
else if (line.substr(0,1) == "g") { // Face group
this->groupIndex.push_back(temp_face_indices.size());
}
else if (line.substr(0, line.find(' ')) == "mtllib") { // Material library
// Add the path to the filename to load it relative to the obj file.
ParseMTL(path + line.substr(line.find(' ') + 1));
}
else if (line.substr(0, line.find(' ')) == "usemtl") { // Use material
std::string mtlname = line.substr(line.find(' ') + 1);
// Set as current material group
currentMtlGroup = mtlname;
// Push back color (for now)
Material m = this->mats[mtlname];
glm::vec3 amb(m.ka[0], m.ka[1], m.ka[2]);
glm::vec3 spec(m.ks[0], m.ks[1], m.ks[2]);
glm::vec3 dif(m.kd[0], m.kd[1], m.kd[2]);
glm::vec3 color = amb + dif + spec;
temp_colors.push_back(Color(color.r, color.g, color.b));
this->faceGroups[temp_face_indices.size()] = currentMtlGroup;
current_color++;
}
else if ((line.substr(0,1) == "#") || (line.size() == 0)) { // Comment or blank line
/* ignoring this line comment or blank*/
}
else { // Unknown
/* ignoring this line */
std::string test = line.substr(0, line.find(' '));
LOG_WARN << "Unrecognized line " << line;
}
}
// Now we have all raw attributes stored in the temp vectors,
// and the set of indicies for each face. Opengl only supports
// one index buffer, so we must duplicate vertices until
// all the data lines up.
for(unsigned int i=0; i < temp_face_indices.size(); i++) {
std::vector<VertexIndices>::iterator result;
unsigned int v[3];
for(int j=0; j<3; j++) {
result = std::find(unique_vertices.begin(),
unique_vertices.end(),
temp_face_indices[i].v[j]);
// if this combination of indicies doesn't exist,
// add the data to the attribute arrays
if (result == unique_vertices.end()) {
v[j] = this->verts.size();
this->verts.push_back(temp_verts[temp_face_indices[i].v[j].vertex]);
if (temp_uvs.size() > 0) {
this->texCoords.push_back(temp_uvs[temp_face_indices[i].v[j].uv]);
}
if (temp_normals.size() > 0) {
this->vertNorms.push_back(temp_normals[temp_face_indices[i].v[j].normal]);
}
if (temp_colors.size() > 0) {
this->colors.push_back(temp_colors[temp_face_indices[i].v[j].color]);
}
unique_vertices.push_back(temp_face_indices[i].v[j]);
}
else {
// calculate the correct offset
unsigned int unique_vertex_index = std::distance(unique_vertices.begin(), result);
v[j] = unique_vertex_index;
}
}
// Push it back
this->faces.push_back(Face(v[0], v[1], v[2]));
}
// Check if vertex normals exist
if(vertNorms.size() == 0) {
std::vector<Vertex> surfaceNorms;
// compute surface normals
for(size_t i = 0; i < faces.size(); i++) {
glm::vec3 vector1, vector2, cross, normal;
Vertex vert1(verts[faces[i].v1]), vert2(verts[faces[i].v2]), vert3(verts[faces[i].v3]);
vector1 = glm::normalize(glm::vec3(vert2.x-vert1.x, vert2.y-vert1.y, vert2.z-vert1.z));
vector2 = glm::normalize(glm::vec3(vert3.x-vert1.x, vert3.y-vert1.y, vert3.z-vert1.z));
cross = glm::cross(vector1, vector2);
normal = glm::normalize(cross);
surfaceNorms.push_back(Vertex(normal.x, normal.y, normal.z));
}
// compute vertex normals
// should probably compute adjacency first, this could be slow
for(size_t i = 0; i < verts.size(); i++) {
Vertex total_normals(0.0f, 0.0f, 0.0f);
for(size_t j = 0; j < faces.size(); j++) {
if (faces[j].v1 == i || faces[j].v2 == i || faces[j].v3 == i) {
total_normals.x += surfaceNorms[j].x;
total_normals.y += surfaceNorms[j].y;
total_normals.z += surfaceNorms[j].z;
}
}
if(!(total_normals.x == 0.0f && total_normals.y == 0.0f && total_normals.z == 0.0f)) {
glm::vec3 final_normal(total_normals.x, total_normals.y, total_normals.z);
final_normal = glm::normalize(final_normal);
vertNorms.push_back(Vertex(final_normal.x, final_normal.y, final_normal.z));
}
else {
vertNorms.push_back(Vertex(total_normals.x, total_normals.y, total_normals.z));
}
}
surfaceNorms.clear();
}
return true;
} // function LoadMesh
void GLMesh::LoadShader() {
IGLComponent::LoadShader(GLMesh::DEFAULT_SHADER);
}
void GLMesh::ParseMTL(std::string fname) {
// Extract the path from the filename.
std::string path;
if (fname.find("/") != std::string::npos) {
path = fname.substr(0, fname.find_last_of("/") + 1); // Keep the separator.
}
else {
path = fname.substr(0, fname.find_last_of("\\") + 1); // Keep the separator.
}
std::ifstream in(fname, std::ios::in);
if (!in) {
LOG_WARN << "Cannot open material " << fname;
return;
}
std::string line;
while (getline(in, line)) {
line = trim(line);
std::stringstream s(line);
std::string label;
s >> label;
if (label == "newmtl") {
std::string name;
s >> name;
Material m;
getline(in, line);
s.clear();
s.str(line);
s.seekg(0);
s >> label;
while (label != "newmtl") {
if (label == "Ka") {
float r,g,b;
s >> r; s >> g; s >> b;
m.ka[0] = r; m.ka[1] = g; m.ka[2] = b;
}
else if (label == "Kd") {
float r,g,b;
s >> r; s >> g; s >> b;
m.kd[0] = r; m.kd[1] = g; m.kd[2] = b;
}
else if (label == "Ks") {
float r,g,b;
s >> r; s >> g; s >> b;
m.ks[0] = r; m.ks[1] = g; m.ks[2] = b;
}
else if ((label == "Tr") || (label == "d")) {
float tr;
s >> tr;
m.tr = tr;
}
else if (label == "Ns") {
float ns;
s >> ns;
m.hardness = ns;
}
else if (label == "illum") {
int i;
s >> i;
m.illum = i;
}
else if (label == "map_Kd") {
std::string filename;
s >> filename;
filename = trim(filename);
if(filename.length() > 0 && texReplaceWith.length() > 0 && texReplace == filename) {
if (OpenGLSystem::textures.find(texReplaceWith) != OpenGLSystem::textures.end()) {
std::cerr << "Using diffuse texture: " << texReplaceWith << std::endl;
m.diffuseMap = Sigma::OpenGLSystem::textures[texReplaceWith].GetID();
}
} else {
filename = convert_path(filename);
LOG << "Loading diffuse texture: " << path + filename;
resource::GLTexture texture;
if (OpenGLSystem::textures.find(filename) == OpenGLSystem::textures.end()) {
texture.LoadDataFromFile(path + filename);
if (texture.GetID() != 0) {
OpenGLSystem::textures[filename] = texture;
}
}
// Add the path to the filename to load it relative to the mtl file
if (OpenGLSystem::textures.find(filename) != OpenGLSystem::textures.end()) {
m.diffuseMap = Sigma::OpenGLSystem::textures[filename].GetID();
}
}
if (m.diffuseMap == 0) {
LOG_WARN << "Error loading diffuse texture: " << path + filename;
}
}
else if (label == "map_Ka") {
std::string filename;
s >> filename;
filename = trim(filename);
filename = convert_path(filename);
LOG << "Loading ambient texture: " << path + filename;
// Add the path to the filename to load it relative to the mtl file
resource::GLTexture texture;
if (OpenGLSystem::textures.find(filename) == OpenGLSystem::textures.end()) {
texture.LoadDataFromFile(path + filename);
if (texture.GetID() != 0) {
OpenGLSystem::textures[filename] = texture;
}
}
// It should be loaded, but in case an error occurred double check for it.
if (OpenGLSystem::textures.find(filename) != OpenGLSystem::textures.end()) {
m.ambientMap = Sigma::OpenGLSystem::textures[filename].GetID();
}
// Add the path to the filename to load it relative to the mtl file
if (m.ambientMap == 0) {
LOG_WARN << "Error loading ambient texture: " << path + filename;
}
}
else if (label == "map_Bump") {
std::string filename;
s >> filename;
filename = trim(filename);
filename = convert_path(filename);
LOG << "Loading normal or bump texture: " << path + filename;
// Add the path to the filename to load it relative to the mtl file
resource::GLTexture texture;
if (OpenGLSystem::textures.find(filename) == OpenGLSystem::textures.end()) {
texture.LoadDataFromFile(path + filename);
if (texture.GetID() != 0) {
OpenGLSystem::textures[filename] = texture;
}
}
// It should be loaded, but in case an error occurred double check for it.
if (OpenGLSystem::textures.find(filename) != OpenGLSystem::textures.end()) {
m.normalMap = Sigma::OpenGLSystem::textures[filename].GetID();
}
// Add the path to the filename to load it relative to the mtl file
if (m.normalMap == 0) {
LOG_WARN << "Error loading normal texture: " << path + filename;
}
}
else {
// Blank line
}
std::streamoff pre = in.tellg();
getline(in, line);
if (in.eof()) {
break;
}
s.clear();
s.str(line);
s.seekg(0);
s >> label;
std::string newlabel;
if (s.str().find("newmtl") != std::string::npos) {
in.seekg(pre);
break;
}
}
this->mats[name] = m;
}
}
} // function ParseMTL
} // namespace Sigma
| mit |
konradovsky/KNWDHackYeahFront | src/views/VolunteerProfile/Volunteer_styles.js | 1485 | import styled from 'styled-components';
import { Container } from '../../utils/styledComponents';
import { colorPalette } from '../../utils/constants/styles';
export const Wrapper = styled.div`
display: flex;
justify-content: center;
width: 100%;
height: 100%;
background-color: ${colorPalette.primary1Color};
`;
export const StyledContainer = Container.extend`
margin-top: 60px;
box-shadow: rgba(0, 0, 0, 0.16) 0 3px 10px, rgba(0, 0, 0, 0.23) 0 3px 10px;
`;
export const Header = styled.div`
width: 100%;
height: 185px;
background-color: red;
position: relative;
`;
export const Profile = styled.div`
height: 100%;
width: 30%;
float: left;
text-align: center;
background-color: ${colorPalette.primary2Color};
img {
margin-top: 60px;
margin-bottom: 10px;
width: 50px;
height: 50px;
}
p {
color: white;
font-size: 20px;
}
`;
export const Name = styled.div`
width: 70%;
height: 100%;
float: left;
background-color: ${colorPalette.primary2Color};
color: white;
text-align: center;
h1 {
font-size: 40px;
padding: 5px;
font-weight: 200;
margin-top: 55px;
margin-bottom: 10px;
}
`;
export const GameSection = styled.div`
width: 100%;
height: 265px;
background-color: white;
color: ${colorPalette.primary2Color};
position: relative;
`;
export const UpdateSection = styled.div`
width: 100%;
height: 370px;
background-color: ${colorPalette.primary1Color};
color: white;
`;
| mit |
kinpa200296/FollowTheTask | FollowTheTask.Web/App_Start/FilterConfig.cs | 253 | using System.Web.Mvc;
namespace FollowTheTask.Web
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
} | mit |
markpad/markpad | src/json-to-params.js | 180 | const JSONToParams = (object) => {
return Object.keys(object).map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(object[k])).join('&');
};
export default JSONToParams; | mit |
godosou/smaroute | src/PathGeneration/Enumeration/patEnumeratePaths.cc | 2858 | /*
* patEnumeratePaths.cc
*
* Created on: May 25, 2012
* Author: jchen
*/
#include "patEnumeratePaths.h"
#include <tr1/unordered_map>
#include <set>
#include "patRoadBase.h"
#include "patMultiModalPath.h"
#include "patException.h"
using namespace std;
using namespace std::tr1;
patEnumeratePaths::patEnumeratePaths() {
// TODO Auto-generated constructor stub
}
void patEnumeratePaths::setNetwork(const patNetworkBase* network_environment) {
m_network = network_environment;
}
void patEnumeratePaths::setPathWriter(patPathWriter* path_writer) {
m_path_writer = path_writer;
}
void patEnumeratePaths::depth_first_enumerate(
const unordered_map<const patNode*, set<const patRoadBase*> >* outgoing_incidents
,const patNode* up_node, const patNode* end_node
, patMultiModalPath& tmp_path,
set<patMultiModalPath>& found_path) const{
const unordered_map<const patNode*, set<const patRoadBase*> >::const_iterator find_outgoing =
outgoing_incidents->find(up_node);
if (find_outgoing == outgoing_incidents->end()) {
DEBUG_MESSAGE(up_node->getUserId());
return;
} else {
for (set<const patRoadBase*>::const_iterator road_iter =
find_outgoing->second.begin();
road_iter != find_outgoing->second.end(); ++road_iter) {
if (tmp_path.addRoadTravelToBack(*road_iter)) {
if (tmp_path.containLoop() != NULL) {
// contain loop, do nothing
//tmp_path.removeRoadTravelToBack();
} else if ((*road_iter)->getDownNode() == end_node) {
found_path.insert(tmp_path);
} else {
depth_first_enumerate(outgoing_incidents,
(*road_iter)->getDownNode(), end_node, tmp_path,
found_path);
}
tmp_path.removeRoadTravelToBack();
} else {
throw RuntimeException("road append error");
}
}
}
}
void patEnumeratePaths::run(const patNode* origin, const patNode* destination) {
const unordered_map<const patNode*, set<const patRoadBase*> >* outgoing_incidents =
m_network->getOutgoingIncidents();
// DEBUG_MESSAGE("ougoing nodes"<<outgoing_incidents->size());
// for(unordered_map<const patNode*, set<const patRoadBase*> >::const_iterator oi_iter = outgoing_incidents->begin();
// oi_iter!=outgoing_incidents->end();++oi_iter){
// DEBUG_MESSAGE(oi_iter->first->getUserId()<<":"<<oi_iter->second.size());
// }
set<patMultiModalPath> found_path;
patMultiModalPath tmp_path;
depth_first_enumerate(outgoing_incidents,origin,destination,tmp_path,found_path);
DEBUG_MESSAGE("Enumerates "<<found_path.size()<<" paths");
map<string, string> attrs;
attrs["count"]="1";
attrs["logweight"]="0.0";
for(set<patMultiModalPath>::const_iterator path_iter = found_path.begin();
path_iter!=found_path.end();
++path_iter){
m_path_writer->writePath(*path_iter,attrs);
}
//m_path_writer->close();
}
patEnumeratePaths::~patEnumeratePaths() {
// TODO Auto-generated destructor stub
}
| mit |
MrPIvanov/SoftUni | 04-Csharp Advanced/03-STACKS AND QUEUES/03-StacksAndQueuesLab/04-MatchingBrackets/StartUp.cs | 659 | namespace _04_MatchingBrackets
{
using System;
using System.Collections.Generic;
class StartUp
{
static void Main(string[] args)
{
var str = Console.ReadLine();
var input = str.ToCharArray();
var stack = new Stack<int>();
for (int i = 0; i < input.Length; i++)
{
if (input[i]=='(')
{
stack.Push(i);
}
if (input[i]==')')
{
Console.WriteLine(str.Substring(stack.Peek(),i-stack.Pop()+1));
}
}
}
}
}
| mit |
dplummer/services_test_server | lib/services_test_server/db_controller.rb | 768 | require 'drb'
require 'thread'
module ServicesTestServer
class DbController
def self.only_one_connection
ActiveRecord::ConnectionAdapters::ConnectionPool.class_eval do
alias_method :old_checkout, :checkout
def checkout
@cached_connection ||= old_checkout
end
end
end
def initialize
@mutex = Mutex.new
end
def begin_transaction
@mutex.lock
ServicesTestServer.logger.debug "Beginning remote transaction"
ActiveRecord::Base.connection.begin_transaction(joinable: false)
end
def rollback_transaction
ServicesTestServer.logger.debug "Rolling back remote transaction"
ActiveRecord::Base.connection.rollback_transaction
@mutex.unlock
end
end
end
| mit |
Arasz/Optimization-techniques | Travelling salesman problem/Algorithms/RandomPathAlgorithm.cs | 1280 | using ConsoleApplication.Graphs;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication.Algorithms
{
public class RandomPathAlgorithm : AlgorithmBase
{
private readonly Random _randomGenerator;
public RandomPathAlgorithm(int steps, IEdgeFinder edgeFinder) : base(steps, edgeFinder)
{
_randomGenerator = new Random();
}
public override Path Solve(int startNode, IGraph completeGraph, Path precalculatedPath = null)
{
var iterator = completeGraph.Iterator;
var nodes = new List<int>(startNode);
var unvisitedNodes = completeGraph.Nodes.Where(node => node != startNode).ToList();
var steps = _steps;
while (--steps > 0)
{
var edgeToNearestNode = _edgeFinder.RandomNodeEdge(iterator.Edges, unvisitedNodes, _randomGenerator);
iterator.MoveAlongEdge(edgeToNearestNode);
unvisitedNodes.Remove(iterator.CurrentNode);
nodes.Add(iterator.CurrentNode);
}
nodes.Add(startNode);
return new Path(nodes, new DefaultCostCalculationStrategy(completeGraph));
}
}
} | mit |
UCSB-CS56-W14/CS56-W14-lab06 | src/edu/ucsb/cs56/W14/drawings/buzdar/advanced/WritePictureToFile.java | 3182 | package edu.ucsb.cs56.w14.drawings.buzdar.advanced;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.Color;
import java.io.File;
import javax.imageio.ImageIO;
import java.io.IOException;
import edu.ucsb.cs56.w14.drawings.utilities.ShapeTransforms;
import edu.ucsb.cs56.w14.drawings.utilities.GeneralPathWrapper;
/**
* A class with a main method that can write a drawing to a graphics file.
*
* @author P. Conrad,
* @version for CS56, W11 UCSB
*/
public class WritePictureToFile
{
public static void usage()
{
System.out.println("Usage: java WritePictureToFile whichImage mypic");
// @@@ modify the next line to describe your picture
System.out.println(" whichImage should be 1,2 or 3");
System.out.println(" whichImage chooses from drawPicture1, 2 or 3");
System.out.println(" .png gets added to the filename");
System.out.println(" e.g. if you pass mypic, filename is mypic.png");
System.out.println("Example: java WritePictureToFile 3 foo");
System.out.println(" produces foo.png from drawPicture3");
}
/** Write the drawFourCoffeeCups picture to a file.
*
* @param args The first command line argument is the file to write to. We leave off the extension
* because that gets put on automatically.
*/
public static void main(String[] args)
{
// make sure we have exactly one command line argument
if (args.length != 2)
{
usage();
System.exit(1);
}
String whichPicture = args[0]; // first command line arg is 1, 2, 3
String outputfileName = args[1]; // second command line arg is which pic
final int WIDTH = 640;
final int HEIGHT = 480;
// create a new image
// TYPE_INT_ARGB is "RGB image" with transparency (A = alpha channel)
BufferedImage bi =
new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
// g2 is a Graphics2D object that will draw into the BufferedImage object
Graphics2D g2 = bi.createGraphics();
if (whichPicture.equals("1")) {
AllMyDrawings.drawPicture1(g2);
} else if (whichPicture.equals("2")) {
AllMyDrawings.drawPicture2(g2);
} else if (whichPicture.equals("3")) {
AllMyDrawings.drawPicture2(g2);
}
final String imageType = "png"; // choices: "gif", "png", "jpg"
// We must declare this variable outside the try block,
// so we can see it inside the catch block
String fullFileName = "";
try
{
fullFileName = outputfileName + "." + imageType; // make the file name
File outputfile = new File(fullFileName); // the file we will try to write
ImageIO.write(bi, imageType, outputfile); // actually write it
System.out.println("I created " + fullFileName); // tell the user
}
catch (IOException e)
{
System.err.println("Sorry, an error occurred--I could not create "+ fullFileName +"\n The error was: "+ e.toString());
}
}
}
| mit |
chrissorchard/malucrawl | demo/classifier.py | 1745 | from __future__ import division
from pebl.util import levenshtein
from malware_crawl.models import Malicouse_sites
_mal_list = []
def read_from_database_to_dict():
"""
Reads the malwares from the database and returns a mal_dict
"""
malwares = Malicouse_sites.objects.all()
mal_dict = {}
for m in malwares:
mal_dict[m.url] = m.malware
return mal_dict
def classify_is_sus(new_url):
sus_sum = 0
notsus_sum = 0
sind = 1
nind = 1
database = read_from_database_to_dict()
if new_url in database:
return database[new_url], 1.0
for item in database:
dist = levenshtein(new_url, item["url"])
if item["malware"]:
sus_sum = sus_sum + dist
sind = sind + 1
else:
notsus_sum = notsus_sum + dist
nind = nind + 1
avg_sus = sus_sum // sind
avg_notsus = notsus_sum // nind
total_len = avg_sus + avg_notsus
if avg_sus > avg_notsus:
return False, 1.0 - avg_notsus / total_len
else:
return True, 1.0 - avg_sus / total_len
def add_url(url, is_mal):
""" Gets url and if it is a malware and fills the
_mal_list which is used for the classification task
url -- the url which is classified as malware or not
is_mal -- true or false
"""
global _mal_list
_mal_list.append({"url": url, "malware": is_mal})
if __name__ == '__main__':
import json
import pkgutil
"""
mal_dict = json.loads(pkgutil.get_data("classifier", "mal_test_data.json"))
malwares = Malicouse_sites.objects.all()
print classify_is_sus(mal_dict, url)
"""
url = 'http://uk.movies.yahoo.com/features/sdfasf'
print classify_is_sus(url)
| mit |
laerciosb/fractal_test | db/migrate/20170421125241_create_products.rb | 282 | # frozen_string_literal: true
class CreateProducts < ActiveRecord::Migration[5.0]
def change
create_table :products do |t|
t.string :name
t.references :supplier, foreign_key: true
t.references :place, foreign_key: true
t.timestamps
end
end
end
| mit |
larsth/go-rmsggpsbinmsg | misc_test.go | 1409 | package binmsg
import (
"strconv"
"testing"
)
func TestFloat32MarshalBinary(t *testing.T) {
want := []byte{0x42, 0x5e, 0xc4, 0x11}
got := float32MarshalBinary(float32(55.69147))
if s, ok := byteSliceCheck(0, got, want); ok == false {
t.Fatal(s)
}
}
func TestFloat32MarshalBinaryValues(t *testing.T) {
want := []byte{0x42, 0x5e, 0xc4, 0x11}
gotV1, gotV2, gotV3, gotV4 := float32MarshalBinaryValues(float32(55.69147))
got := make([]byte, 4)
got[0] = gotV1
got[1] = gotV2
got[2] = gotV3
got[3] = gotV4
if s, ok := byteSliceCheck(0, got, want); ok == false {
t.Fatal(s)
}
}
func TestFloat32UnmarshalBinary(t *testing.T) {
p := []byte{0x42, 0x5e, 0xc4, 0x11}
want := float32(55.69147)
got := float32UnmarshalBinary(p)
if want != got {
gotStr := strconv.FormatFloat(float64(got), 'f', -1, 32)
wantStr := strconv.FormatFloat(float64(got), 'f', -1, 32)
s := mkStrErrString("", gotStr, wantStr)
t.Fatal(s)
}
}
func BenchmarkMiscFloat32MarshalBinary(b *testing.B) {
var f = float32(123.45)
for i := 0; i < b.N; i++ {
_ = float32MarshalBinary(f)
}
}
func BenchmarkMiscFloat32MarshalBinaryValues(b *testing.B) {
var f = float32(123.45)
for i := 0; i < b.N; i++ {
_, _, _, _ = float32MarshalBinaryValues(f)
}
}
func BenchmarkMiscFloat32UnmarshalBinary(b *testing.B) {
var p = []byte{0x01, 0x23, 0x45, 0x67}
for i := 0; i < b.N; i++ {
_ = float32UnmarshalBinary(p)
}
}
| mit |
anycmd/anycmd | src/Anycmd/Engine/Ac/Groups/GroupRemovedEvent.cs | 504 |
namespace Anycmd.Engine.Ac.Groups
{
using Events;
public sealed class GroupRemovedEvent : DomainEvent
{
public GroupRemovedEvent(IAcSession acSession, GroupBase source)
: base(acSession, source)
{
}
internal GroupRemovedEvent(IAcSession acSession, GroupBase source, bool isPrivate)
: this(acSession, source)
{
this.IsPrivate = isPrivate;
}
internal bool IsPrivate { get; private set; }
}
} | mit |
Aprogiena/StratisBitcoinFullNode | src/Stratis.SmartContracts.Tools.Sct/Program.cs | 798 | using McMaster.Extensions.CommandLineUtils;
using Stratis.SmartContracts.Tools.Sct.Build;
using Stratis.SmartContracts.Tools.Sct.Deployment;
using Stratis.SmartContracts.Tools.Sct.Validation;
namespace Stratis.SmartContracts.Tools.Sct
{
[Command(ThrowOnUnexpectedArgument = false)]
[Subcommand("validate", typeof(Validator))]
[Subcommand("build", typeof(Builder))]
[Subcommand("deploy", typeof(Deployer))]
[Subcommand("base58", typeof(Base58Converter))]
[HelpOption]
[VersionOption("-v|--version", "v0.0.2")]
class Program
{
public static int Main(string[] args) => CommandLineApplication.Execute<Program>(args);
private int OnExecute(CommandLineApplication app)
{
app.ShowHelp();
return 1;
}
}
} | mit |
lukasz-jakub-adamczuk/sapi | src/AppBundle/Entity/UserPermission.php | 1210 | <?php
namespace AppBundle\Entity;
/**
* UserPermission
*/
class UserPermission
{
/**
* @var integer
*/
private $idUser;
/**
* @var boolean
*/
private $idPermission;
/**
* @var integer
*/
private $idUserPermission;
/**
* Set idUser
*
* @param integer $idUser
*
* @return UserPermission
*/
public function setIdUser($idUser)
{
$this->idUser = $idUser;
return $this;
}
/**
* Get idUser
*
* @return integer
*/
public function getIdUser()
{
return $this->idUser;
}
/**
* Set idPermission
*
* @param boolean $idPermission
*
* @return UserPermission
*/
public function setIdPermission($idPermission)
{
$this->idPermission = $idPermission;
return $this;
}
/**
* Get idPermission
*
* @return boolean
*/
public function getIdPermission()
{
return $this->idPermission;
}
/**
* Get idUserPermission
*
* @return integer
*/
public function getIdUserPermission()
{
return $this->idUserPermission;
}
}
| mit |
zwippie/trailblazer | test/rails/fake_app/song/operations.rb | 2227 | class Song < ActiveRecord::Base
class Create < Trailblazer::Operation
include CRUD
include Responder
model Song, :create
contract do
property :title, validates: {presence: true}
property :length
end
def process(params)
validate(params[:song]) do
contract.save
end
end
end
class Delete < Create
action :find
def process(params)
model.destroy
self
end
end
end
class Band < ActiveRecord::Base
class Create < Trailblazer::Operation
include CRUD, Responder, Representer
model Band, :create
contract do
include Reform::Form::ActiveModel
model Band
property :name, validates: {presence: true}
property :locality
# class: Song #=> always create new song
# instance: { Song.find(params[:id]) or Song.new } # same as find_or_create ?
# this is what i want:
# maybe make populate_if_empty a representable feature?
collection :songs, populate_if_empty: Song do
property :title
end
end
def process(params)
validate(params[:band]) do
contract.save
end
end
class JSON < self
require "reform/form/json"
contract do
include Reform::Form::JSON # this allows deserialising JSON.
end
representer do
collection :songs, inherit: true, render_empty: false # tested in ControllerPresentTest.
end
end
class Admin < self
def process(params)
res = super
model.update_attribute :name, "#{model.name} [ADMIN]"
res
end
end
# TODO: wait for uber 0.0.10 and @dutow.
# builds -> (params)
# return JSON if params[:format] == "json"
# return Admin if params[:admin]
# end
builds do |params|
if params[:format] == "json"
JSON
elsif params[:admin]
Admin
end
end
end
class Update < Create
action :update
# TODO: infer stuff per default.
class JSON < self
self.contract_class = Create::JSON.contract_class
self.representer_class = Create::JSON.representer_class
end
builds do |params|
JSON if params[:format] == "json"
end
end
end | mit |
nicklasjepsen/GravatarSharp | GravatarSharp/GravatarModels/Name.cs | 355 | using Newtonsoft.Json;
namespace GravatarSharp.GravatarModels
{
internal class Name
{
[JsonProperty("givenName")]
public string GivenName { get; set; }
[JsonProperty("familyName")]
public string FamilyName { get; set; }
[JsonProperty("formatted")]
public string Formatted { get; set; }
}
} | mit |
tomru/switchmon | test/swm.tests.js | 5847 | 'use strict';
const sinon = require('sinon');
const assert = require('assert');
const proxyquire = require('proxyquire');
describe('swm', () => {
let sandbox;
beforeEach(() => {
sandbox = sinon.sandbox.create();
});
afterEach(() => {
sandbox.restore();
});
describe('getDevices', () => {
let execStub;
let xrandrParseStub;
let swm;
beforeEach(() => {
execStub = sandbox.stub();
xrandrParseStub = sandbox.stub();
swm = proxyquire('../swm.js', {
child_process: {
exec: execStub
},
'xrandr-parse': xrandrParseStub
});
});
it('calls exec', () => {
swm.getDevices(sandbox.stub());
assert.equal(execStub.callCount, 1);
assert.equal(execStub.args[0][0], 'xrandr');
});
it('passes error when exec passes error', (done) => {
const devices = swm.getDevices((err, devices) => {
assert.equal(xrandrParseStub.callCount, 0);
assert.equal(err, 'some error');
done();
});
const cb = execStub.args[0][1];
cb('some error');
});
it('parses result', (done) => {
xrandrParseStub.returns('[some result]');
swm.getDevices((err, devices) => {
assert.equal(xrandrParseStub.args[0][0], '[some stdout]');
assert.equal(xrandrParseStub.callCount, 1);
assert.equal(devices, '[some result]');
done();
});
const cb = execStub.args[0][1];
cb(null, '[some stdout]');
});
});
describe('generateXrandrOptions', () => {
let swm;
let devices;
beforeEach(() => {
devices = {
'HDMI1': {
connected: true
},
'HDMI2': {
connected: true,
},
'LVDS1': {
connected: false
},
'DP1': {
connected: true,
}
}
swm = require('../swm.js');
});
describe('activation of monitor', () => {
it('for connected monitors if non is selected', () => {
const result = swm.generateXrandrOptions([], devices);
assert(result.indexOf('--output HDMI1 --auto') > -1);
assert(result.indexOf('--output HDMI2 --auto') > -1);
assert(result.indexOf('--output LVDS1 --off') > -1);
});
it('for connected selected monitors', () => {
const result = swm.generateXrandrOptions(['HDMI2'], devices);
assert(result.indexOf('--output HDMI1 --off') > -1);
assert(result.indexOf('--output HDMI2 --auto') > -1);
assert(result.indexOf('--output LVDS1 --off') > -1);
});
it('skipps selected monitors that are not connected', () => {
const result = swm.generateXrandrOptions(['LVDS1', 'HDMI2'], devices);
assert(result.indexOf('--output HDMI2 --auto') > -1);
assert(result.indexOf('--output LVDS1 --off') > -1);
});
});
it('aligns monitor n to the right of monitor n-1', () => {
const result = swm.generateXrandrOptions(['HDMI1', 'HDMI2', 'DP1'], devices);
assert(result.indexOf('--output HDMI1 --auto') > -1);
assert(result.indexOf('--output HDMI2 --auto --right-of HDMI1') > -1);
assert(result.indexOf('--output DP1 --auto --right-of HDMI2') > -1);
});
it('throws when no selected monitor is connected', () => {
assert.throws(() => {swm.generateXrandrOptions(['LVDS1'], devices)});
assert.throws(() => {swm.generateXrandrOptions(['BOGUS'], devices)});
devices = {};
assert.throws(() => {swm.generateXrandrOptions([], devices)});
});
});
describe('switchDevices', () => {
let execStub;
let swm;
beforeEach(() => {
execStub = sandbox.stub();
swm = proxyquire('../swm.js', {
child_process: {
exec: execStub
}
});
});
it('calls exec with xrandr and opitons', () => {
swm.switchDevices('[some options]', sandbox.stub());
assert.equal(execStub.callCount, 1);
assert.equal(execStub.args[0][0], 'xrandr [some options]');
});
it('passes error when exec passes error', (done) => {
swm.switchDevices('[some options]', (err, devices) => {
assert.equal(err, 'some error');
done();
});
const cb = execStub.args[0][1];
cb('some error');
});
});
describe('executePostCmd', () => {
let execStub;
let swm;
beforeEach(() => {
execStub = sandbox.stub();
swm = proxyquire('../swm.js', {
child_process: {
exec: execStub
}
});
});
it('calls postCmd', () => {
swm.executePostCmd('[some cmd]');
assert.equal(execStub.callCount, 1);
assert.equal(execStub.args[0][0], '[some cmd]');
});
it('passes error when exec passes error', (done) => {
swm.executePostCmd('[some cmd]', (err, devices) => {
assert.equal(err, '[some error]');
done();
});
const cb = execStub.args[0][1];
cb('[some error]');
});
});
});
| mit |
giorgosbarkos2/sysAdmin | src/projectAdmin/principalBundle/Controller/DefaultController.php | 10348 | <?php
namespace projectAdmin\principalBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use projectAdmin\loginBundle\Entity\Categoria;
use projectAdmin\loginBundle\Entity\Producto;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends Controller {
public function principalAction() {
$session = $this->getRequest()->getSession();
$idioma = $session->get('idioma');
$em = $this->getDoctrine()->getManager();
if ($idioma == 'ingles') {
$idioma = 'ingles';
// Lo mismo de abajo pero con ingles
} else {
$idioma = 'español';
}
$queryCategorias = $em->createQuery('SELECT u from projectAdminloginBundle:Categoria u WHERE u.idioma=:idioma order by u.id desc ')
->setParameter('idioma', $idioma);
$query = $em->createQuery('SELECT u from projectAdminloginBundle:Producto u WHERE u.idioma=:idioma order by u.id desc ')
->setParameter('idioma', $idioma)
->setMaxResults(6);
$queryBanner = $em->createQuery('SELECT u from projectAdminloginBundle:Banner u WHERE u.idioma=:idioma order by u.id desc ')->setParameter('idioma', $idioma);
$queryArticulos = $em->createQuery('SELECT u from projectAdminloginBundle:Articulo u WHERE u.idioma=:idioma order by u.id desc ')->setParameter('idioma', $idioma);
$queryCaluga = $em->createQuery('SELECT u from projectAdminloginBundle:Caluga u WHERE u.idioma=:idioma order by u.id desc ')->setParameter('idioma', $idioma);
$queryBannerAd = $em->createQuery('SELECT u from projectAdminloginBundle:Banner2 u WHERE u.idioma=:idioma order by u.id desc ')->setParameter('idioma', $idioma)->setMaxResults(1);
;
$categorias = $queryCategorias->getResult();
$productos = $query->getResult();
$banner = $queryBanner->getResult();
$caluga = $queryCaluga->getResult();
$banner2 = $queryBannerAd->getResult();
$articulos = $queryArticulos->getResult();
return $this->render('projectAdminprincipalBundle:Default:principal.html.twig', array('categoria' => $categorias, 'producto' => $productos, 'banner' => $banner,
'caluga' => $caluga, 'banner2' => $banner2, 'articulos' => $articulos, 'idioma' => $idioma));
}
public function vistaProductosAction($id) {
$em = $this->getDoctrine()->getManager();
$session = $this->getRequest()->getSession();
$idioma = $session->get('idioma');
if ($idioma == 'ingles') {
$idioma = 'ingles';
} else {
$idioma = 'español';
}
$productos = $em->getRepository('projectAdminloginBundle:Producto')->findBy(array('categoria' => $id));
$queryCategorias = $em->createQuery('SELECT u from projectAdminloginBundle:Categoria u WHERE u.idioma=:idioma order by u.id desc ')
->setParameter('idioma', $idioma);
$categoriaP = $em->getRepository('projectAdminloginBundle:Categoria')->findOneBy(array('id' => $id));
$queryArticulos = $em->createQuery('SELECT u from projectAdminloginBundle:Articulo u WHERE u.idioma=:idioma order by u.id desc ')
->setParameter('idioma', $idioma);
$articulos = $queryArticulos->getResult();
$categoria = $queryCategorias->getResult();
return $this->render('projectAdminprincipalBundle:Default:productos.html.twig', array('productos' => $productos, 'categoria' => $categoria, 'categoriaP' => $categoriaP, 'articulos' => $articulos, 'idioma' => $idioma));
}
public function detalleProductoAction($id) {
$em = $this->getDoctrine()->getManager();
$session = $this->getRequest()->getSession();
$idioma = $session->get('idioma');
if ($idioma == 'ingles') {
$idioma = 'ingles';
} else {
$idioma = 'español';
}
$producto = $em->getRepository('projectAdminloginBundle:Producto')->findOneBy(array('id' => $id));
$idCat = $producto->getCategoria()->getId();
$productoAsoc = $em->getRepository('projectAdminloginBundle:Producto')->findBy(array('categoria' => $idCat));
$queryCategorias = $em->createQuery('SELECT u from projectAdminloginBundle:Categoria u WHERE u.idioma=:idioma order by u.id desc ')
->setParameter('idioma', $idioma);
$queryArticulos = $em->createQuery('SELECT u from projectAdminloginBundle:Articulo u WHERE u.idioma=:idioma order by u.id desc ')
->setParameter('idioma', $idioma);
$categorias = $queryCategorias->getResult();
$articulos = $queryArticulos->getResult();
return $this->render('projectAdminprincipalBundle:Default:productoDetalle.html.twig',
array('categoria' => $categorias, 'producto' => $producto,
'productoAsoc' => $productoAsoc, 'articulos' => $articulos , 'idioma' => $idioma));
}
public function formularioContactoAction() {
$em = $this->getDoctrine()->getManager();
$session = $this->getRequest()->getSession();
$idioma = $session->get('idioma');
if ($idioma == 'ingles') {
$idioma = 'ingles';
} else {
$idioma = 'español';
}
$queryCategorias = $em->createQuery('SELECT u from projectAdminloginBundle:Categoria u WHERE u.idioma=:idioma order by u.id desc ')
->setParameter('idioma', $idioma);
$queryArticulos = $em->createQuery('SELECT u from projectAdminloginBundle:Articulo u WHERE u.idioma=:idioma order by u.id desc ')
->setParameter('idioma', $idioma);
$categorias = $queryCategorias->getResult();
$articulos = $queryArticulos->getResult();
return $this->render('projectAdminprincipalBundle:Default:formularioContacto.html.twig', array('categoria' => $categorias, 'articulos' => $articulos , 'idioma' => $idioma ));
}
public function vistaArticuloAction() {
$em = $this->getDoctrine()->getManager();
$categorias = $em->getRepository('projectAdminloginBundle:Categoria')->findAll();
return $this->render('projectAdminprincipalBundle:Default:Articulo.html.twig', array('categoria' => $categorias));
}
public function functionDetalleCalugaAction($id) {
$em = $this->getDoctrine()->getManager();
$session = $this->getRequest()->getSession();
$idioma = $session->get('idioma');
if ($idioma == 'ingles') {
$idioma = 'ingles';
} else {
$idioma = 'español';
}
$queryArticulos = $em->createQuery('SELECT u from projectAdminloginBundle:Articulo u WHERE u.idioma=:idioma order by u.id desc ')->setParameter('idioma', $idioma);
$queryCategorias = $em->createQuery('SELECT u from projectAdminloginBundle:Categoria u WHERE u.idioma=:idioma order by u.id desc ')->setParameter('idioma', $idioma);
$articulos = $queryArticulos->getResult();
$categorias = $queryCategorias->getResult();
$caluga = $em->getRepository('projectAdminloginBundle:Caluga')->findOneBy(array('id' => $id));
return $this->render('projectAdminprincipalBundle:Default:articuloCaluga.html.twig', array('caluga' => $caluga, 'categoria' => $categorias, 'articulos' => $articulos, 'idioma' => $idioma));
}
public function sendContactoAction(Request $request) {
$nombre = $request->request->get('nombre');
$email = $request->request->get('email');
$mesanje = $request->request->get('mensaje');
if ($nombre == '' or $email == '' or $mesanje == '') {
return new Response('100');
} else {
$message = \Swift_Message::newInstance()
->setSubject('Contacto')
->setFrom('giorgosbarkos@gmail.com')
->setTo('giorgosbarkos@gmail.com')
->setBody(
$this->renderView(
'projectAdminprincipalBundle:Default:contacto.html.twig', array('nombre' => $nombre, 'email' => $email, 'mensaje' => $mesanje)
)
)
;
$this->get('mailer')->send($message);
return new Response('200');
}
}
public function cargarArticuloAction($id) {
$em = $this->getDoctrine()->getManager();
$session = $this->getRequest()->getSession();
$idioma = $session->get('idioma');
if ($idioma == 'ingles') {
$idioma = 'ingles';
} else {
$idioma = 'español';
}
$em = $this->getDoctrine()->getManager();
$articulo = $em->getRepository('projectAdminloginBundle:Articulo')->findOneBy(array('id' => $id));
$queryArticulos = $em->createQuery('SELECT u from projectAdminloginBundle:Articulo u WHERE u.idioma=:idioma order by u.id desc ')->setParameter('idioma', $idioma);
$queryCategorias = $em->createQuery('SELECT u from projectAdminloginBundle:Categoria u WHERE u.idioma=:idioma order by u.id desc ')->setParameter('idioma', $idioma);
$articulos = $queryArticulos->getResult();
$categorias = $queryCategorias->getResult();
return $this->render('projectAdminprincipalBundle:Default:Articulo.html.twig', array('articulo' => $articulo, 'categoria' => $categorias, 'articulos' => $articulos, 'idioma' => $idioma));
}
public function IdiomasAction() {
$em = $this->getDoctrine()->getManager();
return new Response('100');
}
public function ingles2Action() {
$em = $this->getDoctrine()->getManager();
$session = $this->getRequest()->getSession();
$session->set('idioma', 'ingles');
return $this->redirect('../home');
}
public function espanolAction() {
$em = $this->getDoctrine()->getManager();
$session = $this->getRequest()->getSession();
$session->set('idioma', 'español');
return $this->redirect('../home');
}
} | mit |
the-ress/vscode | src/vs/platform/list/browser/listService.ts | 44339 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { createStyleSheet } from 'vs/base/browser/dom';
import { IListMouseEvent, IListTouchEvent, IListRenderer, IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import { IPagedRenderer, PagedList, IPagedListOptions } from 'vs/base/browser/ui/list/listPaging';
import { DefaultStyleController, IListOptions, IMultipleSelectionController, IOpenController, isSelectionRangeChangeEvent, isSelectionSingleChangeEvent, List, IListAccessibilityProvider, IListOptionsUpdate } from 'vs/base/browser/ui/list/listWidget';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, dispose, IDisposable, toDisposable, DisposableStore, combinedDisposable } from 'vs/base/common/lifecycle';
import { localize } from 'vs/nls';
import { IConfigurationService, getMigratedSettingValue } from 'vs/platform/configuration/common/configuration';
import { Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry';
import { ContextKeyExpr, IContextKey, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IEditorOptions } from 'vs/platform/editor/common/editor';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { Registry } from 'vs/platform/registry/common/platform';
import { attachListStyler, computeStyles, defaultListStyles, IColorMapping } from 'vs/platform/theme/common/styler';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { InputFocusedContextKey } from 'vs/platform/contextkey/common/contextkeys';
import { ObjectTree, IObjectTreeOptions, ICompressibleTreeRenderer, CompressibleObjectTree, ICompressibleObjectTreeOptions, ICompressibleObjectTreeOptionsUpdate } from 'vs/base/browser/ui/tree/objectTree';
import { ITreeRenderer, IAsyncDataSource, IDataSource } from 'vs/base/browser/ui/tree/tree';
import { AsyncDataTree, IAsyncDataTreeOptions, CompressibleAsyncDataTree, ITreeCompressionDelegate, ICompressibleAsyncDataTreeOptions, IAsyncDataTreeOptionsUpdate } from 'vs/base/browser/ui/tree/asyncDataTree';
import { DataTree, IDataTreeOptions } from 'vs/base/browser/ui/tree/dataTree';
import { IKeyboardNavigationEventFilter, IAbstractTreeOptions, RenderIndentGuides, IAbstractTreeOptionsUpdate } from 'vs/base/browser/ui/tree/abstractTree';
import { IAccessibilityService } from 'vs/platform/accessibility/common/accessibility';
export type ListWidget = List<any> | PagedList<any> | ObjectTree<any, any> | DataTree<any, any, any> | AsyncDataTree<any, any, any>;
export const IListService = createDecorator<IListService>('listService');
export interface IListService {
_serviceBrand: undefined;
/**
* Returns the currently focused list widget if any.
*/
readonly lastFocusedList: ListWidget | undefined;
}
interface IRegisteredList {
widget: ListWidget;
extraContextKeys?: (IContextKey<boolean>)[];
}
export class ListService implements IListService {
_serviceBrand: undefined;
private disposables = new DisposableStore();
private lists: IRegisteredList[] = [];
private _lastFocusedWidget: ListWidget | undefined = undefined;
private _hasCreatedStyleController: boolean = false;
get lastFocusedList(): ListWidget | undefined {
return this._lastFocusedWidget;
}
constructor(@IThemeService private readonly _themeService: IThemeService) {
}
register(widget: ListWidget, extraContextKeys?: (IContextKey<boolean>)[]): IDisposable {
if (!this._hasCreatedStyleController) {
this._hasCreatedStyleController = true;
// create a shared default tree style sheet for performance reasons
const styleController = new DefaultStyleController(createStyleSheet(), '');
this.disposables.add(attachListStyler(styleController, this._themeService));
}
if (this.lists.some(l => l.widget === widget)) {
throw new Error('Cannot register the same widget multiple times');
}
// Keep in our lists list
const registeredList: IRegisteredList = { widget, extraContextKeys };
this.lists.push(registeredList);
// Check for currently being focused
if (widget.getHTMLElement() === document.activeElement) {
this._lastFocusedWidget = widget;
}
return combinedDisposable(
widget.onDidFocus(() => this._lastFocusedWidget = widget),
toDisposable(() => this.lists.splice(this.lists.indexOf(registeredList), 1)),
widget.onDidDispose(() => {
this.lists = this.lists.filter(l => l !== registeredList);
if (this._lastFocusedWidget === widget) {
this._lastFocusedWidget = undefined;
}
})
);
}
dispose(): void {
this.disposables.dispose();
}
}
const RawWorkbenchListFocusContextKey = new RawContextKey<boolean>('listFocus', true);
export const WorkbenchListSupportsMultiSelectContextKey = new RawContextKey<boolean>('listSupportsMultiselect', true);
export const WorkbenchListFocusContextKey = ContextKeyExpr.and(RawWorkbenchListFocusContextKey, ContextKeyExpr.not(InputFocusedContextKey));
export const WorkbenchListHasSelectionOrFocus = new RawContextKey<boolean>('listHasSelectionOrFocus', false);
export const WorkbenchListDoubleSelection = new RawContextKey<boolean>('listDoubleSelection', false);
export const WorkbenchListMultiSelection = new RawContextKey<boolean>('listMultiSelection', false);
export const WorkbenchListSupportsKeyboardNavigation = new RawContextKey<boolean>('listSupportsKeyboardNavigation', true);
export const WorkbenchListAutomaticKeyboardNavigationKey = 'listAutomaticKeyboardNavigation';
export const WorkbenchListAutomaticKeyboardNavigation = new RawContextKey<boolean>(WorkbenchListAutomaticKeyboardNavigationKey, true);
export let didBindWorkbenchListAutomaticKeyboardNavigation = false;
function createScopedContextKeyService(contextKeyService: IContextKeyService, widget: ListWidget): IContextKeyService {
const result = contextKeyService.createScoped(widget.getHTMLElement());
RawWorkbenchListFocusContextKey.bindTo(result);
return result;
}
export const multiSelectModifierSettingKey = 'workbench.list.multiSelectModifier';
export const openModeSettingKey = 'workbench.list.openMode';
export const horizontalScrollingKey = 'workbench.list.horizontalScrolling';
export const keyboardNavigationSettingKey = 'workbench.list.keyboardNavigation';
export const automaticKeyboardNavigationSettingKey = 'workbench.list.automaticKeyboardNavigation';
const treeIndentKey = 'workbench.tree.indent';
const treeRenderIndentGuidesKey = 'workbench.tree.renderIndentGuides';
function getHorizontalScrollingSetting(configurationService: IConfigurationService): boolean {
return getMigratedSettingValue<boolean>(configurationService, horizontalScrollingKey, 'workbench.tree.horizontalScrolling');
}
function useAltAsMultipleSelectionModifier(configurationService: IConfigurationService): boolean {
return configurationService.getValue(multiSelectModifierSettingKey) === 'alt';
}
function useSingleClickToOpen(configurationService: IConfigurationService): boolean {
return configurationService.getValue(openModeSettingKey) !== 'doubleClick';
}
class MultipleSelectionController<T> extends Disposable implements IMultipleSelectionController<T> {
private useAltAsMultipleSelectionModifier: boolean;
constructor(private configurationService: IConfigurationService) {
super();
this.useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
this.registerListeners();
}
private registerListeners(): void {
this._register(this.configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
this.useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(this.configurationService);
}
}));
}
isSelectionSingleChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean {
if (this.useAltAsMultipleSelectionModifier) {
return event.browserEvent.altKey;
}
return isSelectionSingleChangeEvent(event);
}
isSelectionRangeChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean {
return isSelectionRangeChangeEvent(event);
}
}
class WorkbenchOpenController extends Disposable implements IOpenController {
private openOnSingleClick: boolean;
constructor(private configurationService: IConfigurationService, private existingOpenController?: IOpenController) {
super();
this.openOnSingleClick = useSingleClickToOpen(configurationService);
this.registerListeners();
}
private registerListeners(): void {
this._register(this.configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration(openModeSettingKey)) {
this.openOnSingleClick = useSingleClickToOpen(this.configurationService);
}
}));
}
shouldOpen(event: UIEvent): boolean {
if (event instanceof MouseEvent) {
const isLeftButton = event.button === 0;
const isDoubleClick = event.detail === 2;
if (isLeftButton && !this.openOnSingleClick && !isDoubleClick) {
return false;
}
if (isLeftButton /* left mouse button */ || event.button === 1 /* middle mouse button */) {
return this.existingOpenController ? this.existingOpenController.shouldOpen(event) : true;
}
return false;
}
return this.existingOpenController ? this.existingOpenController.shouldOpen(event) : true;
}
}
function toWorkbenchListOptions<T>(options: IListOptions<T>, configurationService: IConfigurationService, keybindingService: IKeybindingService): [IListOptions<T>, IDisposable] {
const disposables = new DisposableStore();
const result = { ...options };
if (options.multipleSelectionSupport !== false && !options.multipleSelectionController) {
const multipleSelectionController = new MultipleSelectionController(configurationService);
result.multipleSelectionController = multipleSelectionController;
disposables.add(multipleSelectionController);
}
const openController = new WorkbenchOpenController(configurationService, options.openController);
result.openController = openController;
disposables.add(openController);
result.keyboardNavigationDelegate = {
mightProducePrintableCharacter(e) {
return keybindingService.mightProducePrintableCharacter(e);
}
};
return [result, disposables];
}
export interface IWorkbenchListOptionsUpdate extends IListOptionsUpdate {
readonly overrideStyles?: IColorMapping;
}
export interface IWorkbenchListOptions<T> extends IWorkbenchListOptionsUpdate, IListOptions<T> {
readonly accessibilityProvider: IListAccessibilityProvider<T>;
}
export class WorkbenchList<T> extends List<T> {
readonly contextKeyService: IContextKeyService;
private readonly configurationService: IConfigurationService;
private readonly themeService: IThemeService;
private listHasSelectionOrFocus: IContextKey<boolean>;
private listDoubleSelection: IContextKey<boolean>;
private listMultiSelection: IContextKey<boolean>;
private _styler: IDisposable | undefined;
private _useAltAsMultipleSelectionModifier: boolean;
constructor(
user: string,
container: HTMLElement,
delegate: IListVirtualDelegate<T>,
renderers: IListRenderer<T, any>[],
options: IWorkbenchListOptions<T>,
@IContextKeyService contextKeyService: IContextKeyService,
@IListService listService: IListService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IKeybindingService keybindingService: IKeybindingService
) {
const horizontalScrolling = typeof options.horizontalScrolling !== 'undefined' ? options.horizontalScrolling : getHorizontalScrollingSetting(configurationService);
const [workbenchListOptions, workbenchListOptionsDisposable] = toWorkbenchListOptions(options, configurationService, keybindingService);
super(user, container, delegate, renderers,
{
keyboardSupport: false,
...computeStyles(themeService.getColorTheme(), defaultListStyles),
...workbenchListOptions,
horizontalScrolling
}
);
this.disposables.add(workbenchListOptionsDisposable);
this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
this.configurationService = configurationService;
this.themeService = themeService;
const listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
listSupportsMultiSelect.set(!(options.multipleSelectionSupport === false));
this.listHasSelectionOrFocus = WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService);
this.listDoubleSelection = WorkbenchListDoubleSelection.bindTo(this.contextKeyService);
this.listMultiSelection = WorkbenchListMultiSelection.bindTo(this.contextKeyService);
this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
this.disposables.add(this.contextKeyService);
this.disposables.add((listService as ListService).register(this));
if (options.overrideStyles) {
this.updateStyles(options.overrideStyles);
}
this.disposables.add(this.onDidChangeSelection(() => {
const selection = this.getSelection();
const focus = this.getFocus();
this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
this.listMultiSelection.set(selection.length > 1);
this.listDoubleSelection.set(selection.length === 2);
}));
this.disposables.add(this.onDidChangeFocus(() => {
const selection = this.getSelection();
const focus = this.getFocus();
this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
}));
this.registerListeners();
}
updateOptions(options: IWorkbenchListOptionsUpdate): void {
super.updateOptions(options);
if (options.overrideStyles) {
this.updateStyles(options.overrideStyles);
}
}
dispose(): void {
super.dispose();
if (this._styler) {
this._styler.dispose();
}
}
private updateStyles(styles: IColorMapping): void {
if (this._styler) {
this._styler.dispose();
}
this._styler = attachListStyler(this, this.themeService, styles);
}
private registerListeners(): void {
this.disposables.add(this.configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(this.configurationService);
}
}));
}
get useAltAsMultipleSelectionModifier(): boolean {
return this._useAltAsMultipleSelectionModifier;
}
}
export interface IWorkbenchPagedListOptions<T> extends IWorkbenchListOptionsUpdate, IPagedListOptions<T> {
readonly accessibilityProvider: IListAccessibilityProvider<T>;
}
export class WorkbenchPagedList<T> extends PagedList<T> {
readonly contextKeyService: IContextKeyService;
private readonly configurationService: IConfigurationService;
private readonly disposables: DisposableStore;
private _useAltAsMultipleSelectionModifier: boolean;
constructor(
user: string,
container: HTMLElement,
delegate: IListVirtualDelegate<number>,
renderers: IPagedRenderer<T, any>[],
options: IWorkbenchPagedListOptions<T>,
@IContextKeyService contextKeyService: IContextKeyService,
@IListService listService: IListService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IKeybindingService keybindingService: IKeybindingService
) {
const horizontalScrolling = typeof options.horizontalScrolling !== 'undefined' ? options.horizontalScrolling : getHorizontalScrollingSetting(configurationService);
const [workbenchListOptions, workbenchListOptionsDisposable] = toWorkbenchListOptions(options, configurationService, keybindingService);
super(user, container, delegate, renderers,
{
keyboardSupport: false,
...computeStyles(themeService.getColorTheme(), defaultListStyles),
...workbenchListOptions,
horizontalScrolling
}
);
this.disposables = new DisposableStore();
this.disposables.add(workbenchListOptionsDisposable);
this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
this.configurationService = configurationService;
const listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
listSupportsMultiSelect.set(!(options.multipleSelectionSupport === false));
this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
this.disposables.add(this.contextKeyService);
this.disposables.add((listService as ListService).register(this));
if (options.overrideStyles) {
this.disposables.add(attachListStyler(this, themeService, options.overrideStyles));
}
this.registerListeners();
}
private registerListeners(): void {
this.disposables.add(this.configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(this.configurationService);
}
}));
}
get useAltAsMultipleSelectionModifier(): boolean {
return this._useAltAsMultipleSelectionModifier;
}
dispose(): void {
super.dispose();
this.disposables.dispose();
}
}
export interface IOpenResourceOptions {
editorOptions: IEditorOptions;
sideBySide: boolean;
element: any;
payload: any;
}
export interface IResourceResultsNavigationOptions {
openOnFocus: boolean;
}
export interface IOpenEvent<T> {
editorOptions: IEditorOptions;
sideBySide: boolean;
element: T;
browserEvent?: UIEvent;
}
export interface IResourceNavigatorOptions {
readonly openOnFocus?: boolean;
readonly openOnSelection?: boolean;
readonly openOnSingleClick?: boolean;
}
export interface SelectionKeyboardEvent extends KeyboardEvent {
preserveFocus?: boolean;
}
export function getSelectionKeyboardEvent(typeArg = 'keydown', preserveFocus?: boolean): SelectionKeyboardEvent {
const e = new KeyboardEvent(typeArg);
(<SelectionKeyboardEvent>e).preserveFocus = preserveFocus;
return e;
}
abstract class ResourceNavigator<T> extends Disposable {
private readonly options: IResourceNavigatorOptions;
private readonly _onDidOpenResource = new Emitter<IOpenEvent<T | null>>();
readonly onDidOpenResource: Event<IOpenEvent<T | null>> = this._onDidOpenResource.event;
constructor(
private readonly treeOrList: {
getFocus(): (T | null)[],
getSelection(): (T | null)[],
setSelection(elements: (T | null)[], browserEvent?: UIEvent): void,
onDidChangeFocus: Event<{ browserEvent?: UIEvent }>,
onDidChangeSelection: Event<{ browserEvent?: UIEvent }>,
onDidOpen: Event<{ browserEvent?: UIEvent }>,
readonly openOnSingleClick?: boolean
},
options?: IResourceNavigatorOptions
) {
super();
this.options = { openOnSelection: true, ...(options || {}) };
this.registerListeners();
}
private registerListeners(): void {
if (this.options && this.options.openOnFocus) {
this._register(this.treeOrList.onDidChangeFocus(e => this.onFocus(e.browserEvent)));
}
if (this.options && this.options.openOnSelection) {
this._register(this.treeOrList.onDidChangeSelection(e => this.onSelection(e.browserEvent)));
}
this._register(this.treeOrList.onDidOpen(e => this.onSelection(e.browserEvent)));
}
private onFocus(browserEvent?: UIEvent): void {
const focus = this.treeOrList.getFocus();
this.treeOrList.setSelection(focus, browserEvent);
if (!browserEvent) {
return;
}
const isMouseEvent = browserEvent && browserEvent instanceof MouseEvent;
if (!isMouseEvent) {
const preserveFocus = (browserEvent instanceof KeyboardEvent && typeof (<SelectionKeyboardEvent>browserEvent).preserveFocus === 'boolean') ?
!!(<SelectionKeyboardEvent>browserEvent).preserveFocus :
true;
this.open(preserveFocus, false, false, browserEvent);
}
}
private onSelection(browserEvent?: MouseEvent | UIEvent): void {
if (!browserEvent || browserEvent.type === 'contextmenu') {
return;
}
const isKeyboardEvent = browserEvent instanceof KeyboardEvent;
const isMiddleClick = browserEvent instanceof MouseEvent ? browserEvent.button === 1 : false;
const isDoubleClick = browserEvent.detail === 2;
const preserveFocus = (browserEvent instanceof KeyboardEvent && typeof (<SelectionKeyboardEvent>browserEvent).preserveFocus === 'boolean') ?
!!(<SelectionKeyboardEvent>browserEvent).preserveFocus :
!isDoubleClick;
if (this.options.openOnSingleClick || this.treeOrList.openOnSingleClick || isDoubleClick || isKeyboardEvent) {
const sideBySide = browserEvent instanceof MouseEvent && (browserEvent.ctrlKey || browserEvent.metaKey || browserEvent.altKey);
this.open(preserveFocus, isDoubleClick || isMiddleClick, sideBySide, browserEvent);
}
}
private open(preserveFocus: boolean, pinned: boolean, sideBySide: boolean, browserEvent?: UIEvent): void {
this._onDidOpenResource.fire({
editorOptions: {
preserveFocus,
pinned,
revealIfVisible: true
},
sideBySide,
element: this.treeOrList.getSelection()[0],
browserEvent
});
}
}
export class ListResourceNavigator<T> extends ResourceNavigator<number> {
constructor(list: WorkbenchList<T> | WorkbenchPagedList<T>, options?: IResourceNavigatorOptions) {
super(list, options);
}
}
export class TreeResourceNavigator<T, TFilterData> extends ResourceNavigator<T> {
constructor(tree: WorkbenchObjectTree<T, TFilterData> | WorkbenchCompressibleObjectTree<T, TFilterData> | WorkbenchDataTree<any, T, TFilterData> | WorkbenchAsyncDataTree<any, T, TFilterData> | WorkbenchCompressibleAsyncDataTree<any, T, TFilterData>, options: IResourceNavigatorOptions = {}) {
super(tree, options);
}
}
function createKeyboardNavigationEventFilter(container: HTMLElement, keybindingService: IKeybindingService): IKeyboardNavigationEventFilter {
let inChord = false;
return event => {
if (inChord) {
inChord = false;
return false;
}
const result = keybindingService.softDispatch(event, container);
if (result && result.enterChord) {
inChord = true;
return false;
}
inChord = false;
return true;
};
}
export interface IWorkbenchObjectTreeOptions<T, TFilterData> extends IObjectTreeOptions<T, TFilterData> {
readonly accessibilityProvider: IListAccessibilityProvider<T>;
readonly overrideStyles?: IColorMapping;
}
export class WorkbenchObjectTree<T extends NonNullable<any>, TFilterData = void> extends ObjectTree<T, TFilterData> {
private internals: WorkbenchTreeInternals<any, T, TFilterData>;
get contextKeyService(): IContextKeyService { return this.internals.contextKeyService; }
get useAltAsMultipleSelectionModifier(): boolean { return this.internals.useAltAsMultipleSelectionModifier; }
constructor(
user: string,
container: HTMLElement,
delegate: IListVirtualDelegate<T>,
renderers: ITreeRenderer<T, TFilterData, any>[],
options: IWorkbenchObjectTreeOptions<T, TFilterData>,
@IContextKeyService contextKeyService: IContextKeyService,
@IListService listService: IListService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IKeybindingService keybindingService: IKeybindingService,
@IAccessibilityService accessibilityService: IAccessibilityService
) {
const { options: treeOptions, getAutomaticKeyboardNavigation, disposable } = workbenchTreeDataPreamble<T, TFilterData, IWorkbenchObjectTreeOptions<T, TFilterData>>(container, options, contextKeyService, configurationService, keybindingService, accessibilityService);
super(user, container, delegate, renderers, treeOptions);
this.disposables.add(disposable);
this.internals = new WorkbenchTreeInternals(this, treeOptions, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService);
this.disposables.add(this.internals);
}
}
export interface IWorkbenchCompressibleObjectTreeOptionsUpdate extends ICompressibleObjectTreeOptionsUpdate {
readonly overrideStyles?: IColorMapping;
}
export interface IWorkbenchCompressibleObjectTreeOptions<T, TFilterData> extends IWorkbenchCompressibleObjectTreeOptionsUpdate, ICompressibleObjectTreeOptions<T, TFilterData> {
readonly accessibilityProvider: IListAccessibilityProvider<T>;
}
export class WorkbenchCompressibleObjectTree<T extends NonNullable<any>, TFilterData = void> extends CompressibleObjectTree<T, TFilterData> {
private internals: WorkbenchTreeInternals<any, T, TFilterData>;
get contextKeyService(): IContextKeyService { return this.internals.contextKeyService; }
get useAltAsMultipleSelectionModifier(): boolean { return this.internals.useAltAsMultipleSelectionModifier; }
constructor(
user: string,
container: HTMLElement,
delegate: IListVirtualDelegate<T>,
renderers: ICompressibleTreeRenderer<T, TFilterData, any>[],
options: IWorkbenchCompressibleObjectTreeOptions<T, TFilterData>,
@IContextKeyService contextKeyService: IContextKeyService,
@IListService listService: IListService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IKeybindingService keybindingService: IKeybindingService,
@IAccessibilityService accessibilityService: IAccessibilityService
) {
const { options: treeOptions, getAutomaticKeyboardNavigation, disposable } = workbenchTreeDataPreamble<T, TFilterData, IWorkbenchCompressibleObjectTreeOptions<T, TFilterData>>(container, options, contextKeyService, configurationService, keybindingService, accessibilityService);
super(user, container, delegate, renderers, treeOptions);
this.disposables.add(disposable);
this.internals = new WorkbenchTreeInternals(this, treeOptions, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService);
this.disposables.add(this.internals);
}
updateOptions(options: IWorkbenchCompressibleObjectTreeOptionsUpdate = {}): void {
super.updateOptions(options);
if (options.overrideStyles) {
this.internals.updateStyleOverrides(options.overrideStyles);
}
}
}
export interface IWorkbenchDataTreeOptionsUpdate extends IAbstractTreeOptionsUpdate {
readonly overrideStyles?: IColorMapping;
}
export interface IWorkbenchDataTreeOptions<T, TFilterData> extends IWorkbenchDataTreeOptionsUpdate, IDataTreeOptions<T, TFilterData> {
readonly accessibilityProvider: IListAccessibilityProvider<T>;
}
export class WorkbenchDataTree<TInput, T, TFilterData = void> extends DataTree<TInput, T, TFilterData> {
private internals: WorkbenchTreeInternals<TInput, T, TFilterData>;
get contextKeyService(): IContextKeyService { return this.internals.contextKeyService; }
get useAltAsMultipleSelectionModifier(): boolean { return this.internals.useAltAsMultipleSelectionModifier; }
constructor(
user: string,
container: HTMLElement,
delegate: IListVirtualDelegate<T>,
renderers: ITreeRenderer<T, TFilterData, any>[],
dataSource: IDataSource<TInput, T>,
options: IWorkbenchDataTreeOptions<T, TFilterData>,
@IContextKeyService contextKeyService: IContextKeyService,
@IListService listService: IListService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IKeybindingService keybindingService: IKeybindingService,
@IAccessibilityService accessibilityService: IAccessibilityService
) {
const { options: treeOptions, getAutomaticKeyboardNavigation, disposable } = workbenchTreeDataPreamble<T, TFilterData, IWorkbenchDataTreeOptions<T, TFilterData>>(container, options, contextKeyService, configurationService, keybindingService, accessibilityService);
super(user, container, delegate, renderers, dataSource, treeOptions);
this.disposables.add(disposable);
this.internals = new WorkbenchTreeInternals(this, treeOptions, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService);
this.disposables.add(this.internals);
}
updateOptions(options: IWorkbenchDataTreeOptionsUpdate = {}): void {
super.updateOptions(options);
if (options.overrideStyles) {
this.internals.updateStyleOverrides(options.overrideStyles);
}
}
}
export interface IWorkbenchAsyncDataTreeOptionsUpdate extends IAsyncDataTreeOptionsUpdate {
readonly overrideStyles?: IColorMapping;
}
export interface IWorkbenchAsyncDataTreeOptions<T, TFilterData> extends IWorkbenchAsyncDataTreeOptionsUpdate, IAsyncDataTreeOptions<T, TFilterData> {
readonly accessibilityProvider: IListAccessibilityProvider<T>;
}
export class WorkbenchAsyncDataTree<TInput, T, TFilterData = void> extends AsyncDataTree<TInput, T, TFilterData> {
private internals: WorkbenchTreeInternals<TInput, T, TFilterData>;
get contextKeyService(): IContextKeyService { return this.internals.contextKeyService; }
get useAltAsMultipleSelectionModifier(): boolean { return this.internals.useAltAsMultipleSelectionModifier; }
constructor(
user: string,
container: HTMLElement,
delegate: IListVirtualDelegate<T>,
renderers: ITreeRenderer<T, TFilterData, any>[],
dataSource: IAsyncDataSource<TInput, T>,
options: IWorkbenchAsyncDataTreeOptions<T, TFilterData>,
@IContextKeyService contextKeyService: IContextKeyService,
@IListService listService: IListService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IKeybindingService keybindingService: IKeybindingService,
@IAccessibilityService accessibilityService: IAccessibilityService
) {
const { options: treeOptions, getAutomaticKeyboardNavigation, disposable } = workbenchTreeDataPreamble<T, TFilterData, IWorkbenchAsyncDataTreeOptions<T, TFilterData>>(container, options, contextKeyService, configurationService, keybindingService, accessibilityService);
super(user, container, delegate, renderers, dataSource, treeOptions);
this.disposables.add(disposable);
this.internals = new WorkbenchTreeInternals(this, treeOptions, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService);
this.disposables.add(this.internals);
}
updateOptions(options: IWorkbenchAsyncDataTreeOptionsUpdate = {}): void {
super.updateOptions(options);
if (options.overrideStyles) {
this.internals.updateStyleOverrides(options.overrideStyles);
}
}
}
export interface IWorkbenchCompressibleAsyncDataTreeOptions<T, TFilterData> extends ICompressibleAsyncDataTreeOptions<T, TFilterData> {
readonly accessibilityProvider: IListAccessibilityProvider<T>;
readonly overrideStyles?: IColorMapping;
}
export class WorkbenchCompressibleAsyncDataTree<TInput, T, TFilterData = void> extends CompressibleAsyncDataTree<TInput, T, TFilterData> {
private internals: WorkbenchTreeInternals<TInput, T, TFilterData>;
get contextKeyService(): IContextKeyService { return this.internals.contextKeyService; }
get useAltAsMultipleSelectionModifier(): boolean { return this.internals.useAltAsMultipleSelectionModifier; }
constructor(
user: string,
container: HTMLElement,
virtualDelegate: IListVirtualDelegate<T>,
compressionDelegate: ITreeCompressionDelegate<T>,
renderers: ICompressibleTreeRenderer<T, TFilterData, any>[],
dataSource: IAsyncDataSource<TInput, T>,
options: IWorkbenchCompressibleAsyncDataTreeOptions<T, TFilterData>,
@IContextKeyService contextKeyService: IContextKeyService,
@IListService listService: IListService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IKeybindingService keybindingService: IKeybindingService,
@IAccessibilityService accessibilityService: IAccessibilityService
) {
const { options: treeOptions, getAutomaticKeyboardNavigation, disposable } = workbenchTreeDataPreamble<T, TFilterData, IWorkbenchCompressibleAsyncDataTreeOptions<T, TFilterData>>(container, options, contextKeyService, configurationService, keybindingService, accessibilityService);
super(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, treeOptions);
this.disposables.add(disposable);
this.internals = new WorkbenchTreeInternals(this, treeOptions, getAutomaticKeyboardNavigation, options.overrideStyles, contextKeyService, listService, themeService, configurationService, accessibilityService);
this.disposables.add(this.internals);
}
}
function workbenchTreeDataPreamble<T, TFilterData, TOptions extends IAbstractTreeOptions<T, TFilterData> | IAsyncDataTreeOptions<T, TFilterData>>(
container: HTMLElement,
options: TOptions,
contextKeyService: IContextKeyService,
configurationService: IConfigurationService,
keybindingService: IKeybindingService,
accessibilityService: IAccessibilityService,
): { options: TOptions, getAutomaticKeyboardNavigation: () => boolean | undefined, disposable: IDisposable } {
WorkbenchListSupportsKeyboardNavigation.bindTo(contextKeyService);
if (!didBindWorkbenchListAutomaticKeyboardNavigation) {
WorkbenchListAutomaticKeyboardNavigation.bindTo(contextKeyService);
didBindWorkbenchListAutomaticKeyboardNavigation = true;
}
const getAutomaticKeyboardNavigation = () => {
// give priority to the context key value to disable this completely
let automaticKeyboardNavigation = contextKeyService.getContextKeyValue<boolean>(WorkbenchListAutomaticKeyboardNavigationKey);
if (automaticKeyboardNavigation) {
automaticKeyboardNavigation = configurationService.getValue<boolean>(automaticKeyboardNavigationSettingKey);
}
return automaticKeyboardNavigation;
};
const accessibilityOn = accessibilityService.isScreenReaderOptimized();
const keyboardNavigation = accessibilityOn ? 'simple' : configurationService.getValue<string>(keyboardNavigationSettingKey);
const horizontalScrolling = typeof options.horizontalScrolling !== 'undefined' ? options.horizontalScrolling : getHorizontalScrollingSetting(configurationService);
const openOnSingleClick = useSingleClickToOpen(configurationService);
const [workbenchListOptions, disposable] = toWorkbenchListOptions(options, configurationService, keybindingService);
const additionalScrollHeight = options.additionalScrollHeight;
return {
getAutomaticKeyboardNavigation,
disposable,
options: {
// ...options, // TODO@Joao why is this not splatted here?
keyboardSupport: false,
...workbenchListOptions,
indent: configurationService.getValue<number>(treeIndentKey),
renderIndentGuides: configurationService.getValue<RenderIndentGuides>(treeRenderIndentGuidesKey),
automaticKeyboardNavigation: getAutomaticKeyboardNavigation(),
simpleKeyboardNavigation: keyboardNavigation === 'simple',
filterOnType: keyboardNavigation === 'filter',
horizontalScrolling,
openOnSingleClick,
keyboardNavigationEventFilter: createKeyboardNavigationEventFilter(container, keybindingService),
additionalScrollHeight,
hideTwistiesOfChildlessElements: options.hideTwistiesOfChildlessElements
} as TOptions
};
}
class WorkbenchTreeInternals<TInput, T, TFilterData> {
readonly contextKeyService: IContextKeyService;
private hasSelectionOrFocus: IContextKey<boolean>;
private hasDoubleSelection: IContextKey<boolean>;
private hasMultiSelection: IContextKey<boolean>;
private _useAltAsMultipleSelectionModifier: boolean;
private disposables: IDisposable[] = [];
private styler: IDisposable | undefined;
constructor(
private tree: WorkbenchObjectTree<T, TFilterData> | CompressibleObjectTree<T, TFilterData> | WorkbenchDataTree<TInput, T, TFilterData> | WorkbenchAsyncDataTree<TInput, T, TFilterData> | WorkbenchCompressibleAsyncDataTree<TInput, T, TFilterData>,
options: IAbstractTreeOptions<T, TFilterData> | IAsyncDataTreeOptions<T, TFilterData>,
getAutomaticKeyboardNavigation: () => boolean | undefined,
overrideStyles: IColorMapping | undefined,
@IContextKeyService contextKeyService: IContextKeyService,
@IListService listService: IListService,
@IThemeService private themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IAccessibilityService accessibilityService: IAccessibilityService,
) {
this.contextKeyService = createScopedContextKeyService(contextKeyService, tree);
const listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
listSupportsMultiSelect.set(!(options.multipleSelectionSupport === false));
this.hasSelectionOrFocus = WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService);
this.hasDoubleSelection = WorkbenchListDoubleSelection.bindTo(this.contextKeyService);
this.hasMultiSelection = WorkbenchListMultiSelection.bindTo(this.contextKeyService);
this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
const interestingContextKeys = new Set();
interestingContextKeys.add(WorkbenchListAutomaticKeyboardNavigationKey);
const updateKeyboardNavigation = () => {
const accessibilityOn = accessibilityService.isScreenReaderOptimized();
const keyboardNavigation = accessibilityOn ? 'simple' : configurationService.getValue<string>(keyboardNavigationSettingKey);
tree.updateOptions({
simpleKeyboardNavigation: keyboardNavigation === 'simple',
filterOnType: keyboardNavigation === 'filter'
});
};
this.updateStyleOverrides(overrideStyles);
this.disposables.push(
this.contextKeyService,
(listService as ListService).register(tree),
tree.onDidChangeSelection(() => {
const selection = tree.getSelection();
const focus = tree.getFocus();
this.hasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
this.hasMultiSelection.set(selection.length > 1);
this.hasDoubleSelection.set(selection.length === 2);
}),
tree.onDidChangeFocus(() => {
const selection = tree.getSelection();
const focus = tree.getFocus();
this.hasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
}),
configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration(openModeSettingKey)) {
tree.updateOptions({ openOnSingleClick: useSingleClickToOpen(configurationService) });
}
if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
}
if (e.affectsConfiguration(treeIndentKey)) {
const indent = configurationService.getValue<number>(treeIndentKey);
tree.updateOptions({ indent });
}
if (e.affectsConfiguration(treeRenderIndentGuidesKey)) {
const renderIndentGuides = configurationService.getValue<RenderIndentGuides>(treeRenderIndentGuidesKey);
tree.updateOptions({ renderIndentGuides });
}
if (e.affectsConfiguration(keyboardNavigationSettingKey)) {
updateKeyboardNavigation();
}
if (e.affectsConfiguration(automaticKeyboardNavigationSettingKey)) {
tree.updateOptions({ automaticKeyboardNavigation: getAutomaticKeyboardNavigation() });
}
}),
this.contextKeyService.onDidChangeContext(e => {
if (e.affectsSome(interestingContextKeys)) {
tree.updateOptions({ automaticKeyboardNavigation: getAutomaticKeyboardNavigation() });
}
}),
accessibilityService.onDidChangeScreenReaderOptimized(() => updateKeyboardNavigation())
);
}
get useAltAsMultipleSelectionModifier(): boolean {
return this._useAltAsMultipleSelectionModifier;
}
updateStyleOverrides(overrideStyles?: IColorMapping): void {
dispose(this.styler);
this.styler = overrideStyles ? attachListStyler(this.tree, this.themeService, overrideStyles) : Disposable.None;
}
dispose(): void {
this.disposables = dispose(this.disposables);
dispose(this.styler);
this.styler = undefined;
}
}
const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration);
configurationRegistry.registerConfiguration({
'id': 'workbench',
'order': 7,
'title': localize('workbenchConfigurationTitle', "Workbench"),
'type': 'object',
'properties': {
[multiSelectModifierSettingKey]: {
'type': 'string',
'enum': ['ctrlCmd', 'alt'],
'enumDescriptions': [
localize('multiSelectModifier.ctrlCmd', "Maps to `Control` on Windows and Linux and to `Command` on macOS."),
localize('multiSelectModifier.alt', "Maps to `Alt` on Windows and Linux and to `Option` on macOS.")
],
'default': 'ctrlCmd',
'description': localize({
key: 'multiSelectModifier',
comment: [
'- `ctrlCmd` refers to a value the setting can take and should not be localized.',
'- `Control` and `Command` refer to the modifier keys Ctrl or Cmd on the keyboard and can be localized.'
]
}, "The modifier to be used to add an item in trees and lists to a multi-selection with the mouse (for example in the explorer, open editors and scm view). The 'Open to Side' mouse gestures - if supported - will adapt such that they do not conflict with the multiselect modifier.")
},
[openModeSettingKey]: {
'type': 'string',
'enum': ['singleClick', 'doubleClick'],
'default': 'singleClick',
'description': localize({
key: 'openModeModifier',
comment: ['`singleClick` and `doubleClick` refers to a value the setting can take and should not be localized.']
}, "Controls how to open items in trees and lists using the mouse (if supported). For parents with children in trees, this setting will control if a single click expands the parent or a double click. Note that some trees and lists might choose to ignore this setting if it is not applicable. ")
},
[horizontalScrollingKey]: {
'type': 'boolean',
'default': false,
'description': localize('horizontalScrolling setting', "Controls whether lists and trees support horizontal scrolling in the workbench. Warning: turning on this setting has a performance implication.")
},
'workbench.tree.horizontalScrolling': {
'type': 'boolean',
'default': false,
'description': localize('tree horizontalScrolling setting', "Controls whether trees support horizontal scrolling in the workbench."),
'deprecationMessage': localize('deprecated', "This setting is deprecated, please use '{0}' instead.", horizontalScrollingKey)
},
[treeIndentKey]: {
'type': 'number',
'default': 8,
minimum: 0,
maximum: 40,
'description': localize('tree indent setting', "Controls tree indentation in pixels.")
},
[treeRenderIndentGuidesKey]: {
type: 'string',
enum: ['none', 'onHover', 'always'],
default: 'onHover',
description: localize('render tree indent guides', "Controls whether the tree should render indent guides.")
},
[keyboardNavigationSettingKey]: {
'type': 'string',
'enum': ['simple', 'highlight', 'filter'],
'enumDescriptions': [
localize('keyboardNavigationSettingKey.simple', "Simple keyboard navigation focuses elements which match the keyboard input. Matching is done only on prefixes."),
localize('keyboardNavigationSettingKey.highlight', "Highlight keyboard navigation highlights elements which match the keyboard input. Further up and down navigation will traverse only the highlighted elements."),
localize('keyboardNavigationSettingKey.filter', "Filter keyboard navigation will filter out and hide all the elements which do not match the keyboard input.")
],
'default': 'highlight',
'description': localize('keyboardNavigationSettingKey', "Controls the keyboard navigation style for lists and trees in the workbench. Can be simple, highlight and filter.")
},
[automaticKeyboardNavigationSettingKey]: {
'type': 'boolean',
'default': true,
markdownDescription: localize('automatic keyboard navigation setting', "Controls whether keyboard navigation in lists and trees is automatically triggered simply by typing. If set to `false`, keyboard navigation is only triggered when executing the `list.toggleKeyboardNavigation` command, for which you can assign a keyboard shortcut.")
}
}
});
| mit |
wind-rider/nuimo-client.ts | examples/serialise.ts | 816 | import "source-map-support/register";
import { withNuimo } from "../src";
import { Update, ClickUpdate, TurnUpdate, SwipeUpdate } from "../src/update/update";
/**
* a serialiser implemented using the update's visitor API
*/
const Serialiser = {
serialise(update: Update) {
return {
type: update.type,
time: update.time,
repr: update.accept(this)
};
},
withClick (clickUpdate: ClickUpdate) {
return { down: clickUpdate.down };
},
withSwipe (swipeUpdate: SwipeUpdate) {
return { direction: swipeUpdate.direction };
},
withTurn (turnUpdate: TurnUpdate) {
return { offset: turnUpdate.offset };
}
};
withNuimo().then(nuimo => {
nuimo.listen(data => {
const serialised = Serialiser.serialise(data);
console.log(JSON.stringify(serialised));
});
});
| mit |
smylydon/msc-project | src/app/models/updateAttempt.js | 469 | 'use strict';
import mongoose from 'mongoose';
// create new schema
const schema = new mongoose.Schema({
type: String,
data: {
cell_id: String,
formula: String,
user_id: String,
browserTimestamp: Boolean,
timestamp: Number,
type: {type:String},
transaction_id: Number
}
}, {
strict: false
});
// virtual date attribute
schema.virtual('date')
.get(() => this._id.getTimestamp());
// assign schema to 'Sheet'
mongoose.model('UpdateAttempt', schema);
| mit |
QuinntyneBrown/virtual-for | examples/filter/filter.ts | 1188 | var app = angular.module("filterApp", ["virtualFor"]);
module Filter {
export class AppController {
public movies: Array<any> = [
{ "name": "Matrix" },
{ "name": "This the End" },
{ "name": "Ghostbusters" },
{ "name": "300" },
{ "name": "Top Five" },
{ "name": "Wedding Crashers" },
{ "name": "Mission Impossible 2" },
{ "name": "Despicable Me" },
{ "name": "Her" },
{ "name": "Argo" },
{ "name": "The Two" },
{ "name": "Pain and No Gain" },
{ "name": "The Wedding Ringer" },
{ "name": "The Town" },
{ "name": "Hangover" },
{ "name": "Terminator" },
{ "name": "Avengers" },
{ "name": "The Transporter" },
{ "name": "X-Men 3" },
{ "name": "Fast 7" },
{ "name": "Coming To America" }];
public filterTerm: string;
public filterFn = (item: any, searchTerm: string) => {
return item.name.indexOf(searchTerm) > -1;
}
}
}
app.controller("appController", [Filter.AppController]);
| mit |
tony19760619/PHPRunnerProjects | Finance/output/LoanStatements_print.php | 3036 | <?php
@ini_set("display_errors","1");
@ini_set("display_startup_errors","1");
require_once("include/dbcommon.php");
require_once("classes/searchclause.php");
require_once('include/xtempl.php');
require_once('classes/printpage.php');
require_once('classes/printpage_details.php');
require_once('classes/reportpage.php');
require_once('classes/reportprintpage.php');
add_nocache_headers();
require_once("include/LoanStatements_variables.php");
if( !Security::processPageSecurity( $strtablename, 'P' ) )
return;
$layout = new TLayout("print", "RoundedOffice", "MobileOffice");
$layout->version = 2;
$layout->blocks["center"] = array();
$layout->containers["pageheader"] = array();
$layout->container_properties["pageheader"] = array( "print" => "repeat" );
$layout->containers["pageheader"][] = array("name"=>"printheader",
"block"=>"printheader", "substyle"=>1 );
$layout->containers["pageheader"][] = array("name"=>"page_of_print",
"block"=>"page_number", "substyle"=>1 );
$layout->skins["pageheader"] = "empty";
$layout->blocks["center"][] = "pageheader";
$layout->containers["grid"] = array();
$layout->container_properties["grid"] = array( );
$layout->containers["grid"][] = array("name"=>"printgridnext",
"block"=>"grid_block", "substyle"=>1 );
$layout->skins["grid"] = "grid";
$layout->blocks["center"][] = "grid";
$layout->blocks["top"] = array();
$layout->containers["pdf"] = array();
$layout->container_properties["pdf"] = array( "print" => "none" );
$layout->containers["pdf"][] = array("name"=>"printbuttons",
"block"=>"printbuttons", "substyle"=>1 );
$layout->skins["pdf"] = "empty";
$layout->blocks["top"][] = "pdf";
$layout->skins["master"] = "empty";
$layout->blocks["top"][] = "master";
$page_layouts["LoanStatements_print"] = $layout;
$layout->skinsparams = array();
$layout->skinsparams["empty"] = array("button"=>"button2");
$layout->skinsparams["menu"] = array("button"=>"button1");
$layout->skinsparams["hmenu"] = array("button"=>"button1");
$layout->skinsparams["undermenu"] = array("button"=>"button1");
$layout->skinsparams["fields"] = array("button"=>"button1");
$layout->skinsparams["form"] = array("button"=>"button1");
$layout->skinsparams["1"] = array("button"=>"button1");
$layout->skinsparams["2"] = array("button"=>"button1");
$layout->skinsparams["3"] = array("button"=>"button1");
$xt = new Xtempl();
$id = postvalue("id");
$id = $id != "" ? $id : 1;
//array of params for classes
$params = array();
$params["id"] = $id;
$params["xt"] = &$xt;
$params["pageType"] = PAGE_PRINT;
$params["tName"] = $strTableName;
$params["selectedRecords"] = PrintPage::readSelectedRecordsFromRequest( "LoanStatements" );
$params["allPagesMode"] = postvalue("all");
$params["pdfMode"] = postvalue("pdf");
$params["pdfContent"] = postvalue("htmlPdfContent");
$params["pdfWidth"] = postvalue("width");
$params["detailTables"] = postvalue("details");
$params["splitByRecords"] = postvalue("records");
$pageObject = new PrintPage($params);
$pageObject->init();
$pageObject->process();
?> | mit |