code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
<?php
namespace HiFebriansyah\LaravelContentManager\Traits;
use Form;
use Illuminate\Support\MessageBag;
use Carbon;
use Session;
trait Generator
{
public function generateForm($class, $columns, $model)
{
$lcm = $model->getConfigs();
$errors = Session::get('errors', new MessageBag());
$isDebug = (request()->input('debug') == true);
if ($model[$model->getKeyName()]) {
echo Form::model($model, ['url' => url('lcm/gen/'.$class.'/1'), 'method' => 'post', 'files' => true]);
} else {
echo Form::model('', ['url' => url('lcm/gen/'.$class), 'method' => 'post', 'files' => true]);
}
foreach ($columns as $column) {
if (strpos($column->Extra, 'auto_increment') === false && !in_array($column->Field, $lcm['hides'])) {
$readOnly = (in_array($column->Field, $lcm['readOnly'])) ? 'readonly' : '';
if (!$model[$column->Field] && $column->Default != '') {
if ($column->Default == 'CURRENT_TIMESTAMP') {
$mytime = Carbon::now();
$model->{$column->Field} = $mytime->toDateTimeString();
} else {
$model->{$column->Field} = $column->Default;
}
}
echo '<div class="form-group '.($errors->has($column->Field) ? 'has-error' : '').'">';
if (in_array($column->Field, $lcm['files'])) {
echo Form::label($column->Field, str_replace('_', ' ', $column->Field));
echo Form::file($column->Field, [$readOnly]);
} elseif (strpos($column->Key, 'MUL') !== false) {
$reference = $model->getReference($column->Field);
$referencedClass = '\\App\\Models\\'.studly_case(str_singular($reference->REFERENCED_TABLE_NAME));
$referencedClass = new $referencedClass();
$referencedClassLcm = $referencedClass->getConfigs();
$labelName = str_replace('_', ' ', $column->Field);
$labelName = str_replace('id', ':'.$referencedClassLcm['columnLabel'], $labelName);
echo Form::label($column->Field, $labelName);
echo Form::select($column->Field, ['' => '---'] + $referencedClass::lists($referencedClassLcm['columnLabel'], 'id')->all(), null, ['id' => $column->Field, 'class' => 'form-control', $readOnly]);
} elseif (strpos($column->Type, 'char') !== false) {
echo Form::label($column->Field, str_replace('_', ' ', $column->Field));
echo Form::text($column->Field, $model[$column->Field], ['class' => 'form-control', $readOnly]);
} elseif (strpos($column->Type, 'text') !== false) {
echo Form::label($column->Field, str_replace('_', ' ', $column->Field));
echo Form::textarea($column->Field, $model[$column->Field], ['class' => 'form-control', $readOnly]);
} elseif (strpos($column->Type, 'int') !== false) {
echo Form::label($column->Field, str_replace('_', ' ', $column->Field));
echo Form::number($column->Field, $model[$column->Field], ['class' => 'form-control', $readOnly]);
} elseif (strpos($column->Type, 'timestamp') !== false || strpos($column->Type, 'date') !== false) {
echo Form::label($column->Field, str_replace('_', ' ', $column->Field));
echo Form::text($column->Field, $model[$column->Field], ['class' => 'form-control has-datepicker', $readOnly]);
} else {
echo Form::label($column->Field, str_replace('_', ' ', $column->Field.' [undetect]'));
echo Form::text($column->Field, $model[$column->Field], ['class' => 'form-control', $readOnly]);
}
echo $errors->first($column->Field, '<p class="help-block">:message</p>');
echo '</div>';
if ($isDebug) {
echo '<pre>', var_dump($column), '</pre>';
}
}
}
foreach ($lcm['checkboxes'] as $key => $value) {
echo Form::checkbox('name', 'value');
}
echo '<button type="submit" class="btn btn-info"><i class="fa fa-save"></i>'.(($model[$model->getKeyName()]) ? 'Update' : 'Save').'</button>';
Form::close();
if ($isDebug) {
echo '<pre>', var_dump($errors), '</pre>';
}
}
}
| hifebriansyah/laravel-content-manager | src/Traits/Generator.php | PHP | mit | 4,601 |
# Recipe-Box
An implamentation of freeCodeCamp's Recipe Box
| devNoiseConsulting/Recipe-Box | README.md | Markdown | mit | 60 |
---
layout: post
title: bbcp
tags: [Network, Linux, Security]
---
In this post, we document how we installed and configured [BBCP](https://www.slac.stanford.edu/~abh/bbcp/) on [pulpo-dtn]({{ site.baseurl }}{% post_url 2017-2-9-pulpos %}).<!-- more -->
* Table of Contents
{:toc}
## Installation
For simplicity, We simply downloaded a precompiled [bbcp binary executable](http://www.slac.stanford.edu/~abh/bbcp/bin/) and placed it in `/usr/local/bin`:
{% highlight shell_session %}
# cd /usr/local/bin/
# wget http://www.slac.stanford.edu/~abh/bbcp/bin/amd64_rhel60/bbcp
# chmod +x bbcp
{% endhighlight %}
We note in passing that although the binary executable was built for 64-bit RHEL 6, it works without issue on RHEL/CentOS 7.
Create account for Jeffrey LeFevre on **pulpo-dtn**:
{% highlight shell_session %}
# ldapsearch -x -H ldap://ldap-blue.ucsc.edu -LLL 'uid=jlefevre'
dn: uid=jlefevre,ou=people,dc=ucsc,dc=edu
gidNumber: 100000
uidNumber: 28981
# groupadd -g 28981 jlefevre
# useradd -u 28981 -g jlefevre -c "Jeffrey LeFevre" -m -d /mnt/pulpos/jlefevre jlefevre
{% endhighlight %}
## Firewall
Append the following 2 lines to `/etc/services`:
{% highlight conf %}
bbcpfirst 60000/tcp # bbcp
bbcplast 60015/tcp # bbcp
{% endhighlight %}
Open inbound TCP ports 60000 - 60015 from any using FirewallD:
{% highlight shell_session %}
# firewall-cmd --permanent --zone=public --add-port=60000-60015/tcp
success
# firewall-cmd --reload
success
{% endhighlight %}
## Testing
Similarly install BBCP on on the 4-GPU workstation [Hydra]({{ site.baseurl }}{% post_url 2017-7-28-hydra %}).
Transfer a 4GB file from *hydra* to *pulpo-dtn*:
{% highlight shell_session %}
$ bbcp -P 1 -F 4GB.dat [email protected]:/mnt/pulpos/jlefevre/4GB.dat
{% endhighlight %}
**NOTE**:
1). We must use `-F` option, which forces the copy by not checking if there is enough free space on the target host, in order work around a bug in Ceph Luminous; otherwise we'll get the following error:
{% highlight plaintext %}
bbcp: Insufficient space to copy all the files from hydra.soe.ucsc.edu
{% endhighlight %}
2). BBCP doesn't honor *ssh_config*. If I place the following stanza in `~/.ssh/config` on hydra:
{% highlight conf %}
Host pd
HostName pulpo-dtn.ucsc.edu
User jlefevre
IdentityFile ~/.ssh/pulpos
{% endhighlight %}
and attempt a transfer using the following command (`pd` instead of `[email protected]`):
{% highlight shell_session %}
$ bbcp -P 1 -F 4GB.dat pd:/mnt/pulpos/jlefevre/4GB.dat
{% endhighlight %}
the command will fail:
{% highlight plaintext %}
bbcp: Unable to connect to (null) ; Name or service not known
bbcp: Unable to allocate more than 0 of 4 data streams.
bbcp: Accept timed out on port 60000
bbcp: Unable to allocate more than 0 of 4 data streams.
{% endhighlight %}
3). If we use a private SSH key that is not the default ~/.ssh/identity, ~/.ssh/id_dsa, ~/.ssh/id_ecdsa, ~/.ssh/id_ed25519 or ~/.ssh/id_rsa*id_rsa*, we can use the `-i` option to specify the key. For example:
{% highlight shell_session %}
$ bbcp -i ~/.ssh/pulpos -P 1 -F 4GB.dat [email protected]:/mnt/pulpos/jlefevre/4GB.dat
{% endhighlight %}
| shawfdong/shawfdong.github.io | _posts/2018-3-2-bbcp.md | Markdown | mit | 3,228 |
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
/**
* Weekly controller.
*
* @Route("/weekly")
*/
class WeeklyController extends Controller
{
/**
* @Route("/", name="default")
*/
public function defaultAction()
{
$BOL = new \DateTime();
$BOL->setDate(1982, 10, 29);
$EOL = new \DateTime();
$EOL->setDate(1982, 10, 29)
->add(new \DateInterval('P90Y'));
$weeksLived = $BOL->diff(new \DateTime())->days / 7;
return $this->render('AppBundle:weekly:index.html.twig', [
'BOL' => $BOL,
'EOL' => $EOL,
'weeksLived' => $weeksLived,
]);
}
}
| alexseif/myapp | src/AppBundle/Controller/WeeklyController.php | PHP | mit | 765 |
cocoalumberjackTest
===================
## setting
platform :ios, '7.0'
pod 'BlocksKit'
pod 'SVProgressHUD'
pod 'CocoaLumberjack'
$ pod install
### xxx-Prefix.pch
#ifdef DEBUG
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#else
static const int ddLogLevel = LOG_LEVEL_OFF;
#endif
and add new formatfile , like CLTCustomFormatter in this sample Source .
and write in
### AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
DDTTYLogger *ttyLogger = [DDTTYLogger sharedInstance];
ttyLogger.logFormatter = [[CLTCustomFormatter alloc] init];
[DDLog addLogger:ttyLogger];
// setting log save dir.
NSString *logPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Logs/"];
DDLogFileManagerDefault *logFileManager = [[DDLogFileManagerDefault alloc] initWithLogsDirectory:logPath];
self.fileLogger = [[DDFileLogger alloc] initWithLogFileManager:logFileManager];
self.fileLogger.logFormatter = [[CLTCustomFormatter alloc] init];
self.fileLogger.maximumFileSize = 10 * 1024 * 1024;
self.fileLogger.logFileManager.maximumNumberOfLogFiles = 5;
[DDLog addLogger:self.fileLogger];
DDLogInfo(@"%@", self.fileLogger.logFileManager.logsDirectory);
return YES;
}
and use, import your new formatter and write above.
DDLogError(@"Paper Jam!");
DDLogWarn(@"Low toner.");
DDLogInfo(@"Doc printed.");
DDLogDebug(@"Debugging");
DDLogVerbose(@"Init doc_parse"); .
| jumbo-in-Jap/cocoalumberjackTest | README.md | Markdown | mit | 1,723 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>WebApp</title>
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<link href="WebApp.Client.styles.css" rel="stylesheet" />
<link href="manifest.json" rel="manifest" />
<link rel="apple-touch-icon" sizes="512x512" href="icon-512.png" />
</head>
<body>
<div id="app">Loading...</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="" class="reload">Reload</a>
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.webassembly.js"></script>
<script>navigator.serviceWorker.register('service-worker.js');</script>
</body>
</html>
| mkjeff/secs4net | samples/WebApp/Client/wwwroot/index.html | HTML | mit | 921 |
/**
* The MIT License
*
* Copyright (C) 2015 Asterios Raptis
*
* 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 de.alpharogroup.user.repositories;
import org.springframework.stereotype.Repository;
import de.alpharogroup.db.dao.jpa.JpaEntityManagerDao;
import de.alpharogroup.user.entities.RelationPermissions;
@Repository("relationPermissionsDao")
public class RelationPermissionsDao extends JpaEntityManagerDao<RelationPermissions, Integer>
{
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = 1L;
} | lightblueseas/user-data | user-entities/src/main/java/de/alpharogroup/user/repositories/RelationPermissionsDao.java | Java | mit | 1,582 |
#////////////////////////////////////////////////////////////////////////////
#//
#// This file is part of RTIMULib
#//
#// Copyright (c) 2014-2015, richards-tech, LLC
#//
#// 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.
# Compiler, tools and options
RTIMULIBPATH = ../../RTIMULib
CC = gcc
CXX = g++
DEFINES =
CFLAGS = -pipe -O2 -Wall -W $(DEFINES)
CXXFLAGS = -pipe -O2 -Wall -W $(DEFINES)
INCPATH = -I. -I$(RTIMULIBPATH)
LINK = g++
LFLAGS = -Wl,-O1
LIBS = -L/usr/lib/arm-linux-gnueabihf
COPY = cp -f
COPY_FILE = $(COPY)
COPY_DIR = $(COPY) -r
STRIP = strip
INSTALL_FILE = install -m 644 -p
INSTALL_DIR = $(COPY_DIR)
INSTALL_PROGRAM = install -m 755 -p
DEL_FILE = rm -f
SYMLINK = ln -f -s
DEL_DIR = rmdir
MOVE = mv -f
CHK_DIR_EXISTS = test -d
MKDIR = mkdir -p
# Output directory
OBJECTS_DIR = objects/
# Files
DEPS = $(RTIMULIBPATH)/RTMath.h \
$(RTIMULIBPATH)/RTIMULib.h \
$(RTIMULIBPATH)/RTIMULibDefs.h \
$(RTIMULIBPATH)/RTIMUHal.h \
$(RTIMULIBPATH)/RTFusion.h \
$(RTIMULIBPATH)/RTFusionKalman4.h \
$(RTIMULIBPATH)/RTFusionRTQF.h \
$(RTIMULIBPATH)/RTFusionAHRS.h \
$(RTIMULIBPATH)/RTIMUSettings.h \
$(RTIMULIBPATH)/RTIMUAccelCal.h \
$(RTIMULIBPATH)/RTIMUGyroCal.h \
$(RTIMULIBPATH)/RTIMUMagCal.h \
$(RTIMULIBPATH)/RTIMUTemperatureCal.h \
$(RTIMULIBPATH)/RTMotion.h \
$(RTIMULIBPATH)/RTIMUCalDefs.h \
$(RTIMULIBPATH)/RunningAverage.h \
$(RTIMULIBPATH)/IMUDrivers/RTIMU.h \
$(RTIMULIBPATH)/IMUDrivers/RTIMUNull.h \
$(RTIMULIBPATH)/IMUDrivers/RTIMUMPU9150.h \
$(RTIMULIBPATH)/IMUDrivers/RTIMUMPU9250.h \
$(RTIMULIBPATH)/IMUDrivers/RTIMUMPU9255.h \
$(RTIMULIBPATH)/IMUDrivers/RTIMUGD20HM303D.h \
$(RTIMULIBPATH)/IMUDrivers/RTIMUGD20M303DLHC.h \
$(RTIMULIBPATH)/IMUDrivers/RTIMUGD20HM303DLHC.h \
$(RTIMULIBPATH)/IMUDrivers/RTIMULSM9DS0.h \
$(RTIMULIBPATH)/IMUDrivers/RTIMULSM9DS1.h \
$(RTIMULIBPATH)/IMUDrivers/RTIMUBMX055.h \
$(RTIMULIBPATH)/IMUDrivers/RTIMUBNO055.h \
$(RTIMULIBPATH)/IMUDrivers/RTPressure.h \
$(RTIMULIBPATH)/IMUDrivers/RTPressureDefs.h \
$(RTIMULIBPATH)/IMUDrivers/RTPressureBMP180.h \
$(RTIMULIBPATH)/IMUDrivers/RTPressureLPS25H.h \
$(RTIMULIBPATH)/IMUDrivers/RTPressureMS5611.h \
$(RTIMULIBPATH)/IMUDrivers/RTPressureMS5637.h \
$(RTIMULIBPATH)/IMUDrivers/RTPressureMS5803.h \
$(RTIMULIBPATH)/IMUDrivers/RTPressureMS5837.h \
$(RTIMULIBPATH)/IMUDrivers/RTHumidity.h \
$(RTIMULIBPATH)/IMUDrivers/RTHumidityDefs.h \
$(RTIMULIBPATH)/IMUDrivers/RTHumidityHTS221.h \
$(RTIMULIBPATH)/IMUDrivers/RTHumidityHTU21D.h \
OBJECTS = objects/RTIMULibDrive11.o \
objects/RTMath.o \
objects/RTIMUHal.o \
objects/RTFusion.o \
objects/RTFusionKalman4.o \
objects/RTFusionRTQF.o \
objects/RTFusionAHRS.o \
objects/RTIMUSettings.o \
objects/RTIMUAccelCal.o \
objects/RTIMUMagCal.o \
objects/RTIMUGyroCal.o \
objects/RTIMUTemperatureCal.o \
objects/RTMotion.o \
objects/RunningAverage.o \
objects/RTIMU.o \
objects/RTIMUNull.o \
objects/RTIMUMPU9150.o \
objects/RTIMUMPU9250.o \
objects/RTIMUMPU9255.o \
objects/RTIMUGD20HM303D.o \
objects/RTIMUGD20M303DLHC.o \
objects/RTIMUGD20HM303DLHC.o \
objects/RTIMULSM9DS0.o \
objects/RTIMULSM9DS1.o \
objects/RTIMUBMX055.o \
objects/RTIMUBNO055.o \
objects/RTPressure.o \
objects/RTPressureBMP180.o \
objects/RTPressureLPS25H.o \
objects/RTPressureMS5611.o \
objects/RTPressureMS5637.o \
objects/RTPressureMS5803.o \
objects/RTPressureMS5837.o \
objects/RTHumidity.o \
objects/RTHumidityHTS221.o \
objects/RTHumidityHTU21D.o \
MAKE_TARGET = RTIMULibDrive11
DESTDIR = Output/
TARGET = Output/$(MAKE_TARGET)
# Build rules
$(TARGET): $(OBJECTS)
@$(CHK_DIR_EXISTS) Output/ || $(MKDIR) Output/
$(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(LIBS)
clean:
-$(DEL_FILE) $(OBJECTS)
-$(DEL_FILE) *~ core *.core
# Compile
$(OBJECTS_DIR)%.o : $(RTIMULIBPATH)/%.cpp $(DEPS)
@$(CHK_DIR_EXISTS) objects/ || $(MKDIR) objects/
$(CXX) -c -o $@ $< $(CFLAGS) $(INCPATH)
$(OBJECTS_DIR)%.o : $(RTIMULIBPATH)/IMUDrivers/%.cpp $(DEPS)
@$(CHK_DIR_EXISTS) objects/ || $(MKDIR) objects/
$(CXX) -c -o $@ $< $(CFLAGS) $(INCPATH)
$(OBJECTS_DIR)RTIMULibDrive11.o : RTIMULibDrive11.cpp $(DEPS)
@$(CHK_DIR_EXISTS) objects/ || $(MKDIR) objects/
$(CXX) -c -o $@ RTIMULibDrive11.cpp $(CFLAGS) $(INCPATH)
# Install
install_target: FORCE
@$(CHK_DIR_EXISTS) $(INSTALL_ROOT)/usr/local/bin/ || $(MKDIR) $(INSTALL_ROOT)/usr/local/bin/
-$(INSTALL_PROGRAM) "Output/$(MAKE_TARGET)" "$(INSTALL_ROOT)/usr/local/bin/$(MAKE_TARGET)"
-$(STRIP) "$(INSTALL_ROOT)/usr/local/bin/$(MAKE_TARGET)"
uninstall_target: FORCE
-$(DEL_FILE) "$(INSTALL_ROOT)/usr/local/bin/$(MAKE_TARGET)"
install: install_target FORCE
uninstall: uninstall_target FORCE
FORCE:
| uutzinger/RTIMULib | Linux/RTIMULibDrive11/Makefile | Makefile | mit | 6,019 |
<?php
/**
* Chronjob that will delete expired nonce tokens every hour
* Author: Sneha Inguva
* Date: 8-2-2014
*/
require_once('../config.php');
require_once('../db/mysqldb.php');
$con = new mysqldb($db_settings1,false);
$stmt = "Delete FROM nonce_values Where expiry_time <= CURRENT_TIMESTAMP";
$result = $con->query($stmt);
?> | si74/peroozBackend | jobs/update_nonce.php | PHP | mit | 339 |
# GTD
<a name="top"></a>
<a href="http://spacemacs.org"><img src="https://cdn.rawgit.com/syl20bnr/spacemacs/442d025779da2f62fc86c2082703697714db6514/assets/spacemacs-badge.svg" alt="Made with Spacemacs">
</a><a href="http://www.twitter.com/zwb_ict"><img src="http://i.imgur.com/tXSoThF.png" alt="Twitter" align="right"></a><br>
***
Spacemacs GTD layer, which based on org-query.
| zwb-ict/.spacemacs.d | layers/gtd/README.md | Markdown | mit | 380 |
---
title: activiti实体类服务组件和实体类
tags: [activiti]
---
### 实体类服务组件
activiti对数据的管理都会提供相应的服务组件。
1)IdentityService,对用户和用户组的管理
2)RepositoryService,流程存储服务组件。主要用于对Activiti中的流程存储的相关数据进行操作。包括流程存储数据的管理、流程部署以及流程的基本操作等。
3)TaskService,提供了操作流程任务的API,包括任务的查询、创建与删除、权限设置和参数设置等。
4)RuntimeService主要用于管理流程在运行时产生的数据以及提供对流程操作的API。
其中流程运行时产生的数据包括流程参数、事件、流程实例以及执行流等。流程的操作包括开始流程、让流程前进等。
### 实体类
activiti中每个实体的实现类均有字节的接口,并且每个实体的实现类名称均为XXXEntity。如Group接口与GroupEntity实现类。
Activiti没有提供任何实体实现类(XXXEntity)的API,如果需要创建这些实体对象,只需调用相应业务组件的方法即可。如创建Group对象,调用indentityService的newGroup方法即可。
### 实体类的查询对象
Activiti中的每个实体对象都对应了查询对象(XXXQuery),具有自己相应的查询方法和排序方法。 | yutian1012/yutian1012.github.io | _posts/language/java/java书籍/疯狂Workflow讲义/activiti常用API/2017-08-05-activiti-service.md | Markdown | mit | 1,370 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WPFProtocolHandler.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| arunjeetsingh/SampleCode | UniversalAppLaunchingWPFApp/WPFProtocolHandler/Properties/Settings.Designer.cs | C# | mit | 1,075 |
Ur/Web
=======================
A set of Sublime Text 2 resources for Ur/Web.
**If you had previously installed this package into your "Packages/User", you
should consider reinstalling as described below to get future updates.**
# Included:
- Language definition for Ur/Web. Provides syntax highlighting in Sublime Text 2
and TextMate
- Snippets for common SML constructions: 'let', 'case', 'fun', 'fn',
'structure', etc
- Example theme "Son of Obsidian" that works with the Ur/Web language definiton
- Build system: will run urweb agains the project file within Sublime
# Installation:
To install, clone the git repository directly inside your
Sublime "Packages" directory. Due to the unfortunate naming of the git repo,
you will need to clone into a specifically named directory for the build
system to work:
git clone https://github.com/gwalborn/UrWeb-Language-Definition.git "SML (Standard ML)"
This way, you'll be able to "git pull" to update
the package, and Sublime will see the changes immediately. You can use the
Preferences>Browse Packages menu within Sublime to get to the Packages
directory.
Otherwise, clone elsewhere and copy the files into a folder called
"UrWeb" in the Packages directory.
# Features:
Syntax highlighing should work automatically with ".ur" and ".urs" files.
The .tmLanguage file should also work with TextMate to provide syntax highlighting.
Snippets will be available for all of the above file types. A full list can be
found through the Tools>Snippets command. To use a snippet, start typing the
name and press tab when the autocomplete window suggests the snippet. Currently
included snippets are: 'case', 'datatype', 'fn', 'fun', 'functor', 'if', 'let',
'signature', 'structure', and 'val'.
The example theme will be available under Preferences>Color Scheme. The example
theme is an example of how to create a theme that matches SML. Most existing
themes should work as this package uses a common naming scheme. This example
.thTheme should also work with TextMate.
The build system will use the "urweb" command to compile the project with the
same basename as the file being edited. The build system can be started with
F7 or Control/Command+B.
On Linux, the build system will be able to locate urweb if it is available on your
PATH variable.
The build system captures error output with a regular expression, so double
clicking on an error in the output window will take you to the file and line
on which the error occured. Alternatively, use F4 and Shift+F4 to cycle through
errors.
# Troubleshooting
First, try closing all files, quitting Sublime, deleting the .cache files in the
"UrWeb" directory under "Packages", and starting Sublime. Then reopen any files.
Finally, consider opening an issue on GitHub.
# Development:
Feel free to fork and contribute to this package. Any additions are
appreciated.
.JSON-* files can be used to generate the .tm* files and vice versa, if you
prefer to work with JSON. You will need the "AAAPackageDev" package for the
JSON build to work. Note that this package uses the .tm* files and excludes
JSON files, so be sure to build the .tm files and don't commit the JSON files.
Also be sure not to commit .cache files.
Originally written by Sean James, while taking 15210 at Carnegie Mellon.
Modified for UrWeb by Gary Walborn.
| gwalborn/UrWeb-Language-Definition | README.md | Markdown | mit | 3,355 |
#!/usr/bin/python
from noisemapper.mapper import *
#from collectors.lib import utils
### Define the object mapper and start mapping
def main():
# utils.drop_privileges()
mapper = NoiseMapper()
mapper.run()
if __name__ == "__main__":
main()
| dustlab/noisemapper | scripts/nmcollector.py | Python | mit | 259 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.6.0_18) on Thu Dec 18 17:18:43 PST 2014 -->
<title>Uses of Class org.xml.sax.helpers.ParserFactory (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.xml.sax.helpers.ParserFactory (Java Platform SE 7 )";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/xml/sax/helpers/ParserFactory.html" title="class in org.xml.sax.helpers">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><strong>Java™ Platform<br>Standard Ed. 7</strong></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/xml/sax/helpers/class-use/ParserFactory.html" target="_top">Frames</a></li>
<li><a href="ParserFactory.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.xml.sax.helpers.ParserFactory" class="title">Uses of Class<br>org.xml.sax.helpers.ParserFactory</h2>
</div>
<div class="classUseContainer">No usage of org.xml.sax.helpers.ParserFactory</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/xml/sax/helpers/ParserFactory.html" title="class in org.xml.sax.helpers">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><strong>Java™ Platform<br>Standard Ed. 7</strong></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/xml/sax/helpers/class-use/ParserFactory.html" target="_top">Frames</a></li>
<li><a href="ParserFactory.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://docs.oracle.com/javase/7/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> <a href="../../../../../../legal/cpyr.html">Copyright</a> © 1993, 2015, Oracle and/or its affiliates. All rights reserved. </font></small></p>
</body>
</html>
| fbiville/annotation-processing-ftw | doc/java/jdk7/org/xml/sax/helpers/class-use/ParserFactory.html | HTML | mit | 4,981 |
---
layout: default
---
{% assign minutes = content | number_of_words | divided_by: 180 %}
{% if minutes == 0 %}
{% assign minutes = 1 %}
{% endif %}
<div class="post-header mb2">
<h2>{{ page.title }}</h2>
<span class="post-meta">{{ page.date | date: "%b %-d, %Y" }}</span><br>
{% if page.update_date %}
<span class="post-meta">Updated: {{ page.update_date | date: "%b %-d, %Y" }}</span><br>
{% endif %}
<span class="post-meta small">
{% if page.minutes %}
{{ page.minutes }} minute read
{% else %}
{{ minutes }} minute read
{% endif %}
</span>
</div>
<article class="post-content">
{{ content }}
</article>
{% if site.show_sharing_icons %}
{% include share_buttons.html %}
{% endif %}
{% if site.show_post_footers %}
{% include post_footer.html %}
{% endif %}
{% if site.disqus_shortname %}
<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = '{{ site.disqus_shortname }}';
var disqus_identifier = '{{ page.id }}';
var disqus_title = '{{ post.title }}';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
{% endif %}
{% if site.show_related_posts %}
<h3 class="related-post-title">Related Posts</h3>
{% for post in site.related_posts %}
<div class="post ml2">
<a href="{{ post.url | prepend: site.baseurl }}" class="post-link">
<h4 class="post-title">{{ post.title }}</h4>
<p class="post-summary">{{ post.summary }}</p>
</a>
</div>
{% endfor %}
{% endif %}
| chufuxi/chufuxi.github.com | _layouts/post.html | HTML | mit | 1,900 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Julas.Utils;
using Julas.Utils.Collections;
using Julas.Utils.Extensions;
using TheArtOfDev.HtmlRenderer.WinForms;
using Ozeki.VoIP;
using VoipClient;
namespace Client
{
public partial class ConversationForm : Form
{
private volatile bool _isInCall = false;
private readonly string _thisUserId;
private readonly string _otherUserId;
private readonly HtmlPanel _htmlPanel;
private readonly Color _textColor = Color.Black;
private readonly Color _timestampColor = Color.DarkGray;
private readonly Color _thisUserColor = Color.DodgerBlue;
private readonly Color _otherUserColor = Color.DarkOrange;
private readonly Color _enabledBtnColor = Color.FromArgb(255, 255, 255);
private readonly Color _disabledBtnColor = Color.FromArgb(226, 226, 226);
private readonly int _fontSize = 1;
private readonly VoipClientModule _voipClient;
public event Action<string> MessageSent;
public event Action Call;
public event Action HangUp;
public ConversationForm(string thisUserId, string otherUserId, string hash_pass, VoipClientModule voipClient)
{
_thisUserId = thisUserId;
_otherUserId = otherUserId;
_voipClient = voipClient;
InitializeComponent();
this.Text = $"Conversation with {otherUserId}";
_htmlPanel = new HtmlPanel();
panel1.Controls.Add(_htmlPanel);
_htmlPanel.Dock = DockStyle.Fill;
_voipClient.PhoneStateChanged += VoipClientOnPhoneStateChanged;
}
public new void Dispose()
{
_voipClient.PhoneStateChanged -= VoipClientOnPhoneStateChanged;
base.Dispose(true);
}
private void VoipClientOnPhoneStateChanged(PhoneState phoneState)
{
Invoke(() =>
{
if (!phoneState.OtherUserId.IsOneOf(null, _otherUserId) || phoneState.Status.IsOneOf(PhoneStatus.Registering))
{
btnCall.Enabled = false;
btnHangUp.Enabled = false;
btnCall.BackColor = _disabledBtnColor;
btnHangUp.BackColor = _disabledBtnColor;
return;
}
else
{
switch (phoneState.Status)
{
case PhoneStatus.Calling:
{
btnCall.Enabled = false;
btnHangUp.Enabled = true;
btnCall.BackColor = _disabledBtnColor;
btnHangUp.BackColor = _enabledBtnColor;
break;
}
case PhoneStatus.InCall:
{
btnCall.Enabled = false;
btnHangUp.Enabled = true;
btnCall.BackColor = _disabledBtnColor;
btnHangUp.BackColor = _enabledBtnColor;
break;
}
case PhoneStatus.IncomingCall:
{
btnCall.Enabled = true;
btnHangUp.Enabled = true;
btnCall.BackColor = _enabledBtnColor;
btnHangUp.BackColor = _enabledBtnColor;
break;
}
case PhoneStatus.Registered:
{
btnCall.Enabled = true;
btnHangUp.Enabled = false;
btnCall.BackColor = _enabledBtnColor;
btnHangUp.BackColor = _disabledBtnColor;
break;
}
}
}
});
}
public void AppendMessageFromOtherUser(string message)
{
AppendMessage(message, _otherUserId, _otherUserColor);
}
private void AppendMessageFromThisUser(string message)
{
AppendMessage(message, _thisUserId, _thisUserColor);
}
private void AppendMessage(string msg, string from, Color nameColor)
{
StringBuilder sb = new StringBuilder();
sb.Append("<p>");
sb.Append($"<b><font color=\"{GetHexColor(nameColor)}\" size=\"{_fontSize}\">{from}</font></b> ");
sb.Append($"<font color=\"{GetHexColor(_timestampColor)}\" size=\"{_fontSize}\">{DateTime.Now.ToString("HH:mm:ss")}</font>");
sb.Append("<br/>");
sb.Append($"<font color=\"{GetHexColor(_textColor)}\" size=\"{_fontSize}\">{msg}</font>");
sb.Append("</p>");
_htmlPanel.Text += sb.ToString();
_htmlPanel.VerticalScroll.Value = _htmlPanel.VerticalScroll.Maximum;
}
private string GetHexColor(Color color)
{
return $"#{color.R.ToString("x2").ToUpper()}{color.G.ToString("x2").ToUpper()}{color.B.ToString("x2").ToUpper()}";
}
private void SendMessage()
{
if (!tbInput.Text.IsNullOrWhitespace())
{
MessageSent?.Invoke(tbInput.Text.Trim());
AppendMessageFromThisUser(tbInput.Text.Trim());
tbInput.Text = "";
tbInput.SelectionStart = 0;
}
}
private void tbInput_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r' || e.KeyChar == '\n')
{
e.Handled = true;
SendMessage();
}
}
private void btnSend_Click(object sender, EventArgs e)
{
SendMessage();
}
private void ConversationForm_Load(object sender, EventArgs e)
{
VoipClientOnPhoneStateChanged(_voipClient.PhoneState);
}
private void Invoke(Action action)
{
if(this.InvokeRequired)
{
this.Invoke(new MethodInvoker(action));
}
else
{
action();
}
}
private void btnCall_Click(object sender, EventArgs e)
{
btnCall.Enabled = false;
btnHangUp.Enabled = false;
btnCall.BackColor = _disabledBtnColor;
btnHangUp.BackColor = _disabledBtnColor;
switch (_voipClient.PhoneState.Status)
{
case PhoneStatus.IncomingCall:
{
_voipClient.AnswerCall();
break;
}
case PhoneStatus.Registered:
{
_voipClient.StartCall(_otherUserId);
break;
}
}
}
private void btnHangUp_Click(object sender, EventArgs e)
{
btnCall.Enabled = false;
btnHangUp.Enabled = false;
btnCall.BackColor = _disabledBtnColor;
btnHangUp.BackColor = _disabledBtnColor;
switch (_voipClient.PhoneState.Status)
{
case PhoneStatus.IncomingCall:
{
_voipClient.RejectCall();
break;
}
case PhoneStatus.InCall:
{
_voipClient.EndCall();
break;
}
case PhoneStatus.Calling:
{
_voipClient.EndCall();
break;
}
}
}
}
}
| EMJK/Projekt_WTI_TIP | Client/ConversationForm.cs | C# | mit | 8,027 |
#ifndef INCLUDED_openfl__legacy_events_KeyboardEvent
#define INCLUDED_openfl__legacy_events_KeyboardEvent
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
#ifndef INCLUDED_openfl__legacy_events_Event
#include <openfl/_legacy/events/Event.h>
#endif
HX_DECLARE_CLASS3(openfl,_legacy,events,Event)
HX_DECLARE_CLASS3(openfl,_legacy,events,KeyboardEvent)
namespace openfl{
namespace _legacy{
namespace events{
class HXCPP_CLASS_ATTRIBUTES KeyboardEvent_obj : public ::openfl::_legacy::events::Event_obj{
public:
typedef ::openfl::_legacy::events::Event_obj super;
typedef KeyboardEvent_obj OBJ_;
KeyboardEvent_obj();
Void __construct(::String type,hx::Null< bool > __o_bubbles,hx::Null< bool > __o_cancelable,hx::Null< int > __o_charCodeValue,hx::Null< int > __o_keyCodeValue,hx::Null< int > __o_keyLocationValue,hx::Null< bool > __o_ctrlKeyValue,hx::Null< bool > __o_altKeyValue,hx::Null< bool > __o_shiftKeyValue,hx::Null< bool > __o_controlKeyValue,hx::Null< bool > __o_commandKeyValue);
public:
inline void *operator new( size_t inSize, bool inContainer=true,const char *inName="openfl._legacy.events.KeyboardEvent")
{ return hx::Object::operator new(inSize,inContainer,inName); }
static hx::ObjectPtr< KeyboardEvent_obj > __new(::String type,hx::Null< bool > __o_bubbles,hx::Null< bool > __o_cancelable,hx::Null< int > __o_charCodeValue,hx::Null< int > __o_keyCodeValue,hx::Null< int > __o_keyLocationValue,hx::Null< bool > __o_ctrlKeyValue,hx::Null< bool > __o_altKeyValue,hx::Null< bool > __o_shiftKeyValue,hx::Null< bool > __o_controlKeyValue,hx::Null< bool > __o_commandKeyValue);
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
//~KeyboardEvent_obj();
HX_DO_RTTI_ALL;
Dynamic __Field(const ::String &inString, hx::PropertyAccess inCallProp);
static bool __GetStatic(const ::String &inString, Dynamic &outValue, hx::PropertyAccess inCallProp);
Dynamic __SetField(const ::String &inString,const Dynamic &inValue, hx::PropertyAccess inCallProp);
static bool __SetStatic(const ::String &inString, Dynamic &ioValue, hx::PropertyAccess inCallProp);
void __GetFields(Array< ::String> &outFields);
static void __register();
::String __ToString() const { return HX_HCSTRING("KeyboardEvent","\xd3","\x8d","\x88","\x91"); }
static void __boot();
static ::String KEY_DOWN;
static ::String KEY_UP;
bool altKey;
int charCode;
bool ctrlKey;
bool controlKey;
bool commandKey;
int keyCode;
int keyLocation;
bool shiftKey;
virtual ::openfl::_legacy::events::Event clone( );
virtual ::String toString( );
};
} // end namespace openfl
} // end namespace _legacy
} // end namespace events
#endif /* INCLUDED_openfl__legacy_events_KeyboardEvent */
| syonfox/PixelPlanetSandbox | haxe/export/linux64/cpp/obj/include/openfl/_legacy/events/KeyboardEvent.h | C | mit | 2,756 |
/*
* PokeDat - A Pokemon Data API.
* Copyright (C) 2015
*
* 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 io.github.kaioru.species;
import java.io.Serializable;
/**
* @todo Class Description
*
* @author Kaioru
**/
public class SpeciesLearnset implements Serializable {
private static final long serialVersionUID = 5370581555765470935L;
}
| Kaioru/PokeDat | PokeDat-Data/src/main/java/io/github/kaioru/species/SpeciesLearnset.java | Java | mit | 1,388 |
今日のコミット
- [bouzuya/rust-sandbox](https://github.com/bouzuya/rust-sandbox) 15 commits
- [add session file creation to log_in](https://github.com/bouzuya/rust-sandbox/commit/342db99d04c7f9e537055a0b114d87c478629413)
- ここまでで mfa log-in サブコマンドが動くようになった
- [add status check to log_in](https://github.com/bouzuya/rust-sandbox/commit/db9da06147fad3181c6737a79c0568c5ac60c855)
- [add post_employee_session to log_in](https://github.com/bouzuya/rust-sandbox/commit/b90d1f6b45a3e771363af02ae18344820056425d)
- [add EmployeeSessionForm to log_in](https://github.com/bouzuya/rust-sandbox/commit/5ccaab4875d6b6d9871bceb5965745188bf212dd)
- [add parse_employee_session_new_html to log_in](https://github.com/bouzuya/rust-sandbox/commit/47daf65a73b417ff73926440e4e8a0d7da667817)
- [add get_employee_session_new to log_in](https://github.com/bouzuya/rust-sandbox/commit/9e0662547959f3775e92de1f7ae6549a1da36eea)
- [add HttpMethod](https://github.com/bouzuya/rust-sandbox/commit/d2a73254df9e162a96a6da510ab24b61ade0f071)
- [add log-in stub](https://github.com/bouzuya/rust-sandbox/commit/1211a967cc240bb2901790cb6e8f4162db18884d)
- [add cli mod](https://github.com/bouzuya/rust-sandbox/commit/a6e2af44a0a4a2c3b37c22ab728ab94dc2a00e28)
- [cargo add structopt](https://github.com/bouzuya/rust-sandbox/commit/0fb686b39aa6b01b0fef4bdc829bcdacc91d4eee)
- [add http_client](https://github.com/bouzuya/rust-sandbox/commit/e3784bf205bead63accd63e8e394f59de5cab270)
- [add reqwest cookies feature](https://github.com/bouzuya/rust-sandbox/commit/dd6515769499c513a927f9107070a4a327435826)
- [sort dependencies](https://github.com/bouzuya/rust-sandbox/commit/e4668ec36453c3596a73ab2ff83f797e2c72180f)
- [cargo add dirs](https://github.com/bouzuya/rust-sandbox/commit/1ed12dd61a97ea9231480ac76ee5af4600a2e061)
- [cargo add dialoguer](https://github.com/bouzuya/rust-sandbox/commit/9536bfc4b8cb163c7feba961401003aaa71ad78d)
- [cargo add anyhow](https://https://github.com/bouzuya/rust-sandbox/commit/3eea3475c62c4b2166fd9ba5d72677772d1570f2)
- [cargo add reqwest](https://github.com/bouzuya/rust-sandbox/commit/7eedf9114855bc6737f64533b0e279ceb7defef2)
- [cargo add scraper](https://github.com/bouzuya/rust-sandbox/commit/f7333bb570dd0faf07217f293c4f02ceddc43a85)
- [cargo new mfa](https://github.com/bouzuya/rust-sandbox/commit/e9096ae0fa496d890dec656049f98430b8bcc506)
- mfa というアプリケーションを追加した
- [bouzuya/rust-atcoder](https://github.com/bouzuya/rust-atcoder) 1 commit
- [abc144](https://github.com/bouzuya/rust-atcoder/commit/015e2f8960ce7fd68b15da09d92cd5ce0e41817b)
- A 〜 C まで淡々と解いた
- D - Water Bottle は解説 AC
- C - Walk on Multiplication Table
- 前はかなり手こずった様子
- N はふたつの整数の掛け算なので約数を列挙して各組で試せば良い
---
コミットログの列挙は手動では厳しいので何か書こう。
---
昨日今日とゆず湯に入っている。ゆずのかおりがする。そりゃそうか。
子どもが喜んでいるらしい。
| bouzuya/blog.bouzuya.net | data/2020/12/2020-12-22.md | Markdown | mit | 3,156 |
export { default } from './ui'
export * from './ui.selectors'
export * from './tabs'
| Trampss/kriya | examples/redux/ui/index.js | JavaScript | mit | 85 |
<?php
/*
* This File is part of the Lucid\Common\Tests\Struct package
*
* (c) iwyg <[email protected]>
*
* For full copyright and license information, please refer to the LICENSE file
* that was distributed with this package.
*/
namespace Lucid\Common\Tests\Struct;
use Lucid\Common\Struct\Items;
/**
* @class ItemsTest
*
* @package Lucid\Common\Tests\Struct
* @version $Id$
* @author iwyg <[email protected]>
*/
class ItemsTest extends \PHPUnit_Framework_TestCase
{
/** @test */
public function testConstructWithData()
{
$list = new Items(1, 2, 3, 4, 5);
$this->assertEquals(5, count($list));
$this->assertEquals([1, 2, 3, 4, 5], $list->toArray());
}
/** @test */
public function testPop()
{
$list = new Items(1, 2, 3, 4, 5);
$this->assertEquals(5, $list->pop());
$this->assertEquals(2, $list->pop(1));
$this->assertEquals(4, $list->pop(2));
}
/** @test */
public function popShouldThrowErrorOnInvalidIndex()
{
$list = new Items(1, 2);
try {
$this->assertEquals(4, $list->remove(3));
} catch (\InvalidArgumentException $e) {
$this->assertTrue(true);
return;
}
$this->fail();
}
/** @test */
public function testInsert()
{
$list = new Items(1, 2, 3, 4, 5);
$list->insert(3, 'foo');
$this->assertEquals([1, 2, 3, 'foo', 4, 5], $list->toArray());
}
/** @test */
public function testCountValue()
{
$list = new Items(1, 'red', 'green', 3, 'blue', 4, 'red', 5);
$this->assertEquals(2, $list->countValue('red'));
$this->assertEquals(1, $list->countValue('green'));
}
/** @test */
public function testSort()
{
$list = new Items(120, -1, 3, 20, -110);
$list->sort();
$this->assertEquals([-110, -1, 3, 20, 120], $list->toArray());
}
/** @test */
public function testRemove()
{
$list = new Items(1, 2, 3, 4, 5);
$list->remove(3);
$this->assertEquals([1, 2, 4, 5], $list->toArray());
$list = new Items('red', 'green', 'blue');
$list->remove('green');
$this->assertEquals(['red', 'blue'], $list->toArray());
}
/** @test */
public function testReverse()
{
$list = new Items(1, 2, 3, 4, 5);
$list->reverse();
$this->assertEquals([5, 4, 3, 2, 1], $list->toArray());
}
/** @test */
public function testExtend()
{
$listA = new Items(1, 2, 3, 4, 5);
$listB = new Items('red', 'green');
$listA->extend($listB);
$this->assertEquals([1, 2, 3, 4, 5, 'red', 'green'], $listA->toArray());
}
}
| iwyg/common | tests/Struct/ItemsTest.php | PHP | mit | 2,769 |
<input type="hidden" id="permission" value="<?php echo $permission;?>">
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">Usuarios</h3>
<?php
if (strpos($permission,'Add') !== false) {
echo '<button class="btn btn-block btn-success" style="width: 100px; margin-top: 10px;" data-toggle="modal" onclick="LoadUsr(0,\'Add\')" id="btnAdd">Agregar</button>';
}
?>
</div><!-- /.box-header -->
<div class="box-body">
<table id="users" class="table table-bordered table-hover">
<thead>
<tr>
<th>Usuario</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Comisión</th>
<th width="20%">Acciones</th>
</tr>
</thead>
<tbody>
<?php
foreach($list as $u)
{
//var_dump($u);
echo '<tr>';
echo '<td style="text-align: left">'.$u['usrNick'].'</td>';
echo '<td style="text-align: left">'.$u['usrName'].'</td>';
echo '<td style="text-align: left">'.$u['usrLastName'].'</td>';
echo '<td style="text-align: right">'.$u['usrComision'].' %</td>';
echo '<td>';
if (strpos($permission,'Add') !== false) {
echo '<i class="fa fa-fw fa-pencil" style="color: #f39c12; cursor: pointer; margin-left: 15px;" onclick="LoadUsr('.$u['usrId'].',\'Edit\')"></i>';
}
if (strpos($permission,'Del') !== false) {
echo '<i class="fa fa-fw fa-times-circle" style="color: #dd4b39; cursor: pointer; margin-left: 15px;" onclick="LoadUsr('.$u['usrId'].',\'Del\')"></i>';
}
if (strpos($permission,'View') !== false) {
echo '<i class="fa fa-fw fa-search" style="color: #3c8dbc; cursor: pointer; margin-left: 15px;" onclick="LoadUsr('.$u['usrId'].',\'View\')"></i>';
}
echo '</td>';
echo '</tr>';
}
?>
</tbody>
</table>
</div><!-- /.box-body -->
</div><!-- /.box -->
</div><!-- /.col -->
</div><!-- /.row -->
</section><!-- /.content -->
<script>
$(function () {
//$("#groups").DataTable();
$('#users').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": true,
"language": {
"lengthMenu": "Ver _MENU_ filas por página",
"zeroRecords": "No hay registros",
"info": "Mostrando pagina _PAGE_ de _PAGES_",
"infoEmpty": "No hay registros disponibles",
"infoFiltered": "(filtrando de un total de _MAX_ registros)",
"sSearch": "Buscar: ",
"oPaginate": {
"sNext": "Sig.",
"sPrevious": "Ant."
}
}
});
});
var idUsr = 0;
var acUsr = '';
function LoadUsr(id_, action){
idUsr = id_;
acUsr = action;
LoadIconAction('modalAction',action);
WaitingOpen('Cargando Usuario');
$.ajax({
type: 'POST',
data: { id : id_, act: action },
url: 'index.php/user/getUser',
success: function(result){
WaitingClose();
$("#modalBodyUsr").html(result.html);
setTimeout("$('#modalUsr').modal('show')",800);
},
error: function(result){
WaitingClose();
alert("error");
},
dataType: 'json'
});
}
$('#btnSave').click(function(){
if(acUsr == 'View')
{
$('#modalUsr').modal('hide');
return;
}
var hayError = false;
if($('#usrNick').val() == '')
{
hayError = true;
}
if($('#usrName').val() == '')
{
hayError = true;
}
if($('#usrLastName').val() == '')
{
hayError = true;
}
if($('#usrComision').val() == '')
{
hayError = true;
}
if($('#usrPassword').val() != $('#usrPasswordConf').val()){
hayError = true;
}
if(hayError == true){
$('#errorUsr').fadeIn('slow');
return;
}
$('#errorUsr').fadeOut('slow');
WaitingOpen('Guardando cambios');
$.ajax({
type: 'POST',
data: {
id : idUsr,
act: acUsr,
usr: $('#usrNick').val(),
name: $('#usrName').val(),
lnam: $('#usrLastName').val(),
com: $('#usrComision').val(),
pas: $('#usrPassword').val(),
grp: $('#grpId').val()
},
url: 'index.php/user/setUser',
success: function(result){
WaitingClose();
$('#modalUsr').modal('hide');
setTimeout("cargarView('user', 'index', '"+$('#permission').val()+"');",1000);
},
error: function(result){
WaitingClose();
alert("error");
},
dataType: 'json'
});
});
</script>
<!-- Modal -->
<div class="modal fade" id="modalUsr" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel"><span id="modalAction"> </span> Usuario</h4>
</div>
<div class="modal-body" id="modalBodyUsr">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
<button type="button" class="btn btn-primary" id="btnSave">Guardar</button>
</div>
</div>
</div>
</div> | sergiojaviermoyano/sideli | application/views/users/list.php | PHP | mit | 6,178 |
using System;
using System.Diagnostics.CodeAnalysis;
namespace Delimited.Data.Exceptions
{
[Serializable, ExcludeFromCodeCoverage]
public class DelimitedReaderException : Exception
{
//
// For guidelines regarding the creation of new exception types, see
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp
// and
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp
//
public DelimitedReaderException() { }
public DelimitedReaderException(string message) : base(message) { }
public DelimitedReaderException(string message, Exception inner) : base(message, inner) { }
protected DelimitedReaderException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
}
| putridparrot/Delimited.Data | Delimited.Data/Exceptions/DelimitedReaderException.cs | C# | mit | 904 |
import numpy as np
from numpy import cumsum, sum, searchsorted
from numpy.random import rand
import math
import utils
import core.sentence as sentence
import core.markovchain as mc
import logging
logger = logging.getLogger(__name__)
# Dialogue making class. Need to review where to return a string, where to return a list of tokens, etc.
# setters: list of speakers, pronouns, priors etc.
# random transitions
# Internal: build list of structures:
# e.g.{:speaker_name "Alice", :speaker_pronoun "she", :speaker_str "she", :speech_verb "said", :position "end"}
# Then end with fn that maps that out to a suitable string
# e.g. "<SPEECH>, she said."
# External bit then replaces <SPEECH> with a markov-chain-generated sentence (or several).
class dialogue_maker(object):
"""Class to handle creating dialogue based on a list of speakers and a sentence generator."""
def __init__(self, names, pronouns, mc):
self.speakers = [{"name": n, "pronoun": p} for n, p in list(zip(names, pronouns))]
self._transitions = self.make_transition_probs()
self._speech_acts = ["said", "whispered", "shouted", "cried"]
self._acts_transitions = [25, 2, 2, 2]
self.mc = mc
# self.seeds = seeds
self.target_len = np.random.randint(5, 50, size=len(names)) # rough words per sentence
def make_transition_probs(self):
"""Make transition matrix between speakers, with random symmetric biases added in"""
n = len(self.speakers) # TODO why this line ???
transitions = np.random.randint(5, size=(n, n)) + 1
transitions += transitions.transpose()
for i in range(0, math.floor(n / 2)):
s1 = np.random.randint(n)
s2 = np.random.randint(n)
transitions[s1][s2] += 10
transitions[s2][s1] += 8
return(transitions)
def after(self, speaker_id):
"""Pick next person to speak"""
row = self._transitions[speaker_id]
sucessor = searchsorted(cumsum(row), rand() * sum(row))
return sucessor
def speaker_sequence(self, speaker_id, n):
"""Random walk through transitions matrix to produce a sequence of speaker ids"""
seq = []
for i in range(n):
seq.append(speaker_id)
speaker_id = self.after(speaker_id)
return seq
def speech_sequence(self, n):
speech_acts_seq = []
next_speech_id = 0
for i in range(n):
next_speech_id = searchsorted(cumsum(self._acts_transitions), rand() * sum(self._acts_transitions))
speech_acts_seq.append(self._speech_acts[next_speech_id])
return speech_acts_seq
def seq_to_names(self, sequence):
return([self.speakers[id] for id in sequence])
def make_speech_bits(self, seeds):
n = len(seeds)
speaker_id = self.speaker_sequence(0, n)
speech_acts_seq = self.speech_sequence(n)
bits = []
ss = sentence.SentenceMaker(self.mc)
for i in range(n):
sent_toks = ss.generate_sentence_tokens([seeds[i]], self.target_len[speaker_id[i]])
sent_toks = ss.polish_sentence(sent_toks)
bits.append({'speaker_name': self.speakers[speaker_id[i]]["name"],
'speech_act': speech_acts_seq[speaker_id[i]],
'seq_id': speaker_id[i],
'speech': sent_toks,
'paragraph': True})
return(bits)
def simplify(self, seq_map):
"Take a sequence of speech parts and make more natural by removing name reptition etc."
for i in range(0, len(seq_map)):
seq_map[i]['speaker_str'] = seq_map[i]['speaker_name'] # default
# Same speaker contiues:
if i > 0 and seq_map[i]['seq_id'] == seq_map[i - 1]['seq_id']:
seq_map[i]['speaker_str'] = ""
seq_map[i]['speech_act'] = ""
seq_map[i]['paragraph'] = False
else:
if i > 1 and seq_map[i]['seq_id'] == seq_map[i - 2]['seq_id'] \
and seq_map[i]['seq_id'] != seq_map[i - 1]['seq_id']:
seq_map[i]['speaker_str'] = ""
seq_map[i]['speech_act'] = ""
seq_map[i]['paragraph'] = True
return seq_map
def report_seq(self, seq_map):
"""Convert sequence of speeches to a tokens."""
sents = []
for i in range(0, len(seq_map)):
if seq_map[i]['paragraph']:
# text += "\n "
quote_start = '"'
else:
quote_start = ""
if i > len(seq_map) - 2 or seq_map[i + 1]['paragraph']:
quote_end = '"'
else:
quote_end = " "
if len(seq_map[i]['speech_act']) > 0:
speech_act = seq_map[i]['speech_act'] + ","
else:
speech_act = seq_map[i]['speech_act']
tokens = [utils.START_TOKEN]
tokens.append(seq_map[i]['speaker_str'])
tokens.append(speech_act)
tokens.append(quote_start)
tokens.extend(seq_map[i]['speech'][1:-1])
tokens.append(quote_end)
tokens.append(utils.END_TOKEN)
sents.append(tokens)
return sents
def make_dialogue(self, seeds):
"""Returns a list of sentences, each being a list of tokens."""
acts = self.make_speech_bits(seeds)
seq_map = self.simplify(acts)
sents = self.report_seq(seq_map)
return(sents)
def dev():
import knowledge.names as names
mcW = mc.MarkovChain()
nm = names.NameMaker()
speakers = [nm.random_person() for i in range(1, 4)]
dm = dialogue_maker([n['name'] for n in speakers], [n['pronoun'] for n in speakers], mcW)
dlg = dm.make_dialogue(["dog", "run", "spot"])
print(dlg)
| dcorney/text-generation | core/dialogue.py | Python | mit | 5,911 |
/*
Credits: Most of the original code seems to have been
written by George Michael Brower. The changes I've made
include adding background particle animations, text
placement and modification, and integration with a
sparkfun heart rate monitor by using Pubnub and johnny-five.
INSTRUCTIONS
- npm install [email protected]
- npm install johnny-five
- node Board.js to hook up to johnnyfive
*/
function FizzyText(message) {
var that = this;
// These are the variables that we manipulate with gui-dat.
// Notice they're all defined with "this". That makes them public.
// Otherwise, gui-dat can't see them.
this.growthSpeed = 0.98; // how fast do particles change size?
// this.maxSize = getRandomIntInclusive(3, 4); // how big can they get?
this.maxSize = 1.3;
this.noiseStrength = 1.9; // how turbulent is the flow?
this.bgNoiseStrength = 10;
this.speed = 0; // how fast do particles move?
this.bgSpeed = 0.4;
this.displayOutline = false; // should we draw the message as a stroke?
this.framesRendered = 0;
// this.color0 = "#00aeff";
// this.color1 = "#0fa954";
// this.color2 = "#54396e";
// this.color3 = "#e61d5f";
// this.color0 = "#ffdcfc";
// this.color1 = "#c8feff";
// this.color2 = "#ffffff";
// this.color3 = "#c8feff";
this.color0 = "#f0cf5b";
this.color1 = "#2abbf2";
this.color2 = "#660aaf";
this.color3 = "#f57596";
this.bgParticleColor = "#ffffff";
this.fontSize = 100;
this.fontWeight = 800;
// __defineGetter__ and __defineSetter__ make JavaScript believe that
// we've defined a variable 'this.message'. This way, whenever we
// change the message variable, we can call some more functions.
this.__defineGetter__("message", function() {
return message;
});
this.__defineSetter__("message", function(m) {
message = m;
createBitmap(message);
});
// We can even add functions to the DAT.GUI! As long as they have 0 argumets,
// we can call them from the dat-gui panel.
this.explode = function() {
var mag = Math.random() * 30 + 30;
for (var i in particles) {
var angle = Math.random() * Math.PI * 2;
particles[i].vx = Math.cos(angle) * mag;
particles[i].vy = Math.sin(angle) * mag;
}
};
////////////////////////////////
var _this = this;
var width = window.innerWidth;
var height = window.innerHeight;
// var textAscent = Math.random() * height; // for trans
var textAscent = height / 2; // for cisco
// var textOffsetLeft = Math.random() * width;
var textOffsetLeft = 0;
var noiseScale = 300;
var frameTime = 30;
// Keep the message within the canvas height bounds
while ((textAscent > height - 100) || textAscent < 100) {
textAscent = Math.random() * height;
}
var colors = [_this.color0, _this.color1, _this.color2, _this.color3];
// This is the context we use to get a bitmap of text using the
// getImageData function.
var r = document.createElement('canvas');
var s = r.getContext('2d');
// This is the context we actually use to draw.
var c = document.createElement('canvas');
var g = c.getContext('2d');
r.setAttribute('width', width);
c.setAttribute('width', width);
r.setAttribute('height', height);
c.setAttribute('height', height);
// Add our demo to the HTML
document.getElementById('fizzytext').appendChild(c);
// Stores bitmap image
var pixels = [];
// Stores a list of particles
var particles = [];
var bgParticles = [];
// Set g.font to the same font as the bitmap canvas, incase we want to draw some outlines
var fontAttr = _this.fontWeight + " " + _this.fontSize + "px helvetica, arial, sans-serif";
s.font = g.font = fontAttr;
// Instantiate some particles
for (var i = 0; i < 2000; i++) {
particles.push(new Particle(Math.random() * width, Math.random() * height));
}
// 2nd perlin field
for (var i = 0; i < 1000; i++) { // 10k particles
bgParticles.push(new bgParticle(Math.random() * width, Math.random() * height));
}
// This function creates a bitmap of pixels based on your message
// It's called every time we change the message property.
var createBitmap = function(msg) {
s.fillStyle = "#fff";
s.fillRect(0, 0, width, height);
s.fillStyle = "#222";
// Keep the message within canvas width bounds
var msgWidth = s.measureText(msg).width;
// while (textOffsetLeft + msgWidth > widthw) {
// // textOffsetLeft = Math.random() * width;
// }
textOffsetLeft = (width - msgWidth) / 2;
s.fillText(msg, textOffsetLeft, textAscent);
// Pull reference
var imageData = s.getImageData(0, 0, width, height);
pixels = imageData.data;
};
// Called once per frame, updates the animation.
var render = function() {
that.framesRendered++;
// g.clearRect(0, 0, width, height);
// Set the shown canvas background as black
g.rect(0, 0, width, height);
g.fillStyle = "black"; // for trans
// g.fillStyle = "#eee"; // for cisco
g.fill();
if (_this.displayOutline) {
g.globalCompositeOperation = "source-over";
// g.strokeStyle = "#000"; // for trans
g.strokeStyle = "#fff";
g.font = _this.fontSize + "px helvetica, arial, sans-serif"; // took out font weight
g.lineWidth = .5;
g.strokeText(message, textOffsetLeft, textAscent);
}
g.globalCompositeOperation = "darker";
// Choose particle color
for (var i = 0; i < particles.length; i++) {
g.fillStyle = colors[i % colors.length];
particles[i].render();
}
// Choose bg particle color (white for testing)
for (var i = 0; i < bgParticles.length; i++) {
g.fillStyle = _this.bgParticleColor;
bgParticles[i].render();
}
};
// Func tells me where x, y is for each pixel of the text
// Returns x, y coordinates for a given index in the pixel array.
var getPosition = function(i) {
return {
x: (i - (width * 4) * Math.floor(i / (width * 4))) / 4,
y: Math.floor(i / (width * 4))
};
};
// Returns a color for a given pixel in the pixel array
var getColor = function(x, y) {
var base = (Math.floor(y) * width + Math.floor(x)) * 4;
var c = {
r: pixels[base + 0],
g: pixels[base + 1],
b: pixels[base + 2],
a: pixels[base + 3]
};
return "rgb(" + c.r + "," + c.g + "," + c.b + ")";
};
// This calls the setter we've defined above, so it also calls
// the createBitmap function
this.message = message;
// Set the canvas bg
// document.getElementById('fizzytext').style.backgroundColor = colors[Math.floor(Math.random() * 4)]
function resizeCanvas() {
r.width = window.innerWidth;
c.width = window.innerWidth;
r.height = window.innerHeight;
c.height = window.innerHeight;
}
var loop = function() {
// Reset color array
colors = [_this.color0, _this.color1, _this.color2, _this.color3]; // Change colors from dat.gui
s.font = g.font = _this.fontWeight + " " + _this.fontSize + "px helvetica, arial, sans-serif";
createBitmap(message);
// _this.fontSize += 1;
resizeCanvas();
render();
requestAnimationFrame(loop);
}
// This calls the render function every 30ms
loop();
/////////////////////////////////////////////
// This class is responsible for drawing and moving those little
// colored dots.
function Particle(x, y, c) {
// Position
this.x = x;
this.y = y;
// Size of particle
this.r = 0;
// This velocity is used by the explode function.
this.vx = 0;
this.vy = 0;
this.constrain = function(v, o1, o2) {
if (v < o1) v = o1;
else if (v > o2) v = o2;
return v;
};
// Called every frame
this.render = function () {
// What color is the pixel we're sitting on top of?
var c = getColor(this.x, this.y);
// Where should we move?
var angle = noise(this.x / noiseScale, this.y / noiseScale) * _this.noiseStrength;
// Are we within the boundaries of the image?
var onScreen = this.x > 0 && this.x < width && this.y > 0 && this.y < height;
var isBlack = c != "rgb(255,255,255)" && onScreen;
// If we're on top of a black pixel, grow.
// If not, shrink.
if (isBlack) {
this.r += _this.growthSpeed;
} else {
this.r -= _this.growthSpeed;
}
// This velocity is used by the explode function.
this.vx *= 0.5;
this.vy *= 0.5;
// Change our position based on the flow field and our explode velocity.
this.x += Math.cos(angle) * _this.speed + this.vx;
this.y += -Math.sin(angle) * _this.speed + this.vy;
// this.r = 3;
// debugger
// console.log(DAT.GUI.constrain(this.r, 0, _this.maxSize));
this.r = this.constrain(this.r, 0, _this.maxSize);
// If we're tiny, keep moving around until we find a black pixel.
if (this.r <= 0) {
this.x = Math.random() * width;
this.y = Math.random() * height;
return; // Don't draw!
}
// Draw the circle.
g.beginPath();
g.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
g.fill();
}
}
function bgParticle(x, y, c) {
// Position
this.x = x;
this.y = y;
// Size of particle
this.r = 0;
// This velocity is used by the explode function.
this.vx = 0;
this.vy = 0;
this.constrain = function(v, o1, o2) {
if (v < o1) v = o1;
else if (v > o2) v = o2;
return v;
};
// Called every frame
this.render = function () {
// What color is the pixel we're sitting on top of?
var c = getColor(this.x, this.y);
// Where should we move?
var angle = noise(this.x / noiseScale, this.y / noiseScale) * _this.bgNoiseStrength;
// Are we within the boundaries of the image?
var onScreen = this.x > 0 && this.x < width && this.y > 0 && this.y < height;
var isBlack = c != "rgb(255,255,255)" && onScreen;
// If we're on top of a black pixel, grow.
// If not, shrink.
if (isBlack) {
this.r -= _this.growthSpeed / 2;
// this.r -= Math.abs(Math.sin(_this.growthSpeed));
} else {
// this.r += _this.growthSpeed / 2;
this.r += Math.abs(Math.sin(_this.growthSpeed));
}
// if not on screen respawn somewhere random
if (!onScreen) {
this.x = Math.random() * width;
this.y = Math.random() * height;
}
// This velocity is used by the explode function.
this.vx *= 0.5;
this.vy *= 0.5;
// Change our position based on the flow field and our explode velocity.
this.x += Math.cos(angle) * _this.bgSpeed + this.vx;
this.y += -Math.sin(angle) * _this.bgSpeed + this.vy;
// this.r = 3;
// debugger
// console.log(DAT.GUI.constrain(this.r, 0, _this.maxSize));
this.r = this.constrain(this.r, 0, 2);
// If we're tiny, keep moving around until we find a black pixel.
if (this.r <= 0) {
this.x = Math.random() * width;
this.y = Math.random() * height;
return; // Don't draw!
}
// Draw the circle.
g.beginPath();
g.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
g.fill();
}
}
}
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
} | mattchiang-gsp/mattchiang-gsp.github.io | FizzyText.js | JavaScript | mit | 12,644 |
<!DOCTYPE html>
<!--[if lt IE 9]><html class="no-js lt-ie9" lang="en" dir="ltr"><![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js" lang="en" dir="ltr">
<!--<![endif]-->
<!-- Usage: /eic/site/ccc-rec.nsf/tpl-eng/template-1col.html?Open&id=3 (optional: ?Open&page=filename.html&id=x) -->
<!-- Created: ; Product Code: 536; Server: stratnotes2.ic.gc.ca -->
<head>
<!-- Title begins / Début du titre -->
<title>
Spartan Industrial Marine -
Complete profile - Canadian Company Capabilities - Industries and Business - Industry Canada
</title>
<!-- Title ends / Fin du titre -->
<!-- Meta-data begins / Début des métadonnées -->
<meta charset="utf-8" />
<meta name="dcterms.language" title="ISO639-2" content="eng" />
<meta name="dcterms.title" content="" />
<meta name="description" content="" />
<meta name="dcterms.description" content="" />
<meta name="dcterms.type" content="report, data set" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.issued" title="W3CDTF" content="" />
<meta name="dcterms.modified" title="W3CDTF" content="" />
<meta name="keywords" content="" />
<meta name="dcterms.creator" content="" />
<meta name="author" content="" />
<meta name="dcterms.created" title="W3CDTF" content="" />
<meta name="dcterms.publisher" content="" />
<meta name="dcterms.audience" title="icaudience" content="" />
<meta name="dcterms.spatial" title="ISO3166-1" content="" />
<meta name="dcterms.spatial" title="gcgeonames" content="" />
<meta name="dcterms.format" content="HTML" />
<meta name="dcterms.identifier" title="ICsiteProduct" content="536" />
<!-- EPI-11240 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- MCG-202 -->
<meta content="width=device-width,initial-scale=1" name="viewport">
<!-- EPI-11567 -->
<meta name = "format-detection" content = "telephone=no">
<!-- EPI-12603 -->
<meta name="robots" content="noarchive">
<!-- EPI-11190 - Webtrends -->
<script>
var startTime = new Date();
startTime = startTime.getTime();
</script>
<!--[if gte IE 9 | !IE ]><!-->
<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="icon" type="image/x-icon">
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/wet-boew.min.css">
<!--<![endif]-->
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/theme.min.css">
<!--[if lt IE 9]>
<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="shortcut icon" />
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/ie8-wet-boew.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew.min.js"></script>
<![endif]-->
<!--[if lte IE 9]>
<![endif]-->
<noscript><link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/noscript.min.css" /></noscript>
<!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER -->
<script>dataLayer1 = [];</script>
<!-- End Google Tag Manager -->
<!-- EPI-11235 -->
<link rel="stylesheet" href="/eic/home.nsf/css/add_WET_4-0_Canada_Apps.css">
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="/app/ccc/srch/css/print.css" media="print" rel="stylesheet" type="text/css" />
</head>
<body class="home" vocab="http://schema.org/" typeof="WebPage">
<!-- EPIC HEADER BEGIN -->
<!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER -->
<noscript><iframe title="Google Tag Manager" src="//www.googletagmanager.com/ns.html?id=GTM-TLGQ9K" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer1'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer1','GTM-TLGQ9K');</script>
<!-- End Google Tag Manager -->
<!-- EPI-12801 -->
<span typeof="Organization"><meta property="legalName" content="Department_of_Industry"></span>
<ul id="wb-tphp">
<li class="wb-slc">
<a class="wb-sl" href="#wb-cont">Skip to main content</a>
</li>
<li class="wb-slc visible-sm visible-md visible-lg">
<a class="wb-sl" href="#wb-info">Skip to "About this site"</a>
</li>
</ul>
<header role="banner">
<div id="wb-bnr" class="container">
<section id="wb-lng" class="visible-md visible-lg text-right">
<h2 class="wb-inv">Language selection</h2>
<div class="row">
<div class="col-md-12">
<ul class="list-inline mrgn-bttm-0">
<li><a href="nvgt.do?V_TOKEN=1492320339451&V_SEARCH.docsCount=3&V_DOCUMENT.docRank=43177&V_SEARCH.docsStart=43176&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=/prfl.do&lang=fra&redirectUrl=/app/scr/imbs/ccc/rgstrtn/rgstr.sec?_flId?_flxKy=e1s1&estblmntNo=234567041301&profileId=61&_evId=bck&lang=eng&V_SEARCH.showStricts=false&prtl=1&_flId?_flId?_flxKy=e1s1" title="Français" lang="fr">Français</a></li>
</ul>
</div>
</div>
</section>
<div class="row">
<div class="brand col-xs-8 col-sm-9 col-md-6">
<a href="http://www.canada.ca/en/index.html"><object type="image/svg+xml" tabindex="-1" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/sig-blk-en.svg"></object><span class="wb-inv"> Government of Canada</span></a>
</div>
<section class="wb-mb-links col-xs-4 col-sm-3 visible-sm visible-xs" id="wb-glb-mn">
<h2>Search and menus</h2>
<ul class="list-inline text-right chvrn">
<li><a href="#mb-pnl" title="Search and menus" aria-controls="mb-pnl" class="overlay-lnk" role="button"><span class="glyphicon glyphicon-search"><span class="glyphicon glyphicon-th-list"><span class="wb-inv">Search and menus</span></span></span></a></li>
</ul>
<div id="mb-pnl"></div>
</section>
<!-- Site Search Removed -->
</div>
</div>
<nav role="navigation" id="wb-sm" class="wb-menu visible-md visible-lg" data-trgt="mb-pnl" data-ajax-fetch="//cdn.canada.ca/gcweb-cdn-dev/sitemenu/sitemenu-en.html" typeof="SiteNavigationElement">
<h2 class="wb-inv">Topics menu</h2>
<div class="container nvbar">
<div class="row">
<ul class="list-inline menu">
<li><a href="https://www.canada.ca/en/services/jobs.html">Jobs</a></li>
<li><a href="http://www.cic.gc.ca/english/index.asp">Immigration</a></li>
<li><a href="https://travel.gc.ca/">Travel</a></li>
<li><a href="https://www.canada.ca/en/services/business.html">Business</a></li>
<li><a href="https://www.canada.ca/en/services/benefits.html">Benefits</a></li>
<li><a href="http://healthycanadians.gc.ca/index-eng.php">Health</a></li>
<li><a href="https://www.canada.ca/en/services/taxes.html">Taxes</a></li>
<li><a href="https://www.canada.ca/en/services.html">More services</a></li>
</ul>
</div>
</div>
</nav>
<!-- EPIC BODY BEGIN -->
<nav role="navigation" id="wb-bc" class="" property="breadcrumb">
<h2 class="wb-inv">You are here:</h2>
<div class="container">
<div class="row">
<ol class="breadcrumb">
<li><a href="/eic/site/icgc.nsf/eng/home" title="Home">Home</a></li>
<li><a href="/eic/site/icgc.nsf/eng/h_07063.html" title="Industries and Business">Industries and Business</a></li>
<li><a href="/eic/site/ccc-rec.nsf/tpl-eng/../eng/home" >Canadian Company Capabilities</a></li>
</ol>
</div>
</div>
</nav>
</header>
<main id="wb-cont" role="main" property="mainContentOfPage" class="container">
<!-- End Header -->
<!-- Begin Body -->
<!-- Begin Body Title -->
<!-- End Body Title -->
<!-- Begin Body Head -->
<!-- End Body Head -->
<!-- Begin Body Content -->
<br>
<!-- Complete Profile -->
<!-- Company Information above tabbed area-->
<input id="showMore" type="hidden" value='more'/>
<input id="showLess" type="hidden" value='less'/>
<h1 id="wb-cont">
Company profile - Canadian Company Capabilities
</h1>
<div class="profileInfo hidden-print">
<ul class="list-inline">
<li><a href="cccSrch.do?lang=eng&profileId=&prtl=1&key.hitsPerPage=25&searchPage=%252Fapp%252Fccc%252Fsrch%252FcccBscSrch.do%253Flang%253Deng%2526amp%253Bprtl%253D1%2526amp%253Btagid%253D&V_SEARCH.scopeCategory=CCC.Root&V_SEARCH.depth=1&V_SEARCH.showStricts=false&V_SEARCH.sortSpec=title+asc&rstBtn.x=" class="btn btn-link">New Search</a> |</li>
<li><form name="searchForm" method="post" action="/app/ccc/srch/bscSrch.do">
<input type="hidden" name="lang" value="eng" />
<input type="hidden" name="profileId" value="" />
<input type="hidden" name="prtl" value="1" />
<input type="hidden" name="searchPage" value="%2Fapp%2Fccc%2Fsrch%2FcccBscSrch.do%3Flang%3Deng%26amp%3Bprtl%3D1%26amp%3Btagid%3D" />
<input type="hidden" name="V_SEARCH.scopeCategory" value="CCC.Root" />
<input type="hidden" name="V_SEARCH.depth" value="1" />
<input type="hidden" name="V_SEARCH.showStricts" value="false" />
<input id="repeatSearchBtn" class="btn btn-link" type="submit" value="Return to search results" />
</form></li>
<li>| <a href="nvgt.do?V_SEARCH.docsStart=43175&V_DOCUMENT.docRank=43176&V_SEARCH.docsCount=3&lang=eng&prtl=1&sbPrtl=&profile=cmpltPrfl&V_TOKEN=1492320346292&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=%2fprfl.do&estblmntNo=234567003938&profileId=&key.newSearchLabel=">Previous Company</a></li>
<li>| <a href="nvgt.do?V_SEARCH.docsStart=43177&V_DOCUMENT.docRank=43178&V_SEARCH.docsCount=3&lang=eng&prtl=1&sbPrtl=&profile=cmpltPrfl&V_TOKEN=1492320346292&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=%2fprfl.do&estblmntNo=330290340000&profileId=&key.newSearchLabel=">Next Company</a></li>
</ul>
</div>
<details>
<summary>Third-Party Information Liability Disclaimer</summary>
<p>Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.</p>
</details>
<h2>
Spartan Industrial Marine
</h2>
<div class="row">
<div class="col-md-5">
<h2 class="h5 mrgn-bttm-0">Legal/Operating Name:</h2>
<p>Spartan Industrial Marine</p>
<div class="mrgn-tp-md"></div>
<p class="mrgn-bttm-0" ><a href="http://www.spartanmarine.ca"
target="_blank" title="Website URL">http://www.spartanmarine.ca</a></p>
<p><a href="mailto:[email protected]" title="[email protected]">[email protected]</a></p>
</div>
<div class="col-md-4 mrgn-sm-sm">
<h2 class="h5 mrgn-bttm-0">Mailing Address:</h2>
<address class="mrgn-bttm-md">
120 Thornhill Dr.<br/>
DARTMOUTH,
Nova Scotia<br/>
B3B 1S3
<br/>
</address>
<h2 class="h5 mrgn-bttm-0">Location Address:</h2>
<address class="mrgn-bttm-md">
120 Thornhill Dr.<br/>
DARTMOUTH,
Nova Scotia<br/>
B3B 1S3
<br/>
</address>
<p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>:
(902) 468-2111
</p>
<p class="mrgn-bttm-lg"><abbr title="Facsimile">Fax</abbr>:
(902) 468-3077</p>
</div>
<div class="col-md-3 mrgn-tp-md">
</div>
</div>
<div class="row mrgn-tp-md mrgn-bttm-md">
<div class="col-md-12">
<h2 class="wb-inv">Company Profile</h2>
<br> Full range supplier of marine and industrial products .Products and services include ,marine safety equipment sales and service , rigging hardware and equipment ,inspection of rigging equipment ,Commerial fishing supplies ,Commerial fishing net repair and manufacture .<br>
</div>
</div>
<!-- <div class="wb-tabs ignore-session update-hash wb-eqht-off print-active"> -->
<div class="wb-tabs ignore-session">
<div class="tabpanels">
<details id="details-panel1">
<summary>
Full profile
</summary>
<!-- Tab 1 -->
<h2 class="wb-invisible">
Full profile
</h2>
<!-- Contact Information -->
<h3 class="page-header">
Contact information
</h3>
<section class="container-fluid">
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Paul
Johnston
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
<!--if client gender is not null or empty we use gender based job title-->
General Manager
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Area of Responsibility:
</strong>
</div>
<div class="col-md-7">
Management Executive.
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(902) 468-2111
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Ext:
</strong>
</div>
<div class="col-md-7">
240
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(902) 468-3077
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
[email protected]
</div>
</div>
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Lisa
Caron
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
<!--if client gender is not null or empty we use gender based job title-->
Manager
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Area of Responsibility:
</strong>
</div>
<div class="col-md-7">
Management Executive.
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(902) 468-2111
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Ext:
</strong>
</div>
<div class="col-md-7">
225
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(902) 468-3077
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
[email protected]
</div>
</div>
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Ron
Scott
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
<!--if client gender is not null or empty we use gender based job title-->
Manager
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(902) 468-2111
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(902) 468-3077
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
[email protected]
</div>
</div>
</section>
<p class="mrgn-tp-lg text-right small hidden-print">
<a href="#wb-cont">top of page</a>
</p>
<!-- Company Description -->
<h3 class="page-header">
Company description
</h3>
<section class="container-fluid">
<div class="row">
<div class="col-md-5">
<strong>
Country of Ownership:
</strong>
</div>
<div class="col-md-7">
Canada
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Year Established:
</strong>
</div>
<div class="col-md-7">
1983
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Exporting:
</strong>
</div>
<div class="col-md-7">
No
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Industry (NAICS):
</strong>
</div>
<div class="col-md-7">
417230 - Industrial Machinery, Equipment and Supplies Wholesaler-Distributors
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Business Activity:
</strong>
</div>
<div class="col-md-7">
Trading House / Wholesaler / Agent and Distributor
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Number of Employees:
</strong>
</div>
<div class="col-md-7">
10
</div>
</div>
</section>
<!-- Products / Services / Licensing -->
<h3 class="page-header">
Product / Service / Licensing
</h3>
<section class="container-fluid">
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
full menu supplier of marine/industrial and commerial fishing products <br>
</div>
</div>
</section>
<p class="mrgn-tp-lg text-right small hidden-print">
<a href="#wb-cont">top of page</a>
</p>
<!-- Technology Profile -->
<!-- Market Profile -->
<!-- Sector Information -->
<details class="mrgn-tp-md mrgn-bttm-md">
<summary>
Third-Party Information Liability Disclaimer
</summary>
<p>
Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.
</p>
</details>
</details>
<details id="details-panel2">
<summary>
Contacts
</summary>
<h2 class="wb-invisible">
Contact information
</h2>
<!-- Contact Information -->
<section class="container-fluid">
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Paul
Johnston
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
<!--if client gender is not null or empty we use gender based job title-->
General Manager
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Area of Responsibility:
</strong>
</div>
<div class="col-md-7">
Management Executive.
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(902) 468-2111
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Ext:
</strong>
</div>
<div class="col-md-7">
240
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(902) 468-3077
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
[email protected]
</div>
</div>
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Lisa
Caron
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
<!--if client gender is not null or empty we use gender based job title-->
Manager
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Area of Responsibility:
</strong>
</div>
<div class="col-md-7">
Management Executive.
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(902) 468-2111
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Ext:
</strong>
</div>
<div class="col-md-7">
225
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(902) 468-3077
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
[email protected]
</div>
</div>
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Ron
Scott
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
<!--if client gender is not null or empty we use gender based job title-->
Manager
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(902) 468-2111
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(902) 468-3077
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
[email protected]
</div>
</div>
</section>
</details>
<details id="details-panel3">
<summary>
Description
</summary>
<h2 class="wb-invisible">
Company description
</h2>
<section class="container-fluid">
<div class="row">
<div class="col-md-5">
<strong>
Country of Ownership:
</strong>
</div>
<div class="col-md-7">
Canada
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Year Established:
</strong>
</div>
<div class="col-md-7">
1983
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Exporting:
</strong>
</div>
<div class="col-md-7">
No
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Industry (NAICS):
</strong>
</div>
<div class="col-md-7">
417230 - Industrial Machinery, Equipment and Supplies Wholesaler-Distributors
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Business Activity:
</strong>
</div>
<div class="col-md-7">
Trading House / Wholesaler / Agent and Distributor
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Number of Employees:
</strong>
</div>
<div class="col-md-7">
10
</div>
</div>
</section>
</details>
<details id="details-panel4">
<summary>
Products, services and licensing
</summary>
<h2 class="wb-invisible">
Product / Service / Licensing
</h2>
<section class="container-fluid">
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
full menu supplier of marine/industrial and commerial fishing products <br>
</div>
</div>
</section>
</details>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
Last Update Date 2016-02-01
</div>
</div>
<!--
- Artifact ID: CBW - IMBS - CCC Search WAR
- Group ID: ca.gc.ic.strategis.imbs.ccc.search
- Version: 3.26
- Built-By: bamboo
- Build Timestamp: 2017-03-02T21:29:28Z
-->
<!-- End Body Content -->
<!-- Begin Body Foot -->
<!-- End Body Foot -->
<!-- END MAIN TABLE -->
<!-- End body -->
<!-- Begin footer -->
<div class="row pagedetails">
<div class="col-sm-5 col-xs-12 datemod">
<dl id="wb-dtmd">
<dt class=" hidden-print">Date Modified:</dt>
<dd class=" hidden-print">
<span><time>2017-03-02</time></span>
</dd>
</dl>
</div>
<div class="clear visible-xs"></div>
<div class="col-sm-4 col-xs-6">
</div>
<div class="col-sm-3 col-xs-6 text-right">
</div>
<div class="clear visible-xs"></div>
</div>
</main>
<footer role="contentinfo" id="wb-info">
<nav role="navigation" class="container wb-navcurr">
<h2 class="wb-inv">About government</h2>
<!-- EPIC FOOTER BEGIN -->
<!-- EPI-11638 Contact us -->
<ul class="list-unstyled colcount-sm-2 colcount-md-3">
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07026.html#pageid=E048-H00000&from=Industries">Contact us</a></li>
<li><a href="https://www.canada.ca/en/government/dept.html">Departments and agencies</a></li>
<li><a href="https://www.canada.ca/en/government/publicservice.html">Public service and military</a></li>
<li><a href="https://www.canada.ca/en/news.html">News</a></li>
<li><a href="https://www.canada.ca/en/government/system/laws.html">Treaties, laws and regulations</a></li>
<li><a href="https://www.canada.ca/en/transparency/reporting.html">Government-wide reporting</a></li>
<li><a href="http://pm.gc.ca/eng">Prime Minister</a></li>
<li><a href="https://www.canada.ca/en/government/system.html">How government works</a></li>
<li><a href="http://open.canada.ca/en/">Open government</a></li>
</ul>
</nav>
<div class="brand">
<div class="container">
<div class="row">
<nav class="col-md-10 ftr-urlt-lnk">
<h2 class="wb-inv">About this site</h2>
<ul>
<li><a href="https://www.canada.ca/en/social.html">Social media</a></li>
<li><a href="https://www.canada.ca/en/mobile.html">Mobile applications</a></li>
<li><a href="http://www1.canada.ca/en/newsite.html">About Canada.ca</a></li>
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html">Terms and conditions</a></li>
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html#p1">Privacy</a></li>
</ul>
</nav>
<div class="col-xs-6 visible-sm visible-xs tofpg">
<a href="#wb-cont">Top of Page <span class="glyphicon glyphicon-chevron-up"></span></a>
</div>
<div class="col-xs-6 col-md-2 text-right">
<object type="image/svg+xml" tabindex="-1" role="img" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/wmms-blk.svg" aria-label="Symbol of the Government of Canada"></object>
</div>
</div>
</div>
</div>
</footer>
<!--[if gte IE 9 | !IE ]><!-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/wet-boew.min.js"></script>
<!--<![endif]-->
<!--[if lt IE 9]>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew2.min.js"></script>
<![endif]-->
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/theme.min.js"></script>
<!-- EPI-10519 -->
<span class="wb-sessto"
data-wb-sessto='{"inactivity": 1800000, "reactionTime": 180000, "sessionalive": 1800000, "logouturl": "/app/ccc/srch/cccSrch.do?lang=eng&prtl=1"}'></span>
<script src="/eic/home.nsf/js/jQuery.externalOpensInNewWindow.js"></script>
<!-- EPI-11190 - Webtrends -->
<script src="/eic/home.nsf/js/webtrends.js"></script>
<script>var endTime = new Date();</script>
<noscript>
<div><img alt="" id="DCSIMG" width="1" height="1" src="//wt-sdc.ic.gc.ca/dcs6v67hwe0ei7wsv8g9fv50d_3k6i/njs.gif?dcsuri=/nojavascript&WT.js=No&WT.tv=9.4.0&dcssip=www.ic.gc.ca"/></div>
</noscript>
<!-- /Webtrends -->
<!-- JS deps -->
<script src="/eic/home.nsf/js/jquery.imagesloaded.js"></script>
<!-- EPI-11262 - Util JS -->
<script src="/eic/home.nsf/js/_WET_4-0_utils_canada.min.js"></script>
<!-- EPI-11383 -->
<script src="/eic/home.nsf/js/jQuery.icValidationErrors.js"></script>
<span style="display:none;" id='app-info' data-project-groupid='' data-project-artifactid='' data-project-version='' data-project-build-timestamp='' data-issue-tracking='' data-scm-sha1='' data-scm-sha1-abbrev='' data-scm-branch='' data-scm-commit-date=''></span>
</body></html>
<!-- End Footer -->
<!--
- Artifact ID: CBW - IMBS - CCC Search WAR
- Group ID: ca.gc.ic.strategis.imbs.ccc.search
- Version: 3.26
- Built-By: bamboo
- Build Timestamp: 2017-03-02T21:29:28Z
-->
| GoC-Spending/data-corporations | html/234567002226.html | HTML | mit | 46,311 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2020_08_01
module Models
#
# Response for ApplicationGatewayBackendHealth API service call.
#
class ApplicationGatewayBackendHealth
include MsRestAzure
# @return [Array<ApplicationGatewayBackendHealthPool>] A list of
# ApplicationGatewayBackendHealthPool resources.
attr_accessor :backend_address_pools
#
# Mapper for ApplicationGatewayBackendHealth class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ApplicationGatewayBackendHealth',
type: {
name: 'Composite',
class_name: 'ApplicationGatewayBackendHealth',
model_properties: {
backend_address_pools: {
client_side_validation: true,
required: false,
serialized_name: 'backendAddressPools',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ApplicationGatewayBackendHealthPoolElementType',
type: {
name: 'Composite',
class_name: 'ApplicationGatewayBackendHealthPool'
}
}
}
}
}
}
}
end
end
end
end
| Azure/azure-sdk-for-ruby | management/azure_mgmt_network/lib/2020-08-01/generated/azure_mgmt_network/models/application_gateway_backend_health.rb | Ruby | mit | 1,726 |
define("resolver",
[],
function() {
"use strict";
/*
* This module defines a subclass of Ember.DefaultResolver that adds two
* important features:
*
* 1) The resolver makes the container aware of es6 modules via the AMD
* output. The loader's _seen is consulted so that classes can be
* resolved directly via the module loader, without needing a manual
* `import`.
* 2) is able provide injections to classes that implement `extend`
* (as is typical with Ember).
*/
function classFactory(klass) {
return {
create: function (injections) {
if (typeof klass.extend === 'function') {
return klass.extend(injections);
} else {
return klass;
}
}
};
}
var underscore = Ember.String.underscore;
var classify = Ember.String.classify;
var get = Ember.get;
function parseName(fullName) {
var nameParts = fullName.split(":"),
type = nameParts[0], fullNameWithoutType = nameParts[1],
name = fullNameWithoutType,
namespace = get(this, 'namespace'),
root = namespace;
return {
fullName: fullName,
type: type,
fullNameWithoutType: fullNameWithoutType,
name: name,
root: root,
resolveMethodName: "resolve" + classify(type)
};
}
function chooseModuleName(seen, moduleName) {
var underscoredModuleName = Ember.String.underscore(moduleName);
if (moduleName !== underscoredModuleName && seen[moduleName] && seen[underscoredModuleName]) {
throw new TypeError("Ambigous module names: `" + moduleName + "` and `" + underscoredModuleName + "`");
}
if (seen[moduleName]) {
return moduleName;
} else if (seen[underscoredModuleName]) {
return underscoredModuleName;
} else {
return moduleName;
}
}
function resolveOther(parsedName) {
var prefix = this.namespace.modulePrefix;
Ember.assert('module prefix must be defined', prefix);
var pluralizedType = parsedName.type + 's';
var name = parsedName.fullNameWithoutType;
var moduleName = prefix + '/' + pluralizedType + '/' + name;
// allow treat all dashed and all underscored as the same thing
// supports components with dashes and other stuff with underscores.
var normalizedModuleName = chooseModuleName(requirejs._eak_seen, moduleName);
if (requirejs._eak_seen[normalizedModuleName]) {
var module = require(normalizedModuleName, null, null, true /* force sync */);
if (module === undefined) {
throw new Error("Module: '" + name + "' was found but returned undefined. Did you forget to `export default`?");
}
if (Ember.ENV.LOG_MODULE_RESOLVER) {
Ember.Logger.info('hit', moduleName);
}
return module;
} else {
if (Ember.ENV.LOG_MODULE_RESOLVER) {
Ember.Logger.info('miss', moduleName);
}
return this._super(parsedName);
}
}
function resolveTemplate(parsedName) {
return Ember.TEMPLATES[parsedName.name] || Ember.TEMPLATES[Ember.String.underscore(parsedName.name)];
}
// Ember.DefaultResolver docs:
// https://github.com/emberjs/ember.js/blob/master/packages/ember-application/lib/system/resolver.js
var Resolver = Ember.DefaultResolver.extend({
resolveTemplate: resolveTemplate,
resolveOther: resolveOther,
parseName: parseName,
normalize: function(fullName) {
// replace `.` with `/` in order to make nested controllers work in the following cases
// 1. `needs: ['posts/post']`
// 2. `{{render "posts/post"}}`
// 3. `this.render('posts/post')` from Route
return Ember.String.dasherize(fullName.replace(/\./g, '/'));
}
});
return Resolver;
});
| bmac/aircheck | vendor/resolver.js | JavaScript | mit | 3,757 |
package billing;
import cuke4duke.Then;
import cuke4duke.Given;
import static org.junit.Assert.assertTrue;
public class CalledSteps {
private boolean magic;
@Given("^it is (.*)$")
public void itIs(String what) {
if(what.equals("magic")) {
magic = true;
}
}
@Then("^magic should happen$")
public void magicShouldHappen() {
assertTrue(magic);
}
}
| torbjornvatn/cuke4duke | examples/guice/src/test/java/billing/CalledSteps.java | Java | mit | 413 |
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <assert.h>
#include <sys/epoll.h>
#include "reactor.h"
struct state
{
reactor_handler input;
reactor_handler output;
char buffer[4096];
data remaining;
};
int fill(struct state *state)
{
ssize_t n;
n = read(0, state->buffer, sizeof state->buffer);
if (n == 0)
{
reactor_delete(&state->input, 0);
reactor_delete(&state->output, 1);
return -1;
}
if (n == -1 && errno == EAGAIN)
return -1;
assert(n > 0);
state->remaining = data_construct(state->buffer, n);
reactor_modify(&state->input, 0, 0);
reactor_modify(&state->output, 1, EPOLLOUT | EPOLLET);
return 0;
}
int flush(struct state *state)
{
ssize_t n;
n = write(1, data_base(state->remaining), data_size(state->remaining));
if (n == -1 && errno == EAGAIN)
return -1;
assert(n > 0);
state->remaining = data_select(state->remaining, n, data_size(state->remaining) - n);
if (!data_size(state->remaining))
{
reactor_modify(&state->input, 0, EPOLLIN | EPOLLET);
reactor_modify(&state->output, 1, 0);
}
return 0;
}
void input(reactor_event *event)
{
struct state *state = event->state;
int e;
while (!data_size(state->remaining))
{
e = fill(state);
if (e == -1)
break;
e = flush(state);
if (e == -1)
break;
}
}
void output(reactor_event *event)
{
struct state *state = event->state;
int e;
while (data_size(state->remaining))
{
e = flush(state);
if (e == -1)
break;
}
}
int main()
{
struct state state = {0};
fcntl(0, F_SETFL, O_NONBLOCK);
fcntl(1, F_SETFL, O_NONBLOCK);
reactor_construct();
reactor_handler_construct(&state.input, input, &state);
reactor_handler_construct(&state.output, output, &state);
reactor_add(&state.input, 0, EPOLLIN);
reactor_add(&state.output, 1, EPOLLOUT);
reactor_loop();
reactor_destruct();
}
| fredrikwidlund/libreactor | example/fd.c | C | mit | 1,952 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::CognitiveServices::ContentModerator::V1_0
module Models
#
# Detected SSN details.
#
class SSN
include MsRestAzure
# @return [String] Detected SSN in the input text content.
attr_accessor :text
# @return [Integer] Index(Location) of the SSN in the input text content.
attr_accessor :index
#
# Mapper for SSN class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'SSN',
type: {
name: 'Composite',
class_name: 'SSN',
model_properties: {
text: {
client_side_validation: true,
required: false,
serialized_name: 'Text',
type: {
name: 'String'
}
},
index: {
client_side_validation: true,
required: false,
serialized_name: 'Index',
type: {
name: 'Number'
}
}
}
}
}
end
end
end
end
| Azure/azure-sdk-for-ruby | data/azure_cognitiveservices_contentmoderator/lib/1.0/generated/azure_cognitiveservices_contentmoderator/models/ssn.rb | Ruby | mit | 1,419 |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Posts · dpc's blog</title>
<meta name="description" content="Random posts about stuff.">
<meta name="generator" content="Hugo 0.16" />
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Posts · dpc's blog">
<meta name="twitter:description" content="Random posts about stuff.">
<meta property="og:title" content="Posts · dpc's blog">
<meta property="og:type" content="blog">
<meta property="og:description" content="Random posts about stuff.">
<link href='//fonts.googleapis.com/css?family=Source+Sans+Pro:400,700|Oxygen:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/pure/0.6.0/pure-min.css">
<!--[if lte IE 8]>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/pure/0.6.0/grids-responsive-old-ie-min.css">
<![endif]-->
<!--[if gt IE 8]><!-->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/pure/0.6.0/grids-responsive-min.css">
<!--<![endif]-->
<link rel="stylesheet" href="http://dpc.pw//css/all.min.css">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
<link rel="alternate" type="application/rss+xml" title="dpc's blog" href="http://dpc.pw//index.xml" />
</head>
<body>
<div id="layout" class="pure-g">
<div class="sidebar pure-u-1 pure-u-md-1-4">
<div class="header">
<hgroup>
<h1 class="brand-title"><a href="http://dpc.pw/">dpc's blog</a></h1>
<h2 class="brand-tagline">Random posts about stuff.</h2>
</hgroup>
<nav class="nav">
<ul class="nav-list">
<li class="nav-item">
<a class="pure-button" href="http://dpc.pw//index.xml"><i class="fa fa-rss"></i> rss</a>
</li>
</ul>
</nav>
</div>
</div>
<div class="content pure-u-1 pure-u-md-3-4">
<div>
<div class="posts">
<h1 class="content-subhead">
2016-10-10
<p class="post-meta">
<a class="post-tags post-tags-programming" href="http://dpc.pw//tags/programming">programming</a>
</p>
</h1>
<section class="post">
<header class="post-header">
<a href="http://dpc.pw/on-state-pollution/" class="post-title">On state pollution</a>
</header>
<div class="post-description">
<h2 id="introduction">Introduction</h2>
<p>I’d like to share an method I’ve developed on how to judge a code. This method
uses a metric that I named <em>state pollution</em>.</p>
<p>Note: I am not well versed in academic Computer Science nomenclature and just
trying to be precise in my explanation. Be aware that I might be wrong
somewhere and please feel free to correct me if I’m naming something wrong or
misusing concepts. Maybe someone already described something like that (or
better). Please refer me right places if it the case.</p>
<p>First, I use <em>state</em> as a synonym of <em>entropy</em> or <em>amount of information</em>.</p>
<p><em>State pollution</em> of a fragment of a code is an amount of <em>aggregate visible state</em>
that fragment adds to the whole code.</p>
<p><em>Aggregate visible state</em> is sum of <em>visible state</em> of every executable line of
the code.</p>
<p><em>Visible state</em> of a piece/line of code is the amount of <em>state</em> this code can
access (<em>readable visible state</em>) or modify (<em>writeable visible state</em>).</p>
<p>The state is measured in bits. Eg. boolean variable can be only in two states:
<code>true</code> or <code>false</code>. This is 1 bit of information. A C-language <code>char</code> has 256
possible values, which is 8 bits.</p>
<p>The following Rust Hello World example has 0-bits of <em>aggregate visible state</em>.</p>
<pre><code class="language-rust">fn main() {
println!("Hello world!");
}
</code></pre>
<p>The above code has only one effective line of code: <code>println!(...)</code> and that line has no variables to access or modify.</p>
<p>Now let’s say we’re going to add a pointless mutable <code>8-bit</code> variable:</p>
<pre><code class="language-rust">fn main() {
let mut x = 0u8;
println!("Hello world!");
}
</code></pre>
<p>This new line makes it potentially possible for <code>println!(...)</code> to print a text
dependent on it’s value. So the <em>aggregate visible state</em> of the code is now <code>8-bits</code>, and
the <em>state pollution</em> introduced by new line is <code>8-bits</code>.</p>
<p>Not that if <code>mut</code> keyword was removed, <code>println!(...)</code> could potentially print
<code>x</code>, but not modify it (as variables are immutable by default in Rust). That
would cause <em>aggregate writeable visible state</em> to stay equal to 0, increasing
only <em>readable visible state</em>.</p>
<p>Note: this whole <em>entropy</em> calculation is not meant to be precise. It is to be thought of
as <a href="https://en.wikipedia.org/wiki/Big_O_notation">Big O Notation</a>. It’s the magnitude that is important, not the exact values! To mimic <code>O(...)</code>
I’m going to use similar <code>P(...)</code> where <em>P</em> stands for <em>pollution</em>.</p>
<p>I hope the concept is clear now. Now let’s get to while it’s useful. I find
<em>state pollution</em> metric to be generalization of many other more-specific ways
to judge the code, and corresponding to “good practices” and judgments about the
code that people develop with experience.</p>
<h2 id="why-is-using-enumerator-better-than-an-integer">Why is using enumerator better than an integer</h2>
<p>Let’s compare:</p>
<pre><code class="language-rust">enum State {
Open,
Connected,
Errored
}
state : State;
</code></pre>
<p>vs</p>
<pre><code class="language-rust">state : uint;
</code></pre>
<p><code>state</code> that is an enumerator have only 3 possible values (entropy = 1.5 bits). <code>state</code> that is just an integer,
has a lot more possible values, thus introducing more <em>state pollution</em>.</p>
<h2 id="why-are-local-values-preferable-over-globals">Why are local values preferable over globals</h2>
<p>Most programmers would agree that avoiding global values in any code is a good
practice. Using <em>state pollution</em> metric one could say that, a global variable
has a <code>P(n*e)</code> where <code>n</code> is number of lines of the whole code and <code>e</code> is a entropy of the
variable itself (1-bit for boolean, 8-bit for C-language char, etc.). In contrast
local variable has a <code>P(m*e)</code> where <code>m</code> is total number of lines of one
function. As <code>n >= m</code> using local variables instead of global is minimizing
<em>aggregate visible state pollution</em></p>
<p>Natural language explanation simple: every global variable in your code makes
every line of your code potentially do something different depending on the value
of that variable.</p>
<h2 id="why-is-static-typing-preferable-over-dynamic-typing">Why is static typing preferable over dynamic typing?</h2>
<p>In statically-typed languages <code>bool</code> can have only two values. That’s enforced.
In dynamically-typed, every variable can potentially have any value of any
type. Variables in dynamically-typed languages introduce more <em>state
pollution</em>. Obviously code written in dynamically-typed language variables
doesn’t always abuse that, but as a possibility - it’s always there, in every
variable. Maybe by mistake, maybe on purpose, and change to the code could
introduce a new state. So <em>state pollution</em> is there, maybe just discounted a
little.</p>
<h2 id="why-are-immutable-variables-better-than-mutable">Why are immutable variables better than mutable</h2>
<p>The mutable state increases both <em>writeable</em> and <em>readable visible pollution</em>,
immutable only the later. With immutable state any code can potentially
experience different behavior depending on the state, but at least can’t change
the behavior of other places that are polluted with the same state.</p>
<h2 id="why-is-encapsulation-and-abstraction-good">Why is encapsulation and abstraction good</h2>
<p>Limiting visibility of the state using eg. Go <code>interfaces</code> or Rust <code>traits</code>, or
just field and method visibility settings does not completely remove the state,
but wraps it in a surface that limits it’s effective pollution: the code exposed to
encapsulated or abstracted state can’t directly interfere with it.</p>
<h2 id="why-is-functional-code-preferable-over-imperative">Why is functional code preferable over imperative</h2>
<p>By nature functional code limits the state pollution. Eg. pure virtual function
can only use it’s arguments, so that arguments are the only state that pollutes
the function code.</p>
</div>
</section>
<h1 class="content-subhead">
2016-09-27
<p class="post-meta">
<a class="post-tags post-tags-go" href="http://dpc.pw//tags/go">go</a><a class="post-tags post-tags-opinion" href="http://dpc.pw//tags/opinion">opinion</a><a class="post-tags post-tags-rant" href="http://dpc.pw//tags/rant">rant</a>
</p>
</h1>
<section class="post">
<header class="post-header">
<a href="http://dpc.pw/my-opinion-on-go/" class="post-title">My opinion on Go</a>
</header>
<div class="post-description">
<h2 id="tl-dr">TL;DR</h2>
<p>The biggest strength of Go, IMO, was the FAD created by the fact that it is
“backed by Google”. That gave Go immediate traction, and bootstrapped a
decently sized ecosystem. Everybody know about it, and have somewhat positive
attitude thinking “it’s simple, fast, and easy to learn”.</p>
<p>I enjoy (crude but still) static typing, compiling to native
code, and most of all: native-green thread, making Go quite productive for
server side code. I just had to get used to many workarounds for lack of
generics, remember about avoid all the <a href="https://gist.github.com/lavalamp/4bd23295a9f32706a48f">Go landmines</a> and ignore
poor expressiveness.</p>
<p>My favourite thing about Go, is that it produces static, native binaries.
Unlike software written in Python, getting software written in Go to actually
run is always painless.</p>
<p>However overall, Go is poorly designed language full of painful archaisms. It
ignores multiple great ideas from programming languages research and other PL
experiences.</p>
<p><a href="https://news.ycombinator.com/item?id=12525949">“Go’s simplicity is syntactic. The complexity is in semantics and runtime
behavior.”</a></p>
<p>Every time I write code in Go, I get the job done, but I feel deeply disappointed.</p>
<h2 id="reading-material">Reading material</h2>
<p>I think the best description of Go’s problems was <a href="http://yager.io/programming/go.html">Why Go Is Not Good</a>.</p>
<p>Also interesting:</p>
<ul>
<li><a href="http://nomad.so/2015/03/why-gos-design-is-a-disservice-to-intelligent-programmers/">Why Go’s design is a disservice to intelligent
programmers</a>
<ul>
<li>“In my opinion Go has been designed by people who have been using C all
their lives and don’t want to try anything new. The language could be
described as C with training wheels.”</li>
</ul></li>
<li><a href="http://dtrace.org/blogs/ahl/2016/08/02/i-love-go-i-hate-go/">I Love Go; I Hate Go</a></li>
<li><a href="https://github.com/ksimka/go-is-not-good">Many, many articles explaining why Go is just bad</a></li>
</ul>
<h2 id="more-on-my-experiences-with-go">More on my experiences with Go</h2>
<p>While I was following Go programming language since it’s announcement and even
did some learning and toying with it, only recently I had opportunity to try Go
in real projects. For the last couple of months I’ve been working a lot with
Go, and below is why I think Go is simply a bad programming language.</p>
<h3 id="nil">Nil</h3>
<p><code>nil</code>/<code>null</code> should not exists in any recent programming language.</p>
<p><code>nil</code> keeps being the biggest source of frustration when working with code
written in Go. <code>nil</code> handling is inconsistent too with sometimes <code>nil</code> being OK
to use, and sometimes not so much.</p>
<h3 id="no-sane-error-handling">No sane error handling</h3>
<pre><code class="language-go">o1, err := DoSomething1()
if err != nil {
return
}
defer Cleanup(o1)
o2, err := o2.DoSomething2()
if err != nil {
return
}
defer Cleanup2(o2)
…
oN, err := oN-1.DoSomethingN()
if err != nil {
return
}
defer CleanupN(oN)
</code></pre>
<p>compare the above with corresponding Rust code:</p>
<pre><code class="language-rust">let o1 = try!(DoSomething1());
let o2 = try!(o1.DoSomething2());
…
let oN = try!(oN-1.DoSomethingN());
</code></pre>
<p>or</p>
<pre><code class="language-rust">DoSomething1()
.and_then(|o1| o1.DoSomething2())
.and_then(|o2| o2.DoSomething2())
…
.and_then(|oN| oN.DoSomethingN())
</code></pre>
<p>You might ask, where are the cleanup calls. Well, because Rust has guaranteed,
predictable destructors, you don’t need cleanup calls 99% of the time! Files
and sockets will be closed, http connections ended (or returned to the pool) etc.</p>
<p><a href="https://blog.golang.org/error-handling-and-go">Mildly-satisfying workarounds are given</a></p>
<h3 id="lack-of-generics">Lack of generics</h3>
<p>It seems to me lack of generic support is the root cause of all other problems.</p>
<p>Go has <code>nil</code> because without some form of generics, having a <code>Option</code> is not
possible.</p>
<p>Go has poor error handling, as something like Rust’s <code>Result</code> can not be used
without generics.</p>
<p>Go has no proper collections, and you weird <code>make</code> invocations are required
because it lacks generics.</p>
<h3 id="annoyingness">Annoyingness</h3>
<p>I fiddle with the code to try something out, I get an error that something is
not used anymore. I have to remove the <code>import</code> to make the compiler happy.
Then add it again.</p>
<p>Why it can’t be just a warning? Why is it <em>that</em> important for all the
<code>imports</code> to really be used?</p>
<p>Or compiler errors because <code>{</code> is on a newline. Madness.</p>
<p>Go compiler is happy when I don’t check errors returned by a function (maybe by
mistake), and I have to use <code>go vet</code> and <code>golint</code> to ensure there are no real
obvious issues with my code, but it just won’t let me be when it comes to
irrelevant details.</p>
<h3 id="small-things">Small things</h3>
<p>How do you decrement an atomic in Go?</p>
<pre><code class="language-go">AddUint32(&x, ^uint32(c-1))
</code></pre>
<p>That’s how - described right in <a href="https://golang.org/pkg/sync/atomic/#AddUint32">atomic package comment for
AddUint32</a>. Easy to read, and
self-explaining. I mean… come on. It took similar time to write the comment
explaining how to decrement, as it would take to write a much needed function
that would just do it!</p>
<h3 id="community-doesn-t-like-me">Community doesn’t like me</h3>
<p>Couple of times I ventured into Go community gathering places, looking for
advise on how to deal with some of the problems I was having. I don’t know if
it’s me, or the fact that I was referring to mechanisms from other languages,
that Go simply lacks, but every time I got hostile responses in tones of “one
true way of Go” and me being stupid for looking for alternatives to
established Go conventions.</p>
</div>
</section>
<h1 class="content-subhead">
2016-09-15
<p class="post-meta">
<a class="post-tags post-tags-shell" href="http://dpc.pw//tags/shell">shell</a>
</p>
</h1>
<section class="post">
<header class="post-header">
<a href="http://dpc.pw/precache-all-the-things/" class="post-title">Precache all the things!</a>
</header>
<div class="post-description">
<p><img src="http://cdn.memegenerator.net/instances/400x/33671988.jpg" alt="funny meme" /></p>
<p>Having a lot of RAM nowadays is relatively cheap and Linux can make a good use
of it. With tools like <a href="http://en.wikipedia.org/wiki/Preload_(software)">preload</a> most of Linux distributions are
trying to proactively read things that you might want to use soon.</p>
<p>However if your desktop have a ridiculous amount of memory (mine has 32GB) it
may take ages for these tools to make use of all that memory. And why would you pay
for it and then let it just sit idle instead of working for you?</p>
<p>The thing is: you can do much better, because you know what you are going to
use in the future.</p>
<p>So, as always, let’s write a tiny script under the name <code>precache</code>.</p>
<pre><code class="language-bash">#!/bin/sh
exec nice -n 20 ionice -c 3 find "${1:-.}" -xdev -type f \
-exec nice -n 20 ionice -c 3 cat '{}' \; > /dev/null
</code></pre>
<p>Personally I keep it as <code>$HOME/bin/precache</code>.</p>
<p>The basic idea is to traverse through all the subdirectories of an argument
using <code>find</code> and read all the files from the disk, discarding their output. If no
argument is given <code>precache</code> will traverse the current directory.</p>
<p>The <code>nice</code> and <code>ionice</code> commands are used to force all of this to be done only
when the system is really idle, so it’s not slowing down anything else.</p>
<p>Keep in mind that the script will not switch to different filesystems (<code>-xdev</code>
option).</p>
<p>All of this is done to make Linux fill the free memory with cached
data so it’s already waiting for you when you need it. You can check the
memory usage using <code>top</code> command. The <code>cached</code> position is the one that we want
to increase to the point where no memory is sitting idle.</p>
<p>How do I use this script? There are multiple ways.</p>
<p>First, you can preload your whole home directory on boot.</p>
<pre><code class="language-bash">#!/bin/sh
if [ ! -f "/tmp/$USER-home-precache" ]; then
touch -f "/tmp/$USER-home-precache"
precache "$HOME" &
fi
</code></pre>
<p><a href="http://en.gentoo-wiki.com/wiki/Autostart_Programs">Add this command to your autostart on login.</a> or alternatively
just put:</p>
<pre><code>precache /home/<yourusername> &
</code></pre>
<p>in your system’s <code>/etc/rc.local</code>.</p>
<p>Also, when you’re about to work on something in few minutes (like launching a
game or starting a big compilation), you can precache relevant directories to
make the game load and work faster.</p>
</div>
</section>
<h1 class="content-subhead">
2016-09-15
<p class="post-meta">
<a class="post-tags post-tags-shell" href="http://dpc.pw//tags/shell">shell</a><a class="post-tags post-tags-tmux" href="http://dpc.pw//tags/tmux">tmux</a>
</p>
</h1>
<section class="post">
<header class="post-header">
<a href="http://dpc.pw/make-current-dir-a-tmux-session-placeholder./" class="post-title">Make current dir a tmux session placeholder.</a>
</header>
<div class="post-description">
<p><code>tmux-session.sh</code>:</p>
<pre><code class="language-bash">#!/bin/bash
# Reattach to (or spawn new if not existing) tmux session
# tmux session <session_name> [ <session_directory> ]
export STY="tmux-$1"
RC=".tmux"
if [ ! -z "$2" ]; then
RC="$2/$RC"
fi
RC="$(readlink -f "$RC")"
if ! tmux has-session -t "$1" 2>/dev/null ; then
if [ ! -z "$RC" -a -f "$RC" ] ; then
tmux new-session -d -s "$1" "tmux move-window -t 9; exec tmux source-file \"$RC\""
else
tmux new-session -d -s "$1"
fi
fi
exec tmux attach-session -t "$1"
</code></pre>
<p><code>tmux-here.sh</code>:</p>
<pre><code class="language-bash">#!/bin/bash
# Spawn tmux session in current directory
# use path's sha256 hash as session name
exec "$HOME/bin/tmux-session" "$(echo "$PWD" | sha256sum | awk '{ print $1 }')" "$PWD"
</code></pre>
</div>
</section>
<h1 class="content-subhead">
2016-09-15
<p class="post-meta">
<a class="post-tags post-tags-shell" href="http://dpc.pw//tags/shell">shell</a>
</p>
</h1>
<section class="post">
<header class="post-header">
<a href="http://dpc.pw/shell-tip-retry.sh/" class="post-title">Shell tip: `retry.sh`</a>
</header>
<div class="post-description">
<p>It’s often the case when I have a command you want to retry until it’s successful.</p>
<p>It’s useful to have <code>retry.sh</code> script like this:</p>
<pre><code class="language-bash">#!/bin/sh
while ! "$@"; do sleep 1; done
</code></pre>
</div>
</section>
<h1 class="content-subhead">
2016-01-15
<p class="post-meta">
<a class="post-tags post-tags-shell" href="http://dpc.pw//tags/shell">shell</a>
</p>
</h1>
<section class="post">
<header class="post-header">
<a href="http://dpc.pw/prepend-or-append-to-path-like-environment-variable./" class="post-title">Prepend or append to PATH like environment variable.</a>
</header>
<div class="post-description">
<p>In Unix there are quite a lot variables representing path lists of different kind similar to <code>PATH</code> like <code>LD_LIBRARY_PATH</code>, <code>PKG_CONFIG_PATH</code>.</p>
<p>Usual idiom to modify these variables is:</p>
<pre><code>$PATH="$PATH:/new/path/to/something"
</code></pre>
<p>I found it quite a lot of typing in a daily work, so I’m using functions shortening the above to just:</p>
<pre><code>append_env PATH /new/path/to/something
</code></pre>
<p>The version for Bash is:</p>
<pre><code>function append_env {
if [ -z "${!1}" ]; then
export "$1"="$2"
else
export "$1"="${!1}:$2"
fi
}
function prepend_env {
if [ -z "${!1}" ]; then
export "$1"="$2"
else
export "$1"="$2:${!1}"
fi
}
</code></pre>
<p>And for Zsh:</p>
<pre><code>function append_env {
eval "local v=\$$1"
if [ -z "$v" ]; then
export "$1"="$2"
else
export "$1"="$v:$2"
fi
}
function prepend_env {
eval "local v=\$$1"
if [ -z "$v" ]; then
export "$1"="$2"
else
export "$1"="$2:$v"
fi
}
</code></pre>
</div>
</section>
<h1 class="content-subhead">
2014-09-15
<p class="post-meta">
<a class="post-tags post-tags-shell" href="http://dpc.pw//tags/shell">shell</a><a class="post-tags post-tags-c" href="http://dpc.pw//tags/c">c</a>
</p>
</h1>
<section class="post">
<header class="post-header">
<a href="http://dpc.pw/asynchronous-gnu-readline-printing/" class="post-title">Asynchronous GNU Readline printing</a>
</header>
<div class="post-description">
<p>Some while ago I’ve spend my time developing a <a href="http://github.com/dpc/xmppconsole">XMPP command line client</a> which is using <a href="http://code.stanziq.com/strophe/">strophe XMPP library</a>
to handle XMPP and <a href="http://tiswww.case.edu/php/chet/readline/rltop.html">GNU Readline</a> for I/O.</p>
<p>The idea was to have a readline prompt at the bottom and yet be able to asynchronously print incoming messages above it - in the “log window”.</p>
<p>It seems that many people were looking for solution already:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/1512028/gnu-readline-how-do-clear-the-input-line">GNU Readline: how do clear the input line?</a></li>
<li><a href="http://stackoverflow.com/questions/691652/using-gnu-readline-how-can-i-add-ncurses-in-the-same-program">Using GNU Readline; how can I add ncurses in the same program?</a></li>
</ul>
<p>I haven’t found any satisfying answer on the web so I’d like to present my own solution.</p>
<p>Basic idea is to use alternate (asynchronous) GNU Readline interface and on each new asynchronous print:</p>
<ul>
<li>save a copy of current line state</li>
<li>clear both prompt and current line (content + position)</li>
<li>force screen update</li>
<li>print asynchronous event (followed by a newline)</li>
<li>restore prompt and current line state</li>
<li>force screen update</li>
</ul>
<p>Simple it is, indeed and you can see <a href="http://github.com/dpc/xmppconsole/blob/master/src/io.c">a working code</a> if you don’t believe.</p>
<p>The only thing that I was unable to get is preventing putting the original confirmed readline buffer in “log window”. As this is not a big deal for my requirements the complete and universal solution would be able to change what the user typed in the readline buffer just before it’s getting scrolled up and becoming part of the “log window”.</p>
<p>I hope someone will fine it useful, like I do.</p>
<p>Update:</p>
<p>Below is a patch by Denis Linvinus:</p>
<p><a href="http://pastebin.com/SA87Lxqq">http://pastebin.com/SA87Lxqq</a></p>
<p>that he uses to get more “unrestricted log window with a prompt” for his project and wanted me to share with you too. Generally, I think it’s a bit unclean because of using vt100 escape sequences so I’m not going to merge it, but if anyone finds it useful, it’s good for everyone.</p>
</div>
</section>
</div>
<div class="footer">
<div class="pure-menu pure-menu-horizontal pure-menu-open">
<ul>
<li>Powered by <a class="hugo" href="http://hugo.spf13.com/" target="_blank">hugo</a></li>
</ul>
</div>
</div>
<script src="http://dpc.pw//js/all.min.js"></script>
</div>
</div>
</div>
</body>
</html>
| dpc/dpc.github.io | post/index.html | HTML | mit | 27,133 |
(function() {
'use strict';
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '../client')));
app.use('/', routes);
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
module.exports = app;
}());
| akashpjames/Expenses-App | server/app.js | JavaScript | mit | 886 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>ViennaCL - The Vienna Computing Library: symbolic_vector< ID, SCALARTYPE, ALIGNMENT > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">ViennaCL - The Vienna Computing Library
 <span id="projectnumber">1.3.1</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.7.6.1 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Data Fields</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespaceviennacl.html">viennacl</a> </li>
<li class="navelem"><a class="el" href="namespaceviennacl_1_1generator.html">generator</a> </li>
<li class="navelem"><a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">symbolic_vector</a> </li>
</ul>
</div>
</div>
<div class="header">
<div class="summary">
<a href="#pub-types">Public Types</a> |
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pub-static-methods">Static Public Member Functions</a> |
<a href="#pub-static-attribs">Static Public Attributes</a> </div>
<div class="headertitle">
<div class="title">symbolic_vector< ID, SCALARTYPE, ALIGNMENT > Class Template Reference</div> </div>
</div><!--header-->
<div class="contents">
<!-- doxytag: class="viennacl::generator::symbolic_vector" -->
<p>Symbolic vector type.
<a href="classviennacl_1_1generator_1_1symbolic__vector.html#details">More...</a></p>
<p><code>#include <<a class="el" href="symbolic__vector_8hpp_source.html">symbolic_vector.hpp</a>></code></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="pub-types"></a>
Public Types</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">typedef SCALARTYPE </td><td class="memItemRight" valign="bottom"><a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#ae3b49295afe54045affbbd725a4b3c8a">ScalarType</a></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">typedef <a class="el" href="classviennacl_1_1vector.html">viennacl::vector</a><br class="typebreak"/>
< <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#ae3b49295afe54045affbbd725a4b3c8a">ScalarType</a>, <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#a62e9ad0fa1b3d3e62e3b1368a642e2a5">Alignment</a> > </td><td class="memItemRight" valign="bottom"><a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#aade8bf0dd00cefe8123536f079269b2d">runtime_type</a></td></tr>
<tr><td colspan="2"><h2><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr><td class="memTemplParams" colspan="2">template<typename RHS_TYPE > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top"><a class="el" href="structviennacl_1_1generator_1_1enable__if.html">enable_if</a><br class="typebreak"/>
< <a class="el" href="structviennacl_1_1generator_1_1is__same__expression__type.html">is_same_expression_type</a><br class="typebreak"/>
< <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a>, RHS_TYPE ><br class="typebreak"/>
, <a class="el" href="classviennacl_1_1generator_1_1compound__node.html">compound_node</a>< <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a>, <br class="typebreak"/>
<a class="el" href="structviennacl_1_1generator_1_1assign__type.html">assign_type</a>, RHS_TYPE ><br class="typebreak"/>
>::type </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#aeb8cb91f4028b791fcc42749104b544d">operator=</a> (RHS_TYPE const &rhs) const </td></tr>
<tr><td class="memTemplParams" colspan="2">template<typename RHS_TYPE > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top"><a class="el" href="structviennacl_1_1generator_1_1enable__if.html">enable_if</a><br class="typebreak"/>
< <a class="el" href="structviennacl_1_1generator_1_1is__scalar__expression.html">is_scalar_expression</a><br class="typebreak"/>
< RHS_TYPE >, <a class="el" href="classviennacl_1_1generator_1_1compound__node.html">compound_node</a><br class="typebreak"/>
< <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a>, <br class="typebreak"/>
<a class="el" href="structviennacl_1_1generator_1_1inplace__scal__mul__type.html">inplace_scal_mul_type</a>, <br class="typebreak"/>
RHS_TYPE > >::type </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#ad37ae116375b6ff040de8361aa7009d7">operator*=</a> (RHS_TYPE const &rhs) const </td></tr>
<tr><td class="memTemplParams" colspan="2">template<typename RHS_TYPE > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top"><a class="el" href="structviennacl_1_1generator_1_1enable__if.html">enable_if</a><br class="typebreak"/>
< <a class="el" href="structviennacl_1_1generator_1_1is__scalar__expression.html">is_scalar_expression</a><br class="typebreak"/>
< RHS_TYPE >, <a class="el" href="classviennacl_1_1generator_1_1compound__node.html">compound_node</a><br class="typebreak"/>
< <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a>, <br class="typebreak"/>
<a class="el" href="structviennacl_1_1generator_1_1inplace__scal__div__type.html">inplace_scal_div_type</a>, <br class="typebreak"/>
RHS_TYPE > >::type </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#a7f13d96d6e99503d60a0d57e2cd3485c">operator/=</a> (RHS_TYPE const &rhs) const </td></tr>
<tr><td class="memTemplParams" colspan="2">template<typename RHS_TYPE > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top"><a class="el" href="structviennacl_1_1generator_1_1enable__if.html">enable_if</a><br class="typebreak"/>
< <a class="el" href="structviennacl_1_1generator_1_1is__same__expression__type.html">is_same_expression_type</a><br class="typebreak"/>
< <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a>, RHS_TYPE ><br class="typebreak"/>
, <a class="el" href="classviennacl_1_1generator_1_1compound__node.html">compound_node</a>< <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a>, <br class="typebreak"/>
<a class="el" href="structviennacl_1_1generator_1_1inplace__add__type.html">inplace_add_type</a>, RHS_TYPE ><br class="typebreak"/>
>::type </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#ab542044ff83a86b15f737304f0cce679">operator+=</a> (RHS_TYPE const &rhs) const </td></tr>
<tr><td class="memTemplParams" colspan="2">template<typename RHS_TYPE > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top"><a class="el" href="structviennacl_1_1generator_1_1enable__if.html">enable_if</a><br class="typebreak"/>
< <a class="el" href="structviennacl_1_1generator_1_1is__same__expression__type.html">is_same_expression_type</a><br class="typebreak"/>
< <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a>, RHS_TYPE ><br class="typebreak"/>
, <a class="el" href="classviennacl_1_1generator_1_1compound__node.html">compound_node</a>< <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a>, <br class="typebreak"/>
<a class="el" href="structviennacl_1_1generator_1_1inplace__sub__type.html">inplace_sub_type</a>, RHS_TYPE ><br class="typebreak"/>
>::type </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#ab2eb279e4aa72f47a7b9135db90d5c82">operator-=</a> (RHS_TYPE const &rhs) const </td></tr>
<tr><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#a71924732c1a4908b0764e83e82da5adb">operator compound_node< self_type, assign_type, self_type ></a> ()</td></tr>
<tr><td colspan="2"><h2><a name="pub-static-methods"></a>
Static Public Member Functions</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">static const std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#a94960f47a8a5a5db6ee7785c171252f4">name</a> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">static const std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#a26eab9c2d3c2ea43c10e65c31d8bc56d">size2_name</a> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">static const std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#ac19514b9a729db6db6abd6ff453b755e">internal_size2_name</a> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">static const std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#a0948f69273927e19b864ef43297f5c5b">name_argument</a> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">static const std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#a908e68631b5e01cc82f286b563de6671">kernel_arguments</a> ()</td></tr>
<tr><td colspan="2"><h2><a name="pub-static-attribs"></a>
Static Public Attributes</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">static const unsigned int </td><td class="memItemRight" valign="bottom"><a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#a62e9ad0fa1b3d3e62e3b1368a642e2a5">Alignment</a> = ALIGNMENT</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">static const unsigned int </td><td class="memItemRight" valign="bottom"><a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#a4ce1b224962dcde77ec3ce0da36357cd">id</a> = ID</td></tr>
</table>
<hr/><a name="details" id="details"></a><h2>Detailed Description</h2>
<div class="textblock"><h3>template<unsigned int ID, typename SCALARTYPE, unsigned int ALIGNMENT><br/>
class viennacl::generator::symbolic_vector< ID, SCALARTYPE, ALIGNMENT ></h3>
<p>Symbolic vector type. </p>
<dl class=""><dt><b>Template Parameters:</b></dt><dd>
<table class="">
<tr><td class="paramname">ID</td><td>The argument ID of the vector in the generated code </td></tr>
<tr><td class="paramname">SCALARTYPE</td><td>The Scalartype of the vector in the generated code </td></tr>
<tr><td class="paramname">ALIGNMENT</td><td>The Alignment of the vector in the generated code </td></tr>
</table>
</dd>
</dl>
</div><hr/><h2>Member Typedef Documentation</h2>
<a class="anchor" id="aade8bf0dd00cefe8123536f079269b2d"></a><!-- doxytag: member="viennacl::generator::symbolic_vector::runtime_type" ref="aade8bf0dd00cefe8123536f079269b2d" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">typedef <a class="el" href="classviennacl_1_1vector.html">viennacl::vector</a><<a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#ae3b49295afe54045affbbd725a4b3c8a">ScalarType</a>,<a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#a62e9ad0fa1b3d3e62e3b1368a642e2a5">Alignment</a>> <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#aade8bf0dd00cefe8123536f079269b2d">runtime_type</a></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<a class="anchor" id="ae3b49295afe54045affbbd725a4b3c8a"></a><!-- doxytag: member="viennacl::generator::symbolic_vector::ScalarType" ref="ae3b49295afe54045affbbd725a4b3c8a" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">typedef SCALARTYPE <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#ae3b49295afe54045affbbd725a4b3c8a">ScalarType</a></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<hr/><h2>Member Function Documentation</h2>
<a class="anchor" id="ac19514b9a729db6db6abd6ff453b755e"></a><!-- doxytag: member="viennacl::generator::symbolic_vector::internal_size2_name" ref="ac19514b9a729db6db6abd6ff453b755e" args="()" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">static const std::string <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#ac19514b9a729db6db6abd6ff453b755e">internal_size2_name</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td><code> [inline, static]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<a class="anchor" id="a908e68631b5e01cc82f286b563de6671"></a><!-- doxytag: member="viennacl::generator::symbolic_vector::kernel_arguments" ref="a908e68631b5e01cc82f286b563de6671" args="()" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">static const std::string <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#a908e68631b5e01cc82f286b563de6671">kernel_arguments</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td><code> [inline, static]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<a class="anchor" id="a94960f47a8a5a5db6ee7785c171252f4"></a><!-- doxytag: member="viennacl::generator::symbolic_vector::name" ref="a94960f47a8a5a5db6ee7785c171252f4" args="()" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">static const std::string <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#a94960f47a8a5a5db6ee7785c171252f4">name</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td><code> [inline, static]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<a class="anchor" id="a0948f69273927e19b864ef43297f5c5b"></a><!-- doxytag: member="viennacl::generator::symbolic_vector::name_argument" ref="a0948f69273927e19b864ef43297f5c5b" args="()" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">static const std::string <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#a0948f69273927e19b864ef43297f5c5b">name_argument</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td><code> [inline, static]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<a class="anchor" id="a71924732c1a4908b0764e83e82da5adb"></a><!-- doxytag: member="viennacl::generator::symbolic_vector::operator compound_node< self_type, assign_type, self_type >" ref="a71924732c1a4908b0764e83e82da5adb" args="()" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">operator <a class="el" href="classviennacl_1_1generator_1_1compound__node.html">compound_node</a>< <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a>, <a class="el" href="structviennacl_1_1generator_1_1assign__type.html">assign_type</a>, <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a> > </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td><code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<a class="anchor" id="ad37ae116375b6ff040de8361aa7009d7"></a><!-- doxytag: member="viennacl::generator::symbolic_vector::operator*=" ref="ad37ae116375b6ff040de8361aa7009d7" args="(RHS_TYPE const &rhs) const " -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="structviennacl_1_1generator_1_1enable__if.html">enable_if</a><<a class="el" href="structviennacl_1_1generator_1_1is__scalar__expression.html">is_scalar_expression</a><RHS_TYPE>, <a class="el" href="classviennacl_1_1generator_1_1compound__node.html">compound_node</a><<a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a>, <a class="el" href="structviennacl_1_1generator_1_1inplace__scal__mul__type.html">inplace_scal_mul_type</a>, RHS_TYPE > >::type operator*= </td>
<td>(</td>
<td class="paramtype">RHS_TYPE const & </td>
<td class="paramname"><em>rhs</em></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<a class="anchor" id="ab542044ff83a86b15f737304f0cce679"></a><!-- doxytag: member="viennacl::generator::symbolic_vector::operator+=" ref="ab542044ff83a86b15f737304f0cce679" args="(RHS_TYPE const &rhs) const " -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="structviennacl_1_1generator_1_1enable__if.html">enable_if</a><<a class="el" href="structviennacl_1_1generator_1_1is__same__expression__type.html">is_same_expression_type</a><<a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a>,RHS_TYPE>, <a class="el" href="classviennacl_1_1generator_1_1compound__node.html">compound_node</a><<a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a>, <a class="el" href="structviennacl_1_1generator_1_1inplace__add__type.html">inplace_add_type</a>, RHS_TYPE > >::type operator+= </td>
<td>(</td>
<td class="paramtype">RHS_TYPE const & </td>
<td class="paramname"><em>rhs</em></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<a class="anchor" id="ab2eb279e4aa72f47a7b9135db90d5c82"></a><!-- doxytag: member="viennacl::generator::symbolic_vector::operator-=" ref="ab2eb279e4aa72f47a7b9135db90d5c82" args="(RHS_TYPE const &rhs) const " -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="structviennacl_1_1generator_1_1enable__if.html">enable_if</a><<a class="el" href="structviennacl_1_1generator_1_1is__same__expression__type.html">is_same_expression_type</a><<a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a>,RHS_TYPE>, <a class="el" href="classviennacl_1_1generator_1_1compound__node.html">compound_node</a><<a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a>, <a class="el" href="structviennacl_1_1generator_1_1inplace__sub__type.html">inplace_sub_type</a>, RHS_TYPE > >::type operator-= </td>
<td>(</td>
<td class="paramtype">RHS_TYPE const & </td>
<td class="paramname"><em>rhs</em></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<a class="anchor" id="a7f13d96d6e99503d60a0d57e2cd3485c"></a><!-- doxytag: member="viennacl::generator::symbolic_vector::operator/=" ref="a7f13d96d6e99503d60a0d57e2cd3485c" args="(RHS_TYPE const &rhs) const " -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="structviennacl_1_1generator_1_1enable__if.html">enable_if</a><<a class="el" href="structviennacl_1_1generator_1_1is__scalar__expression.html">is_scalar_expression</a><RHS_TYPE>, <a class="el" href="classviennacl_1_1generator_1_1compound__node.html">compound_node</a><<a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a>, <a class="el" href="structviennacl_1_1generator_1_1inplace__scal__div__type.html">inplace_scal_div_type</a>, RHS_TYPE > >::type operator/= </td>
<td>(</td>
<td class="paramtype">RHS_TYPE const & </td>
<td class="paramname"><em>rhs</em></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<a class="anchor" id="aeb8cb91f4028b791fcc42749104b544d"></a><!-- doxytag: member="viennacl::generator::symbolic_vector::operator=" ref="aeb8cb91f4028b791fcc42749104b544d" args="(RHS_TYPE const &rhs) const " -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="structviennacl_1_1generator_1_1enable__if.html">enable_if</a><<a class="el" href="structviennacl_1_1generator_1_1is__same__expression__type.html">is_same_expression_type</a><<a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a>,RHS_TYPE>, <a class="el" href="classviennacl_1_1generator_1_1compound__node.html">compound_node</a><<a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html">self_type</a>, <a class="el" href="structviennacl_1_1generator_1_1assign__type.html">assign_type</a>, RHS_TYPE > >::type operator= </td>
<td>(</td>
<td class="paramtype">RHS_TYPE const & </td>
<td class="paramname"><em>rhs</em></td><td>)</td>
<td> const<code> [inline]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<a class="anchor" id="a26eab9c2d3c2ea43c10e65c31d8bc56d"></a><!-- doxytag: member="viennacl::generator::symbolic_vector::size2_name" ref="a26eab9c2d3c2ea43c10e65c31d8bc56d" args="()" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">static const std::string <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#a26eab9c2d3c2ea43c10e65c31d8bc56d">size2_name</a> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td><code> [inline, static]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<hr/><h2>Field Documentation</h2>
<a class="anchor" id="a62e9ad0fa1b3d3e62e3b1368a642e2a5"></a><!-- doxytag: member="viennacl::generator::symbolic_vector::Alignment" ref="a62e9ad0fa1b3d3e62e3b1368a642e2a5" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">const unsigned int <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#a62e9ad0fa1b3d3e62e3b1368a642e2a5">Alignment</a> = ALIGNMENT<code> [static]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<a class="anchor" id="a4ce1b224962dcde77ec3ce0da36357cd"></a><!-- doxytag: member="viennacl::generator::symbolic_vector::id" ref="a4ce1b224962dcde77ec3ce0da36357cd" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">const unsigned int <a class="el" href="classviennacl_1_1generator_1_1symbolic__vector.html#a4ce1b224962dcde77ec3ce0da36357cd">id</a> = ID<code> [static]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li>viennacl/generator/symbolic_types/<a class="el" href="symbolic__vector_8hpp_source.html">symbolic_vector.hpp</a></li>
</ul>
</div><!-- contents -->
<hr class="footer"/><address class="footer"><small>
Generated on Thu Aug 9 2012 19:49:12 for ViennaCL - The Vienna Computing Library by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.7.6.1
</small></address>
</body>
</html>
| aokomoriuta/ViennaCLFiles | doc/doxygen/html/classviennacl_1_1generator_1_1symbolic__vector.html | HTML | mit | 25,484 |
#include "randomplayer.h"
#include <QDirIterator>
void RandomPlayer::start()
{
this->setMedia(QUrl::fromLocalFile(fileList.takeFirst()));
this->play();
this->_readyToPlay = true;
}
void RandomPlayer::quitPlayMode()
{
this->_readyToPlay = false;
this->stop();
}
bool RandomPlayer::isPlayMode(){
return this->_readyToPlay;
}
void RandomPlayer::initList(bool includePiano, bool includeChants, bool includeMelodies)
{
QString basedir = iPlayer::getMusicRoot();
QStringList listFilter;
listFilter << "*.mp3";
if(!includePiano && !includeChants && !includeMelodies) {
includePiano = true;
}
if (includePiano) {
QDirIterator dirIterator(basedir+"/cantiques/", listFilter ,QDir::Files | QDir::NoSymLinks, QDirIterator::Subdirectories);
while(dirIterator.hasNext())
{
fileList << dirIterator.next();
}
}
if (includeChants) {
QDirIterator dirIterator(basedir+"/chants/", listFilter ,QDir::Files | QDir::NoSymLinks, QDirIterator::Subdirectories);
while(dirIterator.hasNext())
{
fileList << dirIterator.next();
}
}
if (includeMelodies) {
QDirIterator dirIterator(basedir+"/melodies/", listFilter ,QDir::Files | QDir::NoSymLinks, QDirIterator::Subdirectories);
while(dirIterator.hasNext())
{
fileList << dirIterator.next();
}
}
std::random_shuffle(fileList.begin(), fileList.end());
}
| ArnaudBenassy/sono_manager | randomplayer.cpp | C++ | mit | 1,499 |
#ifndef BITCOIN_CHAINPARAMSSEEDS_H
#define BITCOIN_CHAINPARAMSSEEDS_H
/**
* List of fixed seed nodes for the bitcoin network
* AUTOGENERATED by share/seeds/generate-seeds.py
*
* Each line contains a 16-byte IPv6 address and a port.
* IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly.
*/
// ***TODO*** fix generate-seeds.py and REGENERATE
static SeedSpec6 pnSeed6_main[] = {
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0xd9,0x75,0x1d,0x4e}, 2290},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x6d,0xc8,0x9b,0xb8}, 2290}
};
static SeedSpec6 pnSeed6_test[] = {
};
#endif // BITCOIN_CHAINPARAMSSEEDS_H
| puticcoin/putic | src/chainparamsseeds.h | C | mit | 677 |
<h1 align="center">
<br>
<br>
<img width="360" src="logo.png" alt="ulid">
<br>
<br>
<br>
</h1>
[![](https://img.shields.io/pypi/v/python-ulid.svg?style=flat-square)](https://pypi.python.org/pypi/python-ulid)
[![](https://img.shields.io/travis/mdomke/python-ulid/master.svg?style=flat-square)](https://travis-ci.org/mdomke/python-ulid)
[![](https://img.shields.io/pypi/l/python-ulid.svg?style=flat-square)](https://pypi.python.org/pypi/python-ulid)
[![](https://img.shields.io/codecov/c/github/mdomke/python-ulid.svg?style=flat-square)](https://codecov.io/gh/mdomke/python-ulid)
[![](https://readthedocs.org/projects/python-ulid/badge/?version=latest&style=flat-square)](https://python-ulid.readthedocs.io)
[![](https://img.shields.io/badge/code%20style-black-000000.svg?style=flat-square)](https://black.readthedocs.io/en/stable/index.html)
What is this?
=============
This is a port of the original JavaScript [ULID][1] implementation to Python.
A ULID is a *universally unique lexicographically sortable identifier*. It is
- 128-bit compatible with UUID
- 1.21e+24 unique ULIDs per millisecond
- Lexicographically sortable!
- Canonically encoded as a 26 character string, as opposed to the 36 character UUID
- Uses Crockford's base32 for better efficiency and readability (5 bits per character)
- Case insensitive
- No special characters (URL safe)
In general the structure of a ULID is as follows:
```
01AN4Z07BY 79KA1307SR9X4MV3
|----------| |----------------|
Timestamp Randomness
48bits 80bits
```
For more information have a look at the original [specification][2].
Installation
------------
```bash
$ pip install python-ulid
```
Basic Usage
-----------
Create a new `ULID` on from the current timestamp
```python
>>> from ulid import ULID
>>> ulid = ULID()
```
Encode in different formats
```python
>>> str(ulid)
'01BTGNYV6HRNK8K8VKZASZCFPE'
>>> ulid.hex
'015ea15f6cd1c56689a373fab3f63ece'
>>> int(ulid)
1820576928786795198723644692628913870
>>> ulid.bytes
b'\x01^\xa1_l\xd1\xc5f\x89\xa3s\xfa\xb3\xf6>\xce'
```
Access timestamp attribute
```python
>>> ulid.timestamp
1505945939.153
>>> ulid.milliseconds
1505945939153
>>> ulid.datetime
datetime.datetime(2017, 9, 20, 22, 18, 59, 153000, tzinfo=datetime.timezone.utc)
```
Convert to `UUID`
```python
>>> ulid.to_uuid()
UUID('015ea15f-6cd1-c566-89a3-73fab3f63ece')
```
Other implementations
---------------------
- [ahawker/ulid](https://github.com/ahawker/ulid)
- [valohai/ulid2](https://github.com/valohai/ulid2)
- [mdipierro/ulid](https://github.com/mdipierro/ulid)
Changelog
=========
Version 1.0.0
-------------
- Dropped support for Python 2. Only Python 3.6+ is supported.
- Added type annotations
- Added the named constructors `ULID.from_datetime`, `ULID.from_timestamp` and `from_hex`.
- The named constructor `ULID.new` has been removed. Use one of the specifc named constructors
instead. For a new `ULID` created from the current timestamp use the standard constructor.
```python
# old
ulid = ULID.new()
ulid = ULID.new(time.time())
ulid = ULID.new(datetime.now())
# new
ulid = ULID()
ulid = ULID.from_timestamp(time.time())
ulid = ULID.from_datetime(datetime.now())
```
- The `ULID.str` and `ULID.int` methods have been removed in favour of the more Pythonic special
dunder-methods. Use `str(ulid)` and `int(ulid)` instead.
- Added the property `ULID.hex` that returns a hex representation of the `ULID`.
```python
>>> ULID().hex
'0171caa5459a8631a6894d072c8550a8'
```
- Equality checks and ordering now also work with `str`-instances.
- The package now has no external dependencies.
- The test-coverage has been raised to 100%.
[1]: https://github.com/alizain/ulid
[2]: https://github.com/alizain/ulid#specification
| mdomke/python-ulid | README.md | Markdown | mit | 3,829 |
"use strict";
var C = function () {
function C() {
babelHelpers.classCallCheck(this, C);
}
babelHelpers.createClass(C, [{
key: "m",
value: function m(x) {
return 'a';
}
}]);
return C;
}();
| kedromelon/babel | packages/babel-plugin-transform-flow-strip-types/test/fixtures/regression/transformed-class-method-return-type-annotation/expected.js | JavaScript | mit | 223 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using log4net;
using Newtonsoft.Json;
using RoboticsTxt.Lib.Contracts;
using RoboticsTxt.Lib.Contracts.Configuration;
namespace RoboticsTxt.Lib.Components.Sequencer
{
internal class PositionStorageAccessor
{
private readonly ApplicationConfiguration applicationConfiguration;
private readonly ILog logger = LogManager.GetLogger(typeof(PositionStorageAccessor));
public PositionStorageAccessor(ApplicationConfiguration applicationConfiguration)
{
this.applicationConfiguration = applicationConfiguration;
}
private const string FileNamePattern = "Positions_{0}.json";
public bool WritePositionsToFile(IEnumerable<Position> positions)
{
try
{
var positionsJson = JsonConvert.SerializeObject(positions, Formatting.Indented);
var fileName = string.Format(FileNamePattern, applicationConfiguration.ApplicationName);
var stream = new FileStream(fileName, FileMode.Create);
var streamWriter = new StreamWriter(stream);
streamWriter.Write(positionsJson);
streamWriter.Flush();
this.logger.Info($"{positions.Count()} positions written to file {fileName}.");
}
catch (Exception exception)
{
this.logger.Error(exception);
return false;
}
return true;
}
public List<Position> LoadPositionsFromFile()
{
var positions = new List<Position>();
var fileName = string.Format(FileNamePattern, applicationConfiguration.ApplicationName);
if (!File.Exists(fileName))
return positions;
try
{
var stream = new FileStream(fileName, FileMode.Open);
var streamReader = new StreamReader(stream);
var positionsJson = streamReader.ReadToEnd();
positions = JsonConvert.DeserializeObject<List<Position>>(positionsJson);
this.logger.Info($"{positions.Count} positions loaded from file {fileName}.");
}
catch (Exception exception)
{
this.logger.Error(exception);
}
return positions;
}
}
}
| artiso-solutions/robotics-txt-net | TxtControllerLib/Components/Sequencer/PositionStorageAccessor.cs | C# | mit | 2,440 |
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Miruken Docs — SymbolDownloader documentation</title>
<link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
<link rel="stylesheet" href="_static/banner.css" type="text/css" />
<link rel="index" title="Index"
href="genindex.html"/>
<link rel="search" title="Search" href="search.html"/>
<link rel="top" title="SymbolDownloader documentation" href="index.html"/>
<script src="_static/js/modernizr.min.js"></script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search">
<a href="index.html" class="icon icon-home"> SymbolDownloader
</a>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<p class="caption"><span class="caption-text">Table of Contents</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="article/en-US/install.html">Install</a></li>
<li class="toctree-l1"><a class="reference internal" href="article/en-US/usage.html">Usage</a></li>
<li class="toctree-l1"><a class="reference internal" href="article/en-US/configuration.html">Configuration</a></li>
<li class="toctree-l1"><a class="reference internal" href="article/en-US/teamCity.html">Team City</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="index.html">SymbolDownloader</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="index.html">Docs</a> »</li>
<li>Miruken Docs</li>
<li class="wy-breadcrumbs-aside">
<a href="_sources/README.rst.txt" rel="nofollow"> View page source</a>
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<div class="section" id="miruken-docs">
<h1>Miruken Docs<a class="headerlink" href="#miruken-docs" title="Permalink to this headline">¶</a></h1>
<blockquote>
<div>View the docs <a class="reference external" href="http://miruken-dotnet-miruken.readthedocs.io/">here</a></div></blockquote>
<div class="section" id="restructuredtext-rest">
<h2>reStructuredText (reST)<a class="headerlink" href="#restructuredtext-rest" title="Permalink to this headline">¶</a></h2>
<p>This documentation is written with
<a class="reference external" href="http://docutils.sourceforge.net/docs/user/rst/quickstart.html">reStructuredText</a>
and
<a class="reference external" href="http://www.sphinx-doc.org/">Sphinx</a></p>
<p>How to include source code in docs</p>
<ul class="simple">
<li><a class="reference external" href="http://docutils.sourceforge.net/docs/ref/rst/directives.html#include">http://docutils.sourceforge.net/docs/ref/rst/directives.html#include</a></li>
<li><a class="reference external" href="http://sphinx.readthedocs.io/en/stable/markup/code.html#directive-literalinclude">http://sphinx.readthedocs.io/en/stable/markup/code.html#directive-literalinclude</a></li>
</ul>
</div>
<div class="section" id="readthedocs">
<h2>ReadTheDocs<a class="headerlink" href="#readthedocs" title="Permalink to this headline">¶</a></h2>
<p>This documentation is built and hosted with www.ReadTheDocs.io</p>
</div>
</div>
</div>
<div class="articleComments">
</div>
</div>
<footer>
<hr/>
<div role="contentinfo">
<p>
© Copyright 2017, Michael Dudley.
</p>
</div>
Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<div class="rst-versions" data-toggle="rst-versions" role="note" aria-label="versions">
<span class="rst-current-version" data-toggle="rst-current-version">
<span class="fa fa-book"> Other Versions</span>
v: master
<span class="fa fa-caret-down"></span>
</span>
<div class="rst-other-versions">
<dl>
<dt>Branches</dt>
<dd><a href="../develop/README.html">develop</a></dd>
<dd><a href="README.html">master</a></dd>
</dl>
</div>
</div>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT:'./',
VERSION:'',
COLLAPSE_INDEX:false,
FILE_SUFFIX:'.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/js/theme.js"></script>
<script type="text/javascript">
jQuery(function () {
SphinxRtdTheme.StickyNav.enable();
});
</script>
</body>
</html> | miruken/miruken.github.io | documentation/versions/miruken-dotnet/SymbolDownloader/master/README.html | HTML | mit | 6,509 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Vincent Vergnolle
*
* 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.vas.notification;
import java.time.LocalDateTime;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vas.domain.repository.Address;
import org.vas.domain.repository.User;
import org.vas.notification.domain.repository.NotificationService;
/**
* Notification worker for limited users
*
*/
public class NotificationWorker implements Runnable {
protected final Logger logger = LoggerFactory.getLogger(getClass());
protected final List<User> users;
protected final Notifier notifier;
protected final NotificationService notificationService;
public NotificationWorker(List<User> users, NotificationService notificationService, Notifier notifier) {
super();
this.users = users;
this.notifier = notifier;
this.notificationService = notificationService;
}
@Override
public void run() {
if(logger.isTraceEnabled()) {
logger.trace("Start worker with {} users", users);
}
users.forEach(this::notifyUser);
}
protected void notifyUser(User user) {
user.addresses.forEach((address) -> notifyAddress(user, address));
}
protected void notifyAddress(User user, Address address) {
if(logger.isTraceEnabled()) {
logger.trace("Notify address {} - {}", user.username, address.label);
}
notificationService.listByAddress(address).forEach(notif -> doNotify(user, address, notif));
}
protected void doNotify(User user, Address address, Notification notification) {
if(notification.isTime(LocalDateTime.now())) {
dispatch(user, address, notification);
}
}
protected void dispatch(User user, Address address, Notification notification) {
if(logger.isTraceEnabled()) {
logger.trace("Dispatch notification n-{}", notification.id);
}
notifier.dispatch(user, address, notification);
}
}
| vincent7894/vas | vas-notification/src/main/java/org/vas/notification/NotificationWorker.java | Java | mit | 2,998 |
/** @jsx jsx */
import { Transforms } from 'slate'
import { jsx } from '../../..'
export const run = editor => {
Transforms.move(editor, { edge: 'start' })
}
export const input = (
<editor>
<block>
one <anchor />
two t<focus />
hree
</block>
</editor>
)
export const output = (
<editor>
<block>
one t<anchor />
wo t<focus />
hree
</block>
</editor>
)
| ianstormtaylor/slate | packages/slate/test/transforms/move/start/expanded.tsx | TypeScript | mit | 414 |
using UnityEngine;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
// Emanuel Strömgren
public class DebugTrackerVisualizer : MonoBehaviour {
private BinaryFormatter m_Formatter = new BinaryFormatter();
private BinaryFormatter Formatter
{
get { return m_Formatter; }
}
[SerializeField]
[ContextMenuItem("Load File Data", "LoadData")]
private string m_FileName = "";
public string FileName
{
get { return m_FileName; }
}
private TrackerData m_Data;
public TrackerData Data
{
get { return m_Data; }
protected set { m_Data = value; }
}
[SerializeField]
private float m_ColorRate = 10f;
private float ColorRate
{
get { return m_ColorRate / 1000f; }
}
[SerializeField]
private float m_DirectionLength = 1f;
private float DirectionLength
{
get { return m_DirectionLength; }
}
[SerializeField]
[Range(1, 100)]
private int m_TimeStampStep = 10;
private int TimeStampStep
{
get { return m_TimeStampStep; }
}
#if UNITY_EDITOR
void OnDrawGizmosSelected()
{
if (Data.TrackerTime != null)
{
for (int i = 0; i < Data.TrackerTime.Count; i += TimeStampStep)
{
GUIStyle Style = new GUIStyle();
Style.normal.textColor = Color.HSVToRGB((Data.TrackerTime[i] * ColorRate) % 1f, 1f, 1f);
UnityEditor.Handles.Label(Data.PlayerPosition[i] + new Vector3(0f, 1f, 0f), Data.TrackerTime[i].ToString("0.00") + "s", Style);
}
}
}
void OnDrawGizmos()
{
if (Data.TrackerTime != null)
{
for (int i = 0; i < Data.TrackerTime.Count; i++)
{
Gizmos.color = Color.HSVToRGB((Data.TrackerTime[i] * ColorRate) % 1f, 1f, 1f);
if (i > 0)
{
Gizmos.DrawLine(Data.PlayerPosition[i - 1], Data.PlayerPosition[i]);
}
Gizmos.DrawRay(Data.PlayerPosition[i], Data.PlayerDirection[i] * DirectionLength);
}
}
}
#endif
void LoadData()
{
using (Stream FileStream = File.Open(FileName, FileMode.Open))
{
Data = ((SerializableTrackerData)Formatter.Deserialize(FileStream)).Deserialize();
}
}
}
| Towkin/DravenklovaUnity | Assets/Dravenklova/Scripts/PawnScripts/PlayerScripts/DebugTrackerVisualizer.cs | C# | mit | 2,459 |
package shuaicj.hello.configuration.case04;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Spring boot application.
*
* @author shuaicj 2019/10/12
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| shuaicj/hello-java | hello-configuration/hello-configuration-case04/src/main/java/shuaicj/hello/configuration/case04/Application.java | Java | mit | 395 |
# -*- coding: utf-8 -*-
from django.contrib.admin import TabularInline
from .models import GalleryPhoto
class PhotoInline(TabularInline):
"""
Tabular inline that will be displayed in the gallery form during frontend
editing or in the admin site.
"""
model = GalleryPhoto
fk_name = "gallery"
| izimobil/djangocms-unitegallery | djangocms_unitegallery/admin.py | Python | mit | 318 |
// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
// Package epiutil is an utility class with functions
// common to all packages in the epi project.
package epiutil
import "math/rand"
// RandStr returns a string of length n constructed
// from pseudo-randomly selected characters from t.
// The pseudo-randomness uses random values from s.
func RandStr(n int, t string, s rand.Source) string {
l := len(t) - 1
chars := make([]byte, n)
if l > 0 {
for i, p := range rand.New(s).Perm(n) {
chars[i] = t[p%l]
}
}
return string(chars)
}
| mrekucci/epi | internal/epiutil/common.go | GO | mit | 663 |
var assert = require('assert');
var fs = require('fs');
var requireFiles = require(__dirname + '/../lib/requireFiles');
var files = [
__dirname + '/moch/custom_test.txt',
__dirname + '/moch/json_test.json',
__dirname + '/moch/test.js'
];
describe('requireFiles testing', function(){
describe('Structure type', function(){
it('requireFiles should be a function', function(){
assert.equal(typeof requireFiles, 'function');
});
});
describe('Error', function(){
it('Should throw error when an engine isn\'t supported', function(){
assert.throws(function(){
requireFiles(files, {
'.js' : require,
'.json' : require
});
}, /there is no engine registered/);
});
it('Should not throw an error when everything is ok', function(){
assert.doesNotThrow(function(){
result = requireFiles(files.slice(1, 3), {
'.js' : require,
'.json' : require
});
});
});
});
describe('Custom engine', function(){
it('Custom engines should work', function(){
var result = requireFiles(files, {
'.js' : require,
'.json' : require,
'.txt' : function(path){
return fs.readFileSync(path).toString();
}
});
assert.equal(result[files[0]], 'worked\n');
assert.equal(result[files[1]].worked, true);
assert.equal(result[files[2]], 'worked');
});
});
});
| cranic/node-requi | test/requireFiles_test.js | JavaScript | mit | 1,671 |
package com.reactnativeexample;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "ReactNativeExample";
}
/**
* Returns whether dev mode should be enabled.
* This enables e.g. the dev menu.
*/
@Override
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage()
);
}
}
| attrs/webmodules | examples/react-native-web/android/app/src/main/java/com/reactnativeexample/MainActivity.java | Java | mit | 1,050 |
/// <reference path="Global.ts" />
/// <reference path="Decks.ts" />
module ScrollsTypes {
'use strict';
export class DeckCards {
cards:CardsAndStats[] = [];
deck:Deck;
constructor(deck:Deck) {
this.deck = deck;
this.update();
}
update():void {
var r:Card[] = TypesToCards(this.deck.types, _scrolls);
var c:Card[][] = HavingMissingRemainingCards(_cardsReport[1].c, r);
this.cards[0] = new CardsAndStats(c[0], true, true);
this.cards[1] = new CardsAndStats(c[1], true, true);
this.cards[2] = new CardsAndStats(c[2], true, true);
}
addType(type:number):number {
removeDeckStats(this.deck);
var added:number = this.deck.addType(type);
this.update();
addDeckStats(this.deck);
GetDecksStats();
return added;
}
removeType(type:number):number {
removeDeckStats(this.deck);
var removed:number = this.deck.removeType(type);
this.update();
addDeckStats(this.deck);
GetDecksStats();
return removed;
}
replaceDeck(deck:DeckExtended):void {
// this.deck.setDeck(deck.deck);
this.deck.deck = deck.deck;
// this.deck.setAuthor(deck.author);
this.deck.author = deck.author;
this.deck.origin = deck.origin;
this.replaceTypes(deck.types);
}
replaceTypes(types:number[]):void {
removeDeckStats(this.deck);
_.each(_.clone(this.deck.types), (v:number) => {
this.deck.removeType(v);
});
_.each(types, (v:number) => {
this.deck.types.push(v);
});
this.deck.update();
this.update();
addDeckStats(this.deck);
GetDecksStats();
}
}
}
| darosh/scrolls-and-decks | client/types/DeckCards.ts | TypeScript | mit | 1,991 |
class Admin::<%= file_name.classify.pluralize %>Controller < Admin::BaseController
inherit_resources
<% if options[:actions].present? %>
actions <%= options[:actions].map {|a| ":#{a}"}.join(", ") %>
<% else %>
actions :all, except: [:show]
<% end %>
private
def collection
@<%= file_name.pluralize %> ||= end_of_association_chain.page(params[:page]).per(20)
end
end
| kirs/admin-scaffolds | lib/generators/admin_resource/templates/controller.rb | Ruby | mit | 393 |
/*
*= require ecm/tags/backend/application
*/
| robotex82/ecm_tags_backend | app/assets/stylesheets/ecm_tags_backend.css | CSS | mit | 48 |
{{ with $.Site.Params.themeColor }}
<style type="text/css">
.sidebar {
background-color: {{ . }};
}
.read-more-link a {
border-color: {{ . }};
}
.pagination li a {
color: {{ . }};
border: 1px solid {{ . }};
}
.pagination li.active a {
background-color: {{ . }};
}
.pagination li a:hover {
background-color: {{ . }};
opacity: 0.75;
}
footer a,
.content a,
.related-posts li a:hover {
color: {{ . }};
}
</style>
{{ end }}
| VivekRagunathan/vivekragunathan.github.io | themes/soho/layouts/partials/theme-color.html | HTML | mit | 485 |
package net.inpercima.runandfun.service;
import static net.inpercima.runandfun.runkeeper.constants.RunkeeperConstants.ACTIVITIES_MEDIA;
import static net.inpercima.runandfun.runkeeper.constants.RunkeeperConstants.ACTIVITIES_URL_PAGE_SIZE_ONE;
import static net.inpercima.runandfun.runkeeper.constants.RunkeeperConstants.ACTIVITIES_URL_SPECIFIED_PAGE_SIZE_NO_EARLIER_THAN;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.inject.Inject;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.inpercima.restapi.service.RestApiService;
import net.inpercima.runandfun.app.model.AppActivity;
import net.inpercima.runandfun.runkeeper.model.RunkeeperActivities;
import net.inpercima.runandfun.runkeeper.model.RunkeeperActivityItem;
/**
* @author Marcel Jänicke
* @author Sebastian Peters
* @since 26.01.2015
*/
@NoArgsConstructor
@Service
@Slf4j
public class ActivitiesService {
// initial release in 2008 according to http://en.wikipedia.org/wiki/RunKeeper
private static final LocalDate INITIAL_RELEASE_OF_RUNKEEPER = LocalDate.of(2008, 01, 01);
@Inject
private AuthService authService;
@Inject
private RestApiService restApiService;
@Inject
private ActivityRepository repository;
@Inject
private ElasticsearchRestTemplate elasticsearchRestTemplate;
public int indexActivities(final String accessToken) {
final Collection<AppActivity> activities = new ArrayList<>();
final String username = authService.getAppState(accessToken).getUsername();
listActivities(accessToken, calculateFetchDate()).stream().filter(item -> !repository.existsById(item.getId()))
.forEach(item -> addActivity(item, username, activities));
log.info("new activities: {}", activities.size());
if (!activities.isEmpty()) {
repository.saveAll(activities);
}
return activities.size();
}
/**
* List activities live from runkeeper with an accessToken and a date. The full
* size will be determined every time but with the given date only the last
* items will be collected with a max. of the full size.
*
* @param accessToken
* @param from
* @return list of activity items
*/
private List<RunkeeperActivityItem> listActivities(final String accessToken, final LocalDate from) {
log.debug("list activities for token {} until {}", accessToken, from);
// get one item only to get full size
int pageSize = restApiService
.getForObject(ACTIVITIES_URL_PAGE_SIZE_ONE, ACTIVITIES_MEDIA, accessToken, RunkeeperActivities.class)
.getBody().getSize();
// list new activities from given date with max. full size
return restApiService.getForObject(
String.format(ACTIVITIES_URL_SPECIFIED_PAGE_SIZE_NO_EARLIER_THAN, pageSize,
from.format(DateTimeFormatter.ISO_LOCAL_DATE)),
ACTIVITIES_MEDIA, accessToken, RunkeeperActivities.class).getBody().getItemsAsList();
}
private LocalDate calculateFetchDate() {
final AppActivity activity = getLastActivity();
return activity == null ? INITIAL_RELEASE_OF_RUNKEEPER : activity.getDate().toLocalDate();
}
private void addActivity(final RunkeeperActivityItem item, final String username,
final Collection<AppActivity> activities) {
final AppActivity activity = new AppActivity(item.getId(), username, item.getType(), item.getDate(),
item.getDistance(), item.getDuration());
log.debug("prepare {}", activity);
activities.add(activity);
}
/**
* Get last activity from app repository.
*
* @return last activity
*/
public AppActivity getLastActivity() {
return repository.findTopByOrderByDateDesc();
}
/**
* Count activities from app repository.
*
* @return count
*/
public Long countActivities() {
return repository.count();
}
/**
* List activites from app repository.
*
* @param pageable
* @param types
* @param minDate
* @param maxDate
* @param minDistance
* @param maxDistance
* @param query
* @return
*/
public SearchHits<AppActivity> listActivities(final Pageable pageable, final String types, final LocalDate minDate,
final LocalDate maxDate, final Float minDistance, final Float maxDistance, final String query) {
final BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
if (!Strings.isNullOrEmpty(types)) {
final BoolQueryBuilder typesQuery = QueryBuilders.boolQuery();
for (final String type : Splitter.on(',').split(types)) {
typesQuery.should(QueryBuilders.termQuery(AppActivity.FIELD_TYPE, type));
}
queryBuilder.must(typesQuery);
}
if (minDate != null || maxDate != null) {
addDateQuery(queryBuilder, minDate, maxDate);
}
if (minDistance != null || maxDistance != null) {
addDistanceQuery(queryBuilder, minDistance, maxDistance);
}
if (!Strings.isNullOrEmpty(query)) {
addFulltextQuery(queryBuilder, query);
}
if (!queryBuilder.hasClauses()) {
queryBuilder.must(QueryBuilders.matchAllQuery());
}
log.info("{}", queryBuilder);
return elasticsearchRestTemplate.search(
new NativeSearchQueryBuilder().withPageable(pageable).withQuery(queryBuilder).build(),
AppActivity.class, IndexCoordinates.of("activity"));
}
private static void addFulltextQuery(final BoolQueryBuilder queryBuilder, final String query) {
queryBuilder.must(QueryBuilders.termQuery("_all", query.trim()));
}
private static void addDateQuery(final BoolQueryBuilder queryBuilder, final LocalDate minDate,
final LocalDate maxDate) {
final RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery(AppActivity.FIELD_DATE);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'");
if (minDate != null) {
LocalDateTime minDateTime = minDate.atStartOfDay();
rangeQuery.gte(minDateTime.format(formatter));
}
if (maxDate != null) {
LocalDateTime maxDateTime = maxDate.atStartOfDay();
rangeQuery.lte(maxDateTime.format(formatter));
}
queryBuilder.must(rangeQuery);
}
private static void addDistanceQuery(final BoolQueryBuilder queryBuilder, final Float minDistance,
final Float maxDistance) {
final RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery(AppActivity.FIELD_DISTANCE);
if (minDistance != null) {
rangeQuery.gte(minDistance);
}
if (maxDistance != null) {
rangeQuery.lte(maxDistance);
}
queryBuilder.must(rangeQuery);
}
}
| inpercima/run-and-fun | server/src/main/java/net/inpercima/runandfun/service/ActivitiesService.java | Java | mit | 7,790 |
export default function() {
var links = [
{
icon: "fa-sign-in",
title: "Login",
url: "/login"
},
{
icon: "fa-dashboard",
title: "Dashboard",
url: "/"
},
{
icon: "fa-calendar",
title: "Scheduler",
url: "/scheduler"
}
];
return m("#main-sidebar", [
m("ul", {class: "navigation"},
links.map(function(link) {
return m("li", [
m("a", {href: link.url, config: m.route}, [
m("i.menu-icon", {class: "fa " + link.icon}), " ", link.title
])
]);
})
)
]);
}
| dolfelt/scheduler-js | src/component/sidebar.js | JavaScript | mit | 755 |
<html>
<title>nwSGM</title>
<body bgcolor="#000066" text="#FFFF00" link="#8888FF" vlink="#FF0000">
<h1><em>nwSGM</em></h1>
<hr>
<p>
<b><em>Segment generator</em></b>
<p>
<hr>
</body>
</html>
| rangsimanketkaew/NWChem | doc/nwahtml/nwargos_nwSGM.html | HTML | mit | 191 |
@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,600);
body {
font-family: 'Open Sans', sans-serif;
margin: auto;
max-width: 100%;
overflow-x: hidden;
}
.container{
margin: 10px auto;
}
@import url(http://fonts.googleapis.com/css?family=Source+Sans+Pro);
.navbar-brand{
font-family: 'Source Sans Pro', sans-serif;
}
.navbar{
background: linear-gradient(#eef, #dfe3e5);
background-color: #dfe3e5;
margin-bottom: 0;
}
.bevel {
vertical-align: middle;
font-size: 1em;
font-weight: bold;
text-shadow: 1px 1px 1px #eee;
/* color: black;*/
color: #d7dee1;
}
.bevel>li>a:hover {
background: none;
}
.nav-pills>li>a {
color: dimgray;
}
.nav-pills>li>a:hover {
color: black;
}
.pull-right>li>a {
margin-bottom: 0;
background-color: white;
}
.nav-pills {
vertical-align: middle;
}
#head{
margin-top: 0;
height:400px;
background: url(cover.png) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
| mattmc318/pooter | style.css | CSS | mit | 1,054 |
<?php
/**
* Pure-PHP implementation of SFTP.
*
* PHP version 5
*
* Currently only supports SFTPv2 and v3, which, according to wikipedia.org, "is the most widely used version,
* implemented by the popular OpenSSH SFTP server". If you want SFTPv4/5/6 support, provide me with access
* to an SFTPv4/5/6 server.
*
* The API for this library is modeled after the API from PHP's {@link http://php.net/book.ftp FTP extension}.
*
* Here's a short example of how to use this library:
* <code>
* <?php
* include 'vendor/autoload.php';
*
* $sftp = new \phpseclib\Net\SFTP('www.domain.tld');
* if (!$sftp->login('username', 'password')) {
* exit('Login Failed');
* }
*
* echo $sftp->pwd() . "\r\n";
* $sftp->put('filename.ext', 'hello, world!');
* print_r($sftp->nlist());
* ?>
* </code>
*
* @category Net
* @package SFTP
* @author Jim Wigginton <[email protected]>
* @copyright 2009 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net
*/
namespace phpseclib\Net;
use ParagonIE\ConstantTime\Hex;
use phpseclib\Exception\FileNotFoundException;
use phpseclib\Common\Functions\Strings;
/**
* Pure-PHP implementations of SFTP.
*
* @package SFTP
* @author Jim Wigginton <[email protected]>
* @access public
*/
class SFTP extends SSH2
{
/**
* SFTP channel constant
*
* \phpseclib\Net\SSH2::exec() uses 0 and \phpseclib\Net\SSH2::read() / \phpseclib\Net\SSH2::write() use 1.
*
* @see \phpseclib\Net\SSH2::send_channel_packet()
* @see \phpseclib\Net\SSH2::get_channel_packet()
* @access private
*/
const CHANNEL = 0x100;
/**#@+
* @access public
* @see \phpseclib\Net\SFTP::put()
*/
/**
* Reads data from a local file.
*/
const SOURCE_LOCAL_FILE = 1;
/**
* Reads data from a string.
*/
// this value isn't really used anymore but i'm keeping it reserved for historical reasons
const SOURCE_STRING = 2;
/**
* Reads data from callback:
* function callback($length) returns string to proceed, null for EOF
*/
const SOURCE_CALLBACK = 16;
/**
* Resumes an upload
*/
const RESUME = 4;
/**
* Append a local file to an already existing remote file
*/
const RESUME_START = 8;
/**#@-*/
/**
* Packet Types
*
* @see self::__construct()
* @var array
* @access private
*/
private $packet_types = [];
/**
* Status Codes
*
* @see self::__construct()
* @var array
* @access private
*/
private $status_codes = [];
/**
* The Request ID
*
* The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support
* concurrent actions, so it's somewhat academic, here.
*
* @var boolean
* @see self::_send_sftp_packet()
* @access private
*/
private $use_request_id = false;
/**
* The Packet Type
*
* The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support
* concurrent actions, so it's somewhat academic, here.
*
* @var int
* @see self::_get_sftp_packet()
* @access private
*/
private $packet_type = -1;
/**
* Packet Buffer
*
* @var string
* @see self::_get_sftp_packet()
* @access private
*/
private $packet_buffer = '';
/**
* Extensions supported by the server
*
* @var array
* @see self::_initChannel()
* @access private
*/
private $extensions = [];
/**
* Server SFTP version
*
* @var int
* @see self::_initChannel()
* @access private
*/
private $version;
/**
* Current working directory
*
* @var string
* @see self::realpath()
* @see self::chdir()
* @access private
*/
private $pwd = false;
/**
* Packet Type Log
*
* @see self::getLog()
* @var array
* @access private
*/
private $packet_type_log = [];
/**
* Packet Log
*
* @see self::getLog()
* @var array
* @access private
*/
private $packet_log = [];
/**
* Error information
*
* @see self::getSFTPErrors()
* @see self::getLastSFTPError()
* @var array
* @access private
*/
private $sftp_errors = [];
/**
* Stat Cache
*
* Rather than always having to open a directory and close it immediately there after to see if a file is a directory
* we'll cache the results.
*
* @see self::_update_stat_cache()
* @see self::_remove_from_stat_cache()
* @see self::_query_stat_cache()
* @var array
* @access private
*/
private $stat_cache = [];
/**
* Max SFTP Packet Size
*
* @see self::__construct()
* @see self::get()
* @var array
* @access private
*/
private $max_sftp_packet;
/**
* Stat Cache Flag
*
* @see self::disableStatCache()
* @see self::enableStatCache()
* @var bool
* @access private
*/
private $use_stat_cache = true;
/**
* Sort Options
*
* @see self::_comparator()
* @see self::setListOrder()
* @var array
* @access private
*/
private $sortOptions = [];
/**
* Canonicalization Flag
*
* Determines whether or not paths should be canonicalized before being
* passed on to the remote server.
*
* @see self::enablePathCanonicalization()
* @see self::disablePathCanonicalization()
* @see self::realpath()
* @var bool
* @access private
*/
private $canonicalize_paths = true;
/**
* Request Buffers
*
* @see self::_get_sftp_packet()
* @var array
* @access private
*/
var $requestBuffer = array();
/**
* Default Constructor.
*
* Connects to an SFTP server
*
* @param string $host
* @param int $port
* @param int $timeout
* @return \phpseclib\Net\SFTP
* @access public
*/
public function __construct($host, $port = 22, $timeout = 10)
{
parent::__construct($host, $port, $timeout);
$this->max_sftp_packet = 1 << 15;
$this->packet_types = [
1 => 'NET_SFTP_INIT',
2 => 'NET_SFTP_VERSION',
/* the format of SSH_FXP_OPEN changed between SFTPv4 and SFTPv5+:
SFTPv5+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.1
pre-SFTPv5 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.3 */
3 => 'NET_SFTP_OPEN',
4 => 'NET_SFTP_CLOSE',
5 => 'NET_SFTP_READ',
6 => 'NET_SFTP_WRITE',
7 => 'NET_SFTP_LSTAT',
9 => 'NET_SFTP_SETSTAT',
11 => 'NET_SFTP_OPENDIR',
12 => 'NET_SFTP_READDIR',
13 => 'NET_SFTP_REMOVE',
14 => 'NET_SFTP_MKDIR',
15 => 'NET_SFTP_RMDIR',
16 => 'NET_SFTP_REALPATH',
17 => 'NET_SFTP_STAT',
/* the format of SSH_FXP_RENAME changed between SFTPv4 and SFTPv5+:
SFTPv5+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.3
pre-SFTPv5 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.5 */
18 => 'NET_SFTP_RENAME',
19 => 'NET_SFTP_READLINK',
20 => 'NET_SFTP_SYMLINK',
101=> 'NET_SFTP_STATUS',
102=> 'NET_SFTP_HANDLE',
/* the format of SSH_FXP_NAME changed between SFTPv3 and SFTPv4+:
SFTPv4+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-9.4
pre-SFTPv4 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-02#section-7 */
103=> 'NET_SFTP_DATA',
104=> 'NET_SFTP_NAME',
105=> 'NET_SFTP_ATTRS',
200=> 'NET_SFTP_EXTENDED'
];
$this->status_codes = [
0 => 'NET_SFTP_STATUS_OK',
1 => 'NET_SFTP_STATUS_EOF',
2 => 'NET_SFTP_STATUS_NO_SUCH_FILE',
3 => 'NET_SFTP_STATUS_PERMISSION_DENIED',
4 => 'NET_SFTP_STATUS_FAILURE',
5 => 'NET_SFTP_STATUS_BAD_MESSAGE',
6 => 'NET_SFTP_STATUS_NO_CONNECTION',
7 => 'NET_SFTP_STATUS_CONNECTION_LOST',
8 => 'NET_SFTP_STATUS_OP_UNSUPPORTED',
9 => 'NET_SFTP_STATUS_INVALID_HANDLE',
10 => 'NET_SFTP_STATUS_NO_SUCH_PATH',
11 => 'NET_SFTP_STATUS_FILE_ALREADY_EXISTS',
12 => 'NET_SFTP_STATUS_WRITE_PROTECT',
13 => 'NET_SFTP_STATUS_NO_MEDIA',
14 => 'NET_SFTP_STATUS_NO_SPACE_ON_FILESYSTEM',
15 => 'NET_SFTP_STATUS_QUOTA_EXCEEDED',
16 => 'NET_SFTP_STATUS_UNKNOWN_PRINCIPAL',
17 => 'NET_SFTP_STATUS_LOCK_CONFLICT',
18 => 'NET_SFTP_STATUS_DIR_NOT_EMPTY',
19 => 'NET_SFTP_STATUS_NOT_A_DIRECTORY',
20 => 'NET_SFTP_STATUS_INVALID_FILENAME',
21 => 'NET_SFTP_STATUS_LINK_LOOP',
22 => 'NET_SFTP_STATUS_CANNOT_DELETE',
23 => 'NET_SFTP_STATUS_INVALID_PARAMETER',
24 => 'NET_SFTP_STATUS_FILE_IS_A_DIRECTORY',
25 => 'NET_SFTP_STATUS_BYTE_RANGE_LOCK_CONFLICT',
26 => 'NET_SFTP_STATUS_BYTE_RANGE_LOCK_REFUSED',
27 => 'NET_SFTP_STATUS_DELETE_PENDING',
28 => 'NET_SFTP_STATUS_FILE_CORRUPT',
29 => 'NET_SFTP_STATUS_OWNER_INVALID',
30 => 'NET_SFTP_STATUS_GROUP_INVALID',
31 => 'NET_SFTP_STATUS_NO_MATCHING_BYTE_RANGE_LOCK'
];
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-7.1
// the order, in this case, matters quite a lot - see \phpseclib\Net\SFTP::_parseAttributes() to understand why
$this->attributes = [
0x00000001 => 'NET_SFTP_ATTR_SIZE',
0x00000002 => 'NET_SFTP_ATTR_UIDGID', // defined in SFTPv3, removed in SFTPv4+
0x00000004 => 'NET_SFTP_ATTR_PERMISSIONS',
0x00000008 => 'NET_SFTP_ATTR_ACCESSTIME',
// 0x80000000 will yield a floating point on 32-bit systems and converting floating points to integers
// yields inconsistent behavior depending on how php is compiled. so we left shift -1 (which, in
// two's compliment, consists of all 1 bits) by 31. on 64-bit systems this'll yield 0xFFFFFFFF80000000.
// that's not a problem, however, and 'anded' and a 32-bit number, as all the leading 1 bits are ignored.
(-1 << 31) & 0xFFFFFFFF => 'NET_SFTP_ATTR_EXTENDED'
];
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.3
// the flag definitions change somewhat in SFTPv5+. if SFTPv5+ support is added to this library, maybe name
// the array for that $this->open5_flags and similarly alter the constant names.
$this->open_flags = [
0x00000001 => 'NET_SFTP_OPEN_READ',
0x00000002 => 'NET_SFTP_OPEN_WRITE',
0x00000004 => 'NET_SFTP_OPEN_APPEND',
0x00000008 => 'NET_SFTP_OPEN_CREATE',
0x00000010 => 'NET_SFTP_OPEN_TRUNCATE',
0x00000020 => 'NET_SFTP_OPEN_EXCL'
];
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-5.2
// see \phpseclib\Net\SFTP::_parseLongname() for an explanation
$this->file_types = [
1 => 'NET_SFTP_TYPE_REGULAR',
2 => 'NET_SFTP_TYPE_DIRECTORY',
3 => 'NET_SFTP_TYPE_SYMLINK',
4 => 'NET_SFTP_TYPE_SPECIAL',
5 => 'NET_SFTP_TYPE_UNKNOWN',
// the following types were first defined for use in SFTPv5+
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-05#section-5.2
6 => 'NET_SFTP_TYPE_SOCKET',
7 => 'NET_SFTP_TYPE_CHAR_DEVICE',
8 => 'NET_SFTP_TYPE_BLOCK_DEVICE',
9 => 'NET_SFTP_TYPE_FIFO'
];
$this->define_array(
$this->packet_types,
$this->status_codes,
$this->attributes,
$this->open_flags,
$this->file_types
);
if (!defined('NET_SFTP_QUEUE_SIZE')) {
define('NET_SFTP_QUEUE_SIZE', 32);
}
}
/**
* Login
*
* @param string $username
* @param $args[] string password
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return bool
* @access public
*/
public function login($username, ...$args)
{
$this->auth[] = array_merge([$username], $args);
if (!$this->sublogin($username, ...$args)) {
return false;
}
$this->window_size_server_to_client[self::CHANNEL] = $this->window_size;
$packet = Strings::packSSH2(
'CsN3',
NET_SSH2_MSG_CHANNEL_OPEN,
'session',
self::CHANNEL,
$this->window_size,
0x4000
);
$this->send_binary_packet($packet);
$this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_OPEN;
$response = $this->get_channel_packet(self::CHANNEL, true);
if ($response === false) {
return false;
}
$packet = Strings::packSSH2(
'CNsbs',
NET_SSH2_MSG_CHANNEL_REQUEST,
$this->server_channels[self::CHANNEL],
'subsystem',
true,
'sftp'
);
$this->send_binary_packet($packet);
$this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_REQUEST;
$response = $this->get_channel_packet(self::CHANNEL, true);
if ($response === false) {
// from PuTTY's psftp.exe
$command = "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n" .
"test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n" .
"exec sftp-server";
// we don't do $this->exec($command, false) because exec() operates on a different channel and plus the SSH_MSG_CHANNEL_OPEN that exec() does
// is redundant
$packet = Strings::packSSH2(
'CNsCs',
NET_SSH2_MSG_CHANNEL_REQUEST,
$this->server_channels[self::CHANNEL],
'exec',
1,
$command
);
$this->send_binary_packet($packet);
$this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_REQUEST;
$response = $this->get_channel_packet(self::CHANNEL, true);
if ($response === false) {
return false;
}
}
$this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_DATA;
if (!$this->send_sftp_packet(NET_SFTP_INIT, "\0\0\0\3")) {
return false;
}
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_VERSION) {
throw new \UnexpectedValueException('Expected NET_SFTP_VERSION. '
. 'Got packet type: ' . $this->packet_type);
}
list($this->version) = Strings::unpackSSH2('N', $response);
while (!empty($response)) {
list($key, $value) = Strings::unpackSSH2('ss', $response);
$this->extensions[$key] = $value;
}
/*
SFTPv4+ defines a 'newline' extension. SFTPv3 seems to have unofficial support for it via '[email protected]',
however, I'm not sure what '[email protected]' is supposed to do (the fact that it's unofficial means that it's
not in the official SFTPv3 specs) and '[email protected]' / 'newline' are likely not drop-in substitutes for
one another due to the fact that 'newline' comes with a SSH_FXF_TEXT bitmask whereas it seems unlikely that
'[email protected]' would.
*/
/*
if (isset($this->extensions['[email protected]'])) {
$this->extensions['newline'] = $this->extensions['[email protected]'];
unset($this->extensions['[email protected]']);
}
*/
$this->use_request_id = true;
/*
A Note on SFTPv4/5/6 support:
<http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-5.1> states the following:
"If the client wishes to interoperate with servers that support noncontiguous version
numbers it SHOULD send '3'"
Given that the server only sends its version number after the client has already done so, the above
seems to be suggesting that v3 should be the default version. This makes sense given that v3 is the
most popular.
<http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-5.5> states the following;
"If the server did not send the "versions" extension, or the version-from-list was not included, the
server MAY send a status response describing the failure, but MUST then close the channel without
processing any further requests."
So what do you do if you have a client whose initial SSH_FXP_INIT packet says it implements v3 and
a server whose initial SSH_FXP_VERSION reply says it implements v4 and only v4? If it only implements
v4, the "versions" extension is likely not going to have been sent so version re-negotiation as discussed
in draft-ietf-secsh-filexfer-13 would be quite impossible. As such, what \phpseclib\Net\SFTP would do is close the
channel and reopen it with a new and updated SSH_FXP_INIT packet.
*/
switch ($this->version) {
case 2:
case 3:
break;
default:
return false;
}
$this->pwd = $this->realpath('.');
$this->update_stat_cache($this->pwd, []);
return true;
}
/**
* Disable the stat cache
*
* @access public
*/
function disableStatCache()
{
$this->use_stat_cache = false;
}
/**
* Enable the stat cache
*
* @access public
*/
public function enableStatCache()
{
$this->use_stat_cache = true;
}
/**
* Clear the stat cache
*
* @access public
*/
public function clearStatCache()
{
$this->stat_cache = [];
}
/**
* Enable path canonicalization
*
* @access public
*/
public function enablePathCanonicalization()
{
$this->canonicalize_paths = true;
}
/**
* Enable path canonicalization
*
* @access public
*/
public function disablePathCanonicalization()
{
$this->canonicalize_paths = false;
}
/**
* Returns the current directory name
*
* @return mixed
* @access public
*/
public function pwd()
{
return $this->pwd;
}
/**
* Logs errors
*
* @param string $response
* @param int $status
* @access private
*/
private function logError($response, $status = -1)
{
if ($status == -1) {
list($status) = Strings::unpackSSH2('N', $response);
}
list($error) = $this->status_codes[$status];
if ($this->version > 2) {
list($message) = Strings::unpackSSH2('s', $response);
$this->sftp_errors[] = "$error: $message";
} else {
$this->sftp_errors[] = $error;
}
}
/**
* Canonicalize the Server-Side Path Name
*
* SFTP doesn't provide a mechanism by which the current working directory can be changed, so we'll emulate it. Returns
* the absolute (canonicalized) path.
*
* If canonicalize_paths has been disabled using disablePathCanonicalization(), $path is returned as-is.
*
* @see self::chdir()
* @see self::disablePathCanonicalization()
* @param string $path
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return mixed
* @access public
*/
public function realpath($path)
{
if (!$this->canonicalize_paths) {
return $path;
}
if ($this->pwd === false) {
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.9
if (!$this->send_sftp_packet(NET_SFTP_REALPATH, Strings::packSSH2('s', $path))) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_NAME:
// although SSH_FXP_NAME is implemented differently in SFTPv3 than it is in SFTPv4+, the following
// should work on all SFTP versions since the only part of the SSH_FXP_NAME packet the following looks
// at is the first part and that part is defined the same in SFTP versions 3 through 6.
list(, $filename) = Strings::unpackSSH2('Ns', $response);
return $filename;
case NET_SFTP_STATUS:
$this->logError($response);
return false;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_NAME or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
}
if ($path[0] != '/') {
$path = $this->pwd . '/' . $path;
}
$path = explode('/', $path);
$new = [];
foreach ($path as $dir) {
if (!strlen($dir)) {
continue;
}
switch ($dir) {
case '..':
array_pop($new);
case '.':
break;
default:
$new[] = $dir;
}
}
return '/' . implode('/', $new);
}
/**
* Changes the current directory
*
* @param string $dir
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return bool
* @access public
*/
public function chdir($dir)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
// assume current dir if $dir is empty
if ($dir === '') {
$dir = './';
// suffix a slash if needed
} elseif ($dir[strlen($dir) - 1] != '/') {
$dir.= '/';
}
$dir = $this->realpath($dir);
// confirm that $dir is, in fact, a valid directory
if ($this->use_stat_cache && is_array($this->query_stat_cache($dir))) {
$this->pwd = $dir;
return true;
}
// we could do a stat on the alleged $dir to see if it's a directory but that doesn't tell us
// the currently logged in user has the appropriate permissions or not. maybe you could see if
// the file's uid / gid match the currently logged in user's uid / gid but how there's no easy
// way to get those with SFTP
if (!$this->send_sftp_packet(NET_SFTP_OPENDIR, Strings::packSSH2('s', $dir))) {
return false;
}
// see \phpseclib\Net\SFTP::nlist() for a more thorough explanation of the following
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_HANDLE:
$handle = substr($response, 4);
break;
case NET_SFTP_STATUS:
$this->logError($response);
return false;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_HANDLE or NET_SFTP_STATUS' .
'Got packet type: ' . $this->packet_type);
}
if (!$this->close_handle($handle)) {
return false;
}
$this->update_stat_cache($dir, []);
$this->pwd = $dir;
return true;
}
/**
* Returns a list of files in the given directory
*
* @param string $dir
* @param bool $recursive
* @return mixed
* @access public
*/
public function nlist($dir = '.', $recursive = false)
{
return $this->nlist_helper($dir, $recursive, '');
}
/**
* Helper method for nlist
*
* @param string $dir
* @param bool $recursive
* @param string $relativeDir
* @return mixed
* @access private
*/
private function nlist_helper($dir, $recursive, $relativeDir)
{
$files = $this->readlist($dir, false);
if (!$recursive || $files === false) {
return $files;
}
$result = [];
foreach ($files as $value) {
if ($value == '.' || $value == '..') {
$result[] = $relativeDir . $value;
continue;
}
if (is_array($this->query_stat_cache($this->realpath($dir . '/' . $value)))) {
$temp = $this->nlist_helper($dir . '/' . $value, true, $relativeDir . $value . '/');
$temp = is_array($temp) ? $temp : [];
$result = array_merge($result, $temp);
} else {
$result[] = $relativeDir . $value;
}
}
return $result;
}
/**
* Returns a detailed list of files in the given directory
*
* @param string $dir
* @param bool $recursive
* @return mixed
* @access public
*/
public function rawlist($dir = '.', $recursive = false)
{
$files = $this->readlist($dir, true);
if (!$recursive || $files === false) {
return $files;
}
static $depth = 0;
foreach ($files as $key => $value) {
if ($depth != 0 && $key == '..') {
unset($files[$key]);
continue;
}
$is_directory = false;
if ($key != '.' && $key != '..') {
if ($this->use_stat_cache) {
$is_directory = is_array($this->query_stat_cache($this->realpath($dir . '/' . $key)));
} else {
$stat = $this->lstat($dir . '/' . $key);
$is_directory = $stat && $stat['type'] === NET_SFTP_TYPE_DIRECTORY;
}
}
if ($is_directory) {
$depth++;
$files[$key] = $this->rawlist($dir . '/' . $key, true);
$depth--;
} else {
$files[$key] = (object) $value;
}
}
return $files;
}
/**
* Reads a list, be it detailed or not, of files in the given directory
*
* @param string $dir
* @param bool $raw
* @return mixed
* @throws \UnexpectedValueException on receipt of unexpected packets
* @access private
*/
private function readlist($dir, $raw = true)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$dir = $this->realpath($dir . '/');
if ($dir === false) {
return false;
}
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.2
if (!$this->send_sftp_packet(NET_SFTP_OPENDIR, Strings::packSSH2('s', $dir))) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_HANDLE:
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-9.2
// since 'handle' is the last field in the SSH_FXP_HANDLE packet, we'll just remove the first four bytes that
// represent the length of the string and leave it at that
$handle = substr($response, 4);
break;
case NET_SFTP_STATUS:
// presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
$this->logError($response);
return false;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_HANDLE or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
$this->update_stat_cache($dir, []);
$contents = [];
while (true) {
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.2.2
// why multiple SSH_FXP_READDIR packets would be sent when the response to a single one can span arbitrarily many
// SSH_MSG_CHANNEL_DATA messages is not known to me.
if (!$this->send_sftp_packet(NET_SFTP_READDIR, Strings::packSSH2('s', $handle))) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_NAME:
list($count) = Strings::unpackSSH2('N', $response);
for ($i = 0; $i < $count; $i++) {
list($shortname, $longname) = Strings::unpackSSH2('ss', $response);
$attributes = $this->parseAttributes($response);
if (!isset($attributes['type'])) {
$fileType = $this->parseLongname($longname);
if ($fileType) {
$attributes['type'] = $fileType;
}
}
$contents[$shortname] = $attributes + ['filename' => $shortname];
if (isset($attributes['type']) && $attributes['type'] == NET_SFTP_TYPE_DIRECTORY && ($shortname != '.' && $shortname != '..')) {
$this->update_stat_cache($dir . '/' . $shortname, []);
} else {
if ($shortname == '..') {
$temp = $this->realpath($dir . '/..') . '/.';
} else {
$temp = $dir . '/' . $shortname;
}
$this->update_stat_cache($temp, (object) ['lstat' => $attributes]);
}
// SFTPv6 has an optional boolean end-of-list field, but we'll ignore that, since the
// final SSH_FXP_STATUS packet should tell us that, already.
}
break;
case NET_SFTP_STATUS:
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_EOF) {
$this->logError($response, $status);
return false;
}
break 2;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_NAME or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
}
if (!$this->close_handle($handle)) {
return false;
}
if (count($this->sortOptions)) {
uasort($contents, [&$this, 'comparator']);
}
return $raw ? $contents : array_keys($contents);
}
/**
* Compares two rawlist entries using parameters set by setListOrder()
*
* Intended for use with uasort()
*
* @param array $a
* @param array $b
* @return int
* @access private
*/
private function comparator($a, $b)
{
switch (true) {
case $a['filename'] === '.' || $b['filename'] === '.':
if ($a['filename'] === $b['filename']) {
return 0;
}
return $a['filename'] === '.' ? -1 : 1;
case $a['filename'] === '..' || $b['filename'] === '..':
if ($a['filename'] === $b['filename']) {
return 0;
}
return $a['filename'] === '..' ? -1 : 1;
case isset($a['type']) && $a['type'] === NET_SFTP_TYPE_DIRECTORY:
if (!isset($b['type'])) {
return 1;
}
if ($b['type'] !== $a['type']) {
return -1;
}
break;
case isset($b['type']) && $b['type'] === NET_SFTP_TYPE_DIRECTORY:
return 1;
}
foreach ($this->sortOptions as $sort => $order) {
if (!isset($a[$sort]) || !isset($b[$sort])) {
if (isset($a[$sort])) {
return -1;
}
if (isset($b[$sort])) {
return 1;
}
return 0;
}
switch ($sort) {
case 'filename':
$result = strcasecmp($a['filename'], $b['filename']);
if ($result) {
return $order === SORT_DESC ? -$result : $result;
}
break;
case 'permissions':
case 'mode':
$a[$sort]&= 07777;
$b[$sort]&= 07777;
default:
if ($a[$sort] === $b[$sort]) {
break;
}
return $order === SORT_ASC ? $a[$sort] - $b[$sort] : $b[$sort] - $a[$sort];
}
}
}
/**
* Defines how nlist() and rawlist() will be sorted - if at all.
*
* If sorting is enabled directories and files will be sorted independently with
* directories appearing before files in the resultant array that is returned.
*
* Any parameter returned by stat is a valid sort parameter for this function.
* Filename comparisons are case insensitive.
*
* Examples:
*
* $sftp->setListOrder('filename', SORT_ASC);
* $sftp->setListOrder('size', SORT_DESC, 'filename', SORT_ASC);
* $sftp->setListOrder(true);
* Separates directories from files but doesn't do any sorting beyond that
* $sftp->setListOrder();
* Don't do any sort of sorting
*
* @param $args[]
* @access public
*/
public function setListOrder(...$args)
{
$this->sortOptions = [];
if (empty($args)) {
return;
}
$len = count($args) & 0x7FFFFFFE;
for ($i = 0; $i < $len; $i+=2) {
$this->sortOptions[$args[$i]] = $args[$i + 1];
}
if (!count($this->sortOptions)) {
$this->sortOptions = ['bogus' => true];
}
}
/**
* Returns the file size, in bytes, or false, on failure
*
* Files larger than 4GB will show up as being exactly 4GB.
*
* @param string $filename
* @return mixed
* @access public
*/
public function size($filename)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$result = $this->stat($filename);
if ($result === false) {
return false;
}
return isset($result['size']) ? $result['size'] : -1;
}
/**
* Save files / directories to cache
*
* @param string $path
* @param mixed $value
* @access private
*/
private function update_stat_cache($path, $value)
{
if ($this->use_stat_cache === false) {
return;
}
// preg_replace('#^/|/(?=/)|/$#', '', $dir) == str_replace('//', '/', trim($path, '/'))
$dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path));
$temp = &$this->stat_cache;
$max = count($dirs) - 1;
foreach ($dirs as $i => $dir) {
// if $temp is an object that means one of two things.
// 1. a file was deleted and changed to a directory behind phpseclib's back
// 2. it's a symlink. when lstat is done it's unclear what it's a symlink to
if (is_object($temp)) {
$temp = [];
}
if (!isset($temp[$dir])) {
$temp[$dir] = [];
}
if ($i === $max) {
if (is_object($temp[$dir]) && is_object($value)) {
if (!isset($value->stat) && isset($temp[$dir]->stat)) {
$value->stat = $temp[$dir]->stat;
}
if (!isset($value->lstat) && isset($temp[$dir]->lstat)) {
$value->lstat = $temp[$dir]->lstat;
}
}
$temp[$dir] = $value;
break;
}
$temp = &$temp[$dir];
}
}
/**
* Remove files / directories from cache
*
* @param string $path
* @return bool
* @access private
*/
private function remove_from_stat_cache($path)
{
$dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path));
$temp = &$this->stat_cache;
$max = count($dirs) - 1;
foreach ($dirs as $i => $dir) {
if ($i === $max) {
unset($temp[$dir]);
return true;
}
if (!isset($temp[$dir])) {
return false;
}
$temp = &$temp[$dir];
}
}
/**
* Checks cache for path
*
* Mainly used by file_exists
*
* @param string $path
* @return mixed
* @access private
*/
private function query_stat_cache($path)
{
$dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path));
$temp = &$this->stat_cache;
foreach ($dirs as $dir) {
if (!isset($temp[$dir])) {
return null;
}
$temp = &$temp[$dir];
}
return $temp;
}
/**
* Returns general information about a file.
*
* Returns an array on success and false otherwise.
*
* @param string $filename
* @return mixed
* @access public
*/
public function stat($filename)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$filename = $this->realpath($filename);
if ($filename === false) {
return false;
}
if ($this->use_stat_cache) {
$result = $this->query_stat_cache($filename);
if (is_array($result) && isset($result['.']) && isset($result['.']->stat)) {
return $result['.']->stat;
}
if (is_object($result) && isset($result->stat)) {
return $result->stat;
}
}
$stat = $this->stat_helper($filename, NET_SFTP_STAT);
if ($stat === false) {
$this->remove_from_stat_cache($filename);
return false;
}
if (isset($stat['type'])) {
if ($stat['type'] == NET_SFTP_TYPE_DIRECTORY) {
$filename.= '/.';
}
$this->update_stat_cache($filename, (object) ['stat' => $stat]);
return $stat;
}
$pwd = $this->pwd;
$stat['type'] = $this->chdir($filename) ?
NET_SFTP_TYPE_DIRECTORY :
NET_SFTP_TYPE_REGULAR;
$this->pwd = $pwd;
if ($stat['type'] == NET_SFTP_TYPE_DIRECTORY) {
$filename.= '/.';
}
$this->update_stat_cache($filename, (object) ['stat' => $stat]);
return $stat;
}
/**
* Returns general information about a file or symbolic link.
*
* Returns an array on success and false otherwise.
*
* @param string $filename
* @return mixed
* @access public
*/
public function lstat($filename)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$filename = $this->realpath($filename);
if ($filename === false) {
return false;
}
if ($this->use_stat_cache) {
$result = $this->query_stat_cache($filename);
if (is_array($result) && isset($result['.']) && isset($result['.']->lstat)) {
return $result['.']->lstat;
}
if (is_object($result) && isset($result->lstat)) {
return $result->lstat;
}
}
$lstat = $this->stat_helper($filename, NET_SFTP_LSTAT);
if ($lstat === false) {
$this->remove_from_stat_cache($filename);
return false;
}
if (isset($lstat['type'])) {
if ($lstat['type'] == NET_SFTP_TYPE_DIRECTORY) {
$filename.= '/.';
}
$this->update_stat_cache($filename, (object) ['lstat' => $lstat]);
return $lstat;
}
$stat = $this->stat_helper($filename, NET_SFTP_STAT);
if ($lstat != $stat) {
$lstat = array_merge($lstat, ['type' => NET_SFTP_TYPE_SYMLINK]);
$this->update_stat_cache($filename, (object) ['lstat' => $lstat]);
return $stat;
}
$pwd = $this->pwd;
$lstat['type'] = $this->chdir($filename) ?
NET_SFTP_TYPE_DIRECTORY :
NET_SFTP_TYPE_REGULAR;
$this->pwd = $pwd;
if ($lstat['type'] == NET_SFTP_TYPE_DIRECTORY) {
$filename.= '/.';
}
$this->update_stat_cache($filename, (object) ['lstat' => $lstat]);
return $lstat;
}
/**
* Returns general information about a file or symbolic link
*
* Determines information without calling \phpseclib\Net\SFTP::realpath().
* The second parameter can be either NET_SFTP_STAT or NET_SFTP_LSTAT.
*
* @param string $filename
* @param int $type
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return mixed
* @access private
*/
private function stat_helper($filename, $type)
{
// SFTPv4+ adds an additional 32-bit integer field - flags - to the following:
$packet = Strings::packSSH2('s', $filename);
if (!$this->send_sftp_packet($type, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_ATTRS:
return $this->parseAttributes($response);
case NET_SFTP_STATUS:
$this->logError($response);
return false;
}
throw new \UnexpectedValueException('Expected NET_SFTP_ATTRS or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
/**
* Truncates a file to a given length
*
* @param string $filename
* @param int $new_size
* @return bool
* @access public
*/
public function truncate($filename, $new_size)
{
$attr = pack('N3', NET_SFTP_ATTR_SIZE, $new_size / 4294967296, $new_size); // 4294967296 == 0x100000000 == 1<<32
return $this->setstat($filename, $attr, false);
}
/**
* Sets access and modification time of file.
*
* If the file does not exist, it will be created.
*
* @param string $filename
* @param int $time
* @param int $atime
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return bool
* @access public
*/
public function touch($filename, $time = null, $atime = null)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$filename = $this->realpath($filename);
if ($filename === false) {
return false;
}
if (!isset($time)) {
$time = time();
}
if (!isset($atime)) {
$atime = $time;
}
$flags = NET_SFTP_OPEN_WRITE | NET_SFTP_OPEN_CREATE | NET_SFTP_OPEN_EXCL;
$attr = pack('N3', NET_SFTP_ATTR_ACCESSTIME, $time, $atime);
$packet = Strings::packSSH2('sN', $filename, $flags) . $attr;
if (!$this->send_sftp_packet(NET_SFTP_OPEN, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_HANDLE:
return $this->close_handle(substr($response, 4));
case NET_SFTP_STATUS:
$this->logError($response);
break;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_HANDLE or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
return $this->setstat($filename, $attr, false);
}
/**
* Changes file or directory owner
*
* Returns true on success or false on error.
*
* @param string $filename
* @param int $uid
* @param bool $recursive
* @return bool
* @access public
*/
public function chown($filename, $uid, $recursive = false)
{
// quoting from <http://www.kernel.org/doc/man-pages/online/pages/man2/chown.2.html>,
// "if the owner or group is specified as -1, then that ID is not changed"
$attr = pack('N3', NET_SFTP_ATTR_UIDGID, $uid, -1);
return $this->setstat($filename, $attr, $recursive);
}
/**
* Changes file or directory group
*
* Returns true on success or false on error.
*
* @param string $filename
* @param int $gid
* @param bool $recursive
* @return bool
* @access public
*/
public function chgrp($filename, $gid, $recursive = false)
{
$attr = pack('N3', NET_SFTP_ATTR_UIDGID, -1, $gid);
return $this->setstat($filename, $attr, $recursive);
}
/**
* Set permissions on a file.
*
* Returns the new file permissions on success or false on error.
* If $recursive is true than this just returns true or false.
*
* @param int $mode
* @param string $filename
* @param bool $recursive
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return mixed
* @access public
*/
public function chmod($mode, $filename, $recursive = false)
{
if (is_string($mode) && is_int($filename)) {
$temp = $mode;
$mode = $filename;
$filename = $temp;
}
$attr = pack('N2', NET_SFTP_ATTR_PERMISSIONS, $mode & 07777);
if (!$this->setstat($filename, $attr, $recursive)) {
return false;
}
if ($recursive) {
return true;
}
$filename = $this->realpath($filename);
// rather than return what the permissions *should* be, we'll return what they actually are. this will also
// tell us if the file actually exists.
// incidentally, SFTPv4+ adds an additional 32-bit integer field - flags - to the following:
$packet = pack('Na*', strlen($filename), $filename);
if (!$this->send_sftp_packet(NET_SFTP_STAT, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_ATTRS:
$attrs = $this->parseAttributes($response);
return $attrs['permissions'];
case NET_SFTP_STATUS:
$this->logError($response);
return false;
}
throw new \UnexpectedValueException('Expected NET_SFTP_ATTRS or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
/**
* Sets information about a file
*
* @param string $filename
* @param string $attr
* @param bool $recursive
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return bool
* @access private
*/
private function setstat($filename, $attr, $recursive)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$filename = $this->realpath($filename);
if ($filename === false) {
return false;
}
$this->remove_from_stat_cache($filename);
if ($recursive) {
$i = 0;
$result = $this->setstat_recursive($filename, $attr, $i);
$this->read_put_responses($i);
return $result;
}
// SFTPv4+ has an additional byte field - type - that would need to be sent, as well. setting it to
// SSH_FILEXFER_TYPE_UNKNOWN might work. if not, we'd have to do an SSH_FXP_STAT before doing an SSH_FXP_SETSTAT.
if (!$this->send_sftp_packet(NET_SFTP_SETSTAT, Strings::packSSH2('s', $filename) . $attr)) {
return false;
}
/*
"Because some systems must use separate system calls to set various attributes, it is possible that a failure
response will be returned, but yet some of the attributes may be have been successfully modified. If possible,
servers SHOULD avoid this situation; however, clients MUST be aware that this is possible."
-- http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.6
*/
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
throw new \UnexpectedValueException('Expected NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_OK) {
$this->logError($response, $status);
return false;
}
return true;
}
/**
* Recursively sets information on directories on the SFTP server
*
* Minimizes directory lookups and SSH_FXP_STATUS requests for speed.
*
* @param string $path
* @param string $attr
* @param int $i
* @return bool
* @access private
*/
private function setstat_recursive($path, $attr, &$i)
{
if (!$this->read_put_responses($i)) {
return false;
}
$i = 0;
$entries = $this->readlist($path, true);
if ($entries === false) {
return $this->setstat($path, $attr, false);
}
// normally $entries would have at least . and .. but it might not if the directories
// permissions didn't allow reading
if (empty($entries)) {
return false;
}
unset($entries['.'], $entries['..']);
foreach ($entries as $filename => $props) {
if (!isset($props['type'])) {
return false;
}
$temp = $path . '/' . $filename;
if ($props['type'] == NET_SFTP_TYPE_DIRECTORY) {
if (!$this->setstat_recursive($temp, $attr, $i)) {
return false;
}
} else {
if (!$this->send_sftp_packet(NET_SFTP_SETSTAT, Strings::packSSH2('s', $temp) . $attr)) {
return false;
}
$i++;
if ($i >= NET_SFTP_QUEUE_SIZE) {
if (!$this->read_put_responses($i)) {
return false;
}
$i = 0;
}
}
}
if (!$this->send_sftp_packet(NET_SFTP_SETSTAT, Strings::packSSH2('s', $path) . $attr)) {
return false;
}
$i++;
if ($i >= NET_SFTP_QUEUE_SIZE) {
if (!$this->read_put_responses($i)) {
return false;
}
$i = 0;
}
return true;
}
/**
* Return the target of a symbolic link
*
* @param string $link
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return mixed
* @access public
*/
public function readlink($link)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$link = $this->realpath($link);
if (!$this->send_sftp_packet(NET_SFTP_READLINK, Strings::packSSH2('s', $link))) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_NAME:
break;
case NET_SFTP_STATUS:
$this->logError($response);
return false;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_NAME or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
list($count) = Strings::unpackSSH2('N', $response);
// the file isn't a symlink
if (!$count) {
return false;
}
list($filename) = Strings::unpackSSH2('s', $response);
return $filename;
}
/**
* Create a symlink
*
* symlink() creates a symbolic link to the existing target with the specified name link.
*
* @param string $target
* @param string $link
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return bool
* @access public
*/
public function symlink($target, $link)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
//$target = $this->realpath($target);
$link = $this->realpath($link);
$packet = Strings::packSSH2('ss', $target, $link);
if (!$this->send_sftp_packet(NET_SFTP_SYMLINK, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
throw new \UnexpectedValueException('Expected NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_OK) {
$this->logError($response, $status);
return false;
}
return true;
}
/**
* Creates a directory.
*
* @param string $dir
* @param int $mode
* @param bool $recursive
* @return bool
* @access public
*/
public function mkdir($dir, $mode = -1, $recursive = false)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$dir = $this->realpath($dir);
// by not providing any permissions, hopefully the server will use the logged in users umask - their
// default permissions.
$attr = $mode == -1 ? "\0\0\0\0" : pack('N2', NET_SFTP_ATTR_PERMISSIONS, $mode & 07777);
if ($recursive) {
$dirs = explode('/', preg_replace('#/(?=/)|/$#', '', $dir));
if (empty($dirs[0])) {
array_shift($dirs);
$dirs[0] = '/' . $dirs[0];
}
for ($i = 0; $i < count($dirs); $i++) {
$temp = array_slice($dirs, 0, $i + 1);
$temp = implode('/', $temp);
$result = $this->mkdir_helper($temp, $attr);
}
return $result;
}
return $this->mkdir_helper($dir, $attr);
}
/**
* Helper function for directory creation
*
* @param string $dir
* @param string $attr
* @return bool
* @access private
*/
private function mkdir_helper($dir, $attr)
{
if (!$this->send_sftp_packet(NET_SFTP_MKDIR, Strings::packSSH2('s', $dir) . $attr)) {
return false;
}
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
throw new \UnexpectedValueException('Expected NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_OK) {
$this->logError($response, $status);
return false;
}
return true;
}
/**
* Removes a directory.
*
* @param string $dir
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return bool
* @access public
*/
public function rmdir($dir)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$dir = $this->realpath($dir);
if ($dir === false) {
return false;
}
if (!$this->send_sftp_packet(NET_SFTP_RMDIR, Strings::packSSH2('s', $dir))) {
return false;
}
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
throw new \UnexpectedValueException('Expected NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_OK) {
// presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED?
$this->logError($response, $status);
return false;
}
$this->remove_from_stat_cache($dir);
// the following will do a soft delete, which would be useful if you deleted a file
// and then tried to do a stat on the deleted file. the above, in contrast, does
// a hard delete
//$this->update_stat_cache($dir, false);
return true;
}
/**
* Uploads a file to the SFTP server.
*
* By default, \phpseclib\Net\SFTP::put() does not read from the local filesystem. $data is dumped directly into $remote_file.
* So, for example, if you set $data to 'filename.ext' and then do \phpseclib\Net\SFTP::get(), you will get a file, twelve bytes
* long, containing 'filename.ext' as its contents.
*
* Setting $mode to self::SOURCE_LOCAL_FILE will change the above behavior. With self::SOURCE_LOCAL_FILE, $remote_file will
* contain as many bytes as filename.ext does on your local filesystem. If your filename.ext is 1MB then that is how
* large $remote_file will be, as well.
*
* Setting $mode to self::SOURCE_CALLBACK will use $data as callback function, which gets only one parameter -- number of bytes to return, and returns a string if there is some data or null if there is no more data
*
* If $data is a resource then it'll be used as a resource instead.
*
* Currently, only binary mode is supported. As such, if the line endings need to be adjusted, you will need to take
* care of that, yourself.
*
* $mode can take an additional two parameters - self::RESUME and self::RESUME_START. These are bitwise AND'd with
* $mode. So if you want to resume upload of a 300mb file on the local file system you'd set $mode to the following:
*
* self::SOURCE_LOCAL_FILE | self::RESUME
*
* If you wanted to simply append the full contents of a local file to the full contents of a remote file you'd replace
* self::RESUME with self::RESUME_START.
*
* If $mode & (self::RESUME | self::RESUME_START) then self::RESUME_START will be assumed.
*
* $start and $local_start give you more fine grained control over this process and take precident over self::RESUME
* when they're non-negative. ie. $start could let you write at the end of a file (like self::RESUME) or in the middle
* of one. $local_start could let you start your reading from the end of a file (like self::RESUME_START) or in the
* middle of one.
*
* Setting $local_start to > 0 or $mode | self::RESUME_START doesn't do anything unless $mode | self::SOURCE_LOCAL_FILE.
*
* @param string $remote_file
* @param string|resource $data
* @param int $mode
* @param int $start
* @param int $local_start
* @param callable|null $progressCallback
* @throws \UnexpectedValueException on receipt of unexpected packets
* @throws \BadFunctionCallException if you're uploading via a callback and the callback function is invalid
* @throws \phpseclib\Exception\FileNotFoundException if you're uploading via a file and the file doesn't exist
* @return bool
* @access public
* @internal ASCII mode for SFTPv4/5/6 can be supported by adding a new function - \phpseclib\Net\SFTP::setMode().
*/
public function put($remote_file, $data, $mode = self::SOURCE_STRING, $start = -1, $local_start = -1, $progressCallback = null)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$remote_file = $this->realpath($remote_file);
if ($remote_file === false) {
return false;
}
$this->remove_from_stat_cache($remote_file);
$flags = NET_SFTP_OPEN_WRITE | NET_SFTP_OPEN_CREATE;
// according to the SFTP specs, NET_SFTP_OPEN_APPEND should "force all writes to append data at the end of the file."
// in practice, it doesn't seem to do that.
//$flags|= ($mode & self::RESUME) ? NET_SFTP_OPEN_APPEND : NET_SFTP_OPEN_TRUNCATE;
if ($start >= 0) {
$offset = $start;
} elseif ($mode & self::RESUME) {
// if NET_SFTP_OPEN_APPEND worked as it should _size() wouldn't need to be called
$size = $this->size($remote_file);
$offset = $size !== false ? $size : 0;
} else {
$offset = 0;
$flags|= NET_SFTP_OPEN_TRUNCATE;
}
$packet = Strings::packSSH2('sNN', $remote_file, $flags, 0);
if (!$this->send_sftp_packet(NET_SFTP_OPEN, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_HANDLE:
$handle = substr($response, 4);
break;
case NET_SFTP_STATUS:
$this->logError($response);
return false;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_HANDLE or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.2.3
$dataCallback = false;
switch (true) {
case $mode & self::SOURCE_CALLBACK:
if (!is_callable($data)) {
throw new \BadFunctionCallException("\$data should be is_callable() if you specify SOURCE_CALLBACK flag");
}
$dataCallback = $data;
// do nothing
break;
case is_resource($data):
$mode = $mode & ~self::SOURCE_LOCAL_FILE;
$info = stream_get_meta_data($data);
if ($info['wrapper_type'] == 'PHP' && $info['stream_type'] == 'Input') {
$fp = fopen('php://memory', 'w+');
stream_copy_to_stream($data, $fp);
rewind($fp);
} else {
$fp = $data;
}
break;
case $mode & self::SOURCE_LOCAL_FILE:
if (!is_file($data)) {
throw new FileNotFoundException("$data is not a valid file");
}
$fp = @fopen($data, 'rb');
if (!$fp) {
return false;
}
}
if (isset($fp)) {
$stat = fstat($fp);
$size = !empty($stat) ? $stat['size'] : 0;
if ($local_start >= 0) {
fseek($fp, $local_start);
$size-= $local_start;
}
} elseif ($dataCallback) {
$size = 0;
} else {
$size = strlen($data);
}
$sent = 0;
$size = $size < 0 ? ($size & 0x7FFFFFFF) + 0x80000000 : $size;
$sftp_packet_size = 4096; // PuTTY uses 4096
// make the SFTP packet be exactly 4096 bytes by including the bytes in the NET_SFTP_WRITE packets "header"
$sftp_packet_size-= strlen($handle) + 25;
$i = 0;
while ($dataCallback || ($size === 0 || $sent < $size)) {
if ($dataCallback) {
$temp = call_user_func($dataCallback, $sftp_packet_size);
if (is_null($temp)) {
break;
}
} else {
$temp = isset($fp) ? fread($fp, $sftp_packet_size) : substr($data, $sent, $sftp_packet_size);
if ($temp === false || $temp === '') {
break;
}
}
$subtemp = $offset + $sent;
$packet = pack('Na*N3a*', strlen($handle), $handle, $subtemp / 4294967296, $subtemp, strlen($temp), $temp);
if (!$this->send_sftp_packet(NET_SFTP_WRITE, $packet)) {
if ($mode & self::SOURCE_LOCAL_FILE) {
fclose($fp);
}
return false;
}
$sent+= strlen($temp);
if (is_callable($progressCallback)) {
call_user_func($progressCallback, $sent);
}
$i++;
if ($i == NET_SFTP_QUEUE_SIZE) {
if (!$this->read_put_responses($i)) {
$i = 0;
break;
}
$i = 0;
}
}
if (!$this->read_put_responses($i)) {
if ($mode & self::SOURCE_LOCAL_FILE) {
fclose($fp);
}
$this->close_handle($handle);
return false;
}
if ($mode & self::SOURCE_LOCAL_FILE) {
fclose($fp);
}
return $this->close_handle($handle);
}
/**
* Reads multiple successive SSH_FXP_WRITE responses
*
* Sending an SSH_FXP_WRITE packet and immediately reading its response isn't as efficient as blindly sending out $i
* SSH_FXP_WRITEs, in succession, and then reading $i responses.
*
* @param int $i
* @return bool
* @throws \UnexpectedValueException on receipt of unexpected packets
* @access private
*/
private function read_put_responses($i)
{
while ($i--) {
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
throw new \UnexpectedValueException('Expected NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_OK) {
$this->logError($response, $status);
break;
}
}
return $i < 0;
}
/**
* Close handle
*
* @param string $handle
* @return bool
* @throws \UnexpectedValueException on receipt of unexpected packets
* @access private
*/
private function close_handle($handle)
{
if (!$this->send_sftp_packet(NET_SFTP_CLOSE, pack('Na*', strlen($handle), $handle))) {
return false;
}
// "The client MUST release all resources associated with the handle regardless of the status."
// -- http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.3
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
throw new \UnexpectedValueException('Expected NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_OK) {
$this->logError($response, $status);
return false;
}
return true;
}
/**
* Downloads a file from the SFTP server.
*
* Returns a string containing the contents of $remote_file if $local_file is left undefined or a boolean false if
* the operation was unsuccessful. If $local_file is defined, returns true or false depending on the success of the
* operation.
*
* $offset and $length can be used to download files in chunks.
*
* @param string $remote_file
* @param string|bool|resource $local_file
* @param int $offset
* @param int $length
* @param callable|null $progressCallback
* @throws \UnexpectedValueException on receipt of unexpected packets
* @return mixed
* @access public
*/
public function get($remote_file, $local_file = false, $offset = 0, $length = -1, $progressCallback = null)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$remote_file = $this->realpath($remote_file);
if ($remote_file === false) {
return false;
}
$packet = pack('Na*N2', strlen($remote_file), $remote_file, NET_SFTP_OPEN_READ, 0);
if (!$this->send_sftp_packet(NET_SFTP_OPEN, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_HANDLE:
$handle = substr($response, 4);
break;
case NET_SFTP_STATUS: // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
$this->logError($response);
return false;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_HANDLE or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
if (is_resource($local_file)) {
$fp = $local_file;
$stat = fstat($fp);
$res_offset = $stat['size'];
} else {
$res_offset = 0;
if ($local_file !== false) {
$fp = fopen($local_file, 'wb');
if (!$fp) {
return false;
}
} else {
$content = '';
}
}
$fclose_check = $local_file !== false && !is_resource($local_file);
$start = $offset;
$read = 0;
while (true) {
$i = 0;
while ($i < NET_SFTP_QUEUE_SIZE && ($length < 0 || $read < $length)) {
$tempoffset = $start + $read;
$packet_size = $length > 0 ? min($this->max_sftp_packet, $length - $read) : $this->max_sftp_packet;
$packet = Strings::packSSH2('sN3', $handle, $tempoffset / 4294967296, $tempoffset, $packet_size);
if (!$this->send_sftp_packet(NET_SFTP_READ, $packet, $i)) {
if ($fclose_check) {
fclose($fp);
}
return false;
}
$packet = null;
$read+= $packet_size;
if (is_callable($progressCallback)) {
call_user_func($progressCallback, $read);
}
$i++;
}
if (!$i) {
break;
}
$packets_sent = $i - 1;
$clear_responses = false;
while ($i > 0) {
$i--;
if ($clear_responses) {
$this->get_sftp_packet($packets_sent - $i);
continue;
} else {
$response = $this->get_sftp_packet($packets_sent - $i);
}
switch ($this->packet_type) {
case NET_SFTP_DATA:
$temp = substr($response, 4);
$offset+= strlen($temp);
if ($local_file === false) {
$content.= $temp;
} else {
fputs($fp, $temp);
}
$temp = null;
break;
case NET_SFTP_STATUS:
// could, in theory, return false if !strlen($content) but we'll hold off for the time being
$this->logError($response);
$clear_responses = true; // don't break out of the loop yet, so we can read the remaining responses
break;
default:
if ($fclose_check) {
fclose($fp);
}
throw new \UnexpectedValueException('Expected NET_SFTP_DATA or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
$response = null;
}
if ($clear_responses) {
break;
}
}
if ($length > 0 && $length <= $offset - $start) {
if ($local_file === false) {
$content = substr($content, 0, $length);
} else {
ftruncate($fp, $length + $res_offset);
}
}
if ($fclose_check) {
fclose($fp);
}
if (!$this->close_handle($handle)) {
return false;
}
// if $content isn't set that means a file was written to
return isset($content) ? $content : true;
}
/**
* Deletes a file on the SFTP server.
*
* @param string $path
* @param bool $recursive
* @return bool
* @throws \UnexpectedValueException on receipt of unexpected packets
* @access public
*/
public function delete($path, $recursive = true)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
if (is_object($path)) {
// It's an object. Cast it as string before we check anything else.
$path = (string) $path;
}
if (!is_string($path) || $path == '') {
return false;
}
$path = $this->realpath($path);
if ($path === false) {
return false;
}
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.3
if (!$this->send_sftp_packet(NET_SFTP_REMOVE, pack('Na*', strlen($path), $path))) {
return false;
}
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
throw new \UnexpectedValueException('Expected NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
// if $status isn't SSH_FX_OK it's probably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_OK) {
$this->logError($response, $status);
if (!$recursive) {
return false;
}
$i = 0;
$result = $this->delete_recursive($path, $i);
$this->read_put_responses($i);
return $result;
}
$this->remove_from_stat_cache($path);
return true;
}
/**
* Recursively deletes directories on the SFTP server
*
* Minimizes directory lookups and SSH_FXP_STATUS requests for speed.
*
* @param string $path
* @param int $i
* @return bool
* @access private
*/
private function delete_recursive($path, &$i)
{
if (!$this->read_put_responses($i)) {
return false;
}
$i = 0;
$entries = $this->readlist($path, true);
// normally $entries would have at least . and .. but it might not if the directories
// permissions didn't allow reading
if (empty($entries)) {
return false;
}
unset($entries['.'], $entries['..']);
foreach ($entries as $filename => $props) {
if (!isset($props['type'])) {
return false;
}
$temp = $path . '/' . $filename;
if ($props['type'] == NET_SFTP_TYPE_DIRECTORY) {
if (!$this->delete_recursive($temp, $i)) {
return false;
}
} else {
if (!$this->send_sftp_packet(NET_SFTP_REMOVE, Strings::packSSH2('s', $temp))) {
return false;
}
$this->remove_from_stat_cache($temp);
$i++;
if ($i >= NET_SFTP_QUEUE_SIZE) {
if (!$this->read_put_responses($i)) {
return false;
}
$i = 0;
}
}
}
if (!$this->send_sftp_packet(NET_SFTP_RMDIR, Strings::packSSH2('s', $path))) {
return false;
}
$this->remove_from_stat_cache($path);
$i++;
if ($i >= NET_SFTP_QUEUE_SIZE) {
if (!$this->read_put_responses($i)) {
return false;
}
$i = 0;
}
return true;
}
/**
* Checks whether a file or directory exists
*
* @param string $path
* @return bool
* @access public
*/
public function file_exists($path)
{
if ($this->use_stat_cache) {
$path = $this->realpath($path);
$result = $this->query_stat_cache($path);
if (isset($result)) {
// return true if $result is an array or if it's an stdClass object
return $result !== false;
}
}
return $this->stat($path) !== false;
}
/**
* Tells whether the filename is a directory
*
* @param string $path
* @return bool
* @access public
*/
public function is_dir($path)
{
$result = $this->get_stat_cache_prop($path, 'type');
if ($result === false) {
return false;
}
return $result === NET_SFTP_TYPE_DIRECTORY;
}
/**
* Tells whether the filename is a regular file
*
* @param string $path
* @return bool
* @access public
*/
public function is_file($path)
{
$result = $this->get_stat_cache_prop($path, 'type');
if ($result === false) {
return false;
}
return $result === NET_SFTP_TYPE_REGULAR;
}
/**
* Tells whether the filename is a symbolic link
*
* @param string $path
* @return bool
* @access public
*/
public function is_link($path)
{
$result = $this->get_lstat_cache_prop($path, 'type');
if ($result === false) {
return false;
}
return $result === NET_SFTP_TYPE_SYMLINK;
}
/**
* Tells whether a file exists and is readable
*
* @param string $path
* @return bool
* @access public
*/
public function is_readable($path)
{
$packet = Strings::packSSH2('sNN', $this->realpath($path), NET_SFTP_OPEN_READ, 0);
if (!$this->send_sftp_packet(NET_SFTP_OPEN, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_HANDLE:
return true;
case NET_SFTP_STATUS: // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
return false;
default:
throw new \UnexpectedValueException('Expected NET_SFTP_HANDLE or NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
}
/**
* Tells whether the filename is writable
*
* @param string $path
* @return bool
* @access public
*/
public function is_writable($path)
{
$packet = Strings::packSSH2('sNN', $this->realpath($path), NET_SFTP_OPEN_WRITE, 0);
if (!$this->send_sftp_packet(NET_SFTP_OPEN, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_HANDLE:
return true;
case NET_SFTP_STATUS: // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
return false;
default:
throw new \UnexpectedValueException('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
}
/**
* Tells whether the filename is writeable
*
* Alias of is_writable
*
* @param string $path
* @return bool
* @access public
*/
public function is_writeable($path)
{
return $this->is_writable($path);
}
/**
* Gets last access time of file
*
* @param string $path
* @return mixed
* @access public
*/
public function fileatime($path)
{
return $this->get_stat_cache_prop($path, 'atime');
}
/**
* Gets file modification time
*
* @param string $path
* @return mixed
* @access public
*/
public function filemtime($path)
{
return $this->get_stat_cache_prop($path, 'mtime');
}
/**
* Gets file permissions
*
* @param string $path
* @return mixed
* @access public
*/
public function fileperms($path)
{
return $this->get_stat_cache_prop($path, 'permissions');
}
/**
* Gets file owner
*
* @param string $path
* @return mixed
* @access public
*/
public function fileowner($path)
{
return $this->get_stat_cache_prop($path, 'uid');
}
/**
* Gets file group
*
* @param string $path
* @return mixed
* @access public
*/
public function filegroup($path)
{
return $this->get_stat_cache_prop($path, 'gid');
}
/**
* Gets file size
*
* @param string $path
* @return mixed
* @access public
*/
public function filesize($path)
{
return $this->get_stat_cache_prop($path, 'size');
}
/**
* Gets file type
*
* @param string $path
* @return mixed
* @access public
*/
public function filetype($path)
{
$type = $this->get_stat_cache_prop($path, 'type');
if ($type === false) {
return false;
}
switch ($type) {
case NET_SFTP_TYPE_BLOCK_DEVICE:
return 'block';
case NET_SFTP_TYPE_CHAR_DEVICE:
return 'char';
case NET_SFTP_TYPE_DIRECTORY:
return 'dir';
case NET_SFTP_TYPE_FIFO:
return 'fifo';
case NET_SFTP_TYPE_REGULAR:
return 'file';
case NET_SFTP_TYPE_SYMLINK:
return 'link';
default:
return false;
}
}
/**
* Return a stat properity
*
* Uses cache if appropriate.
*
* @param string $path
* @param string $prop
* @return mixed
* @access private
*/
private function get_stat_cache_prop($path, $prop)
{
return $this->get_xstat_cache_prop($path, $prop, 'stat');
}
/**
* Return an lstat properity
*
* Uses cache if appropriate.
*
* @param string $path
* @param string $prop
* @return mixed
* @access private
*/
private function get_lstat_cache_prop($path, $prop)
{
return $this->get_xstat_cache_prop($path, $prop, 'lstat');
}
/**
* Return a stat or lstat properity
*
* Uses cache if appropriate.
*
* @param string $path
* @param string $prop
* @param string $type
* @return mixed
* @access private
*/
private function get_xstat_cache_prop($path, $prop, $type)
{
if ($this->use_stat_cache) {
$path = $this->realpath($path);
$result = $this->query_stat_cache($path);
if (is_object($result) && isset($result->$type)) {
return $result->{$type}[$prop];
}
}
$result = $this->$type($path);
if ($result === false || !isset($result[$prop])) {
return false;
}
return $result[$prop];
}
/**
* Renames a file or a directory on the SFTP server
*
* @param string $oldname
* @param string $newname
* @return bool
* @throws \UnexpectedValueException on receipt of unexpected packets
* @access public
*/
public function rename($oldname, $newname)
{
if (!($this->bitmap & SSH2::MASK_LOGIN)) {
return false;
}
$oldname = $this->realpath($oldname);
$newname = $this->realpath($newname);
if ($oldname === false || $newname === false) {
return false;
}
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.3
$packet = Strings::packSSH2('ss', $oldname, $newname);
if (!$this->send_sftp_packet(NET_SFTP_RENAME, $packet)) {
return false;
}
$response = $this->get_sftp_packet();
if ($this->packet_type != NET_SFTP_STATUS) {
throw new \UnexpectedValueException('Expected NET_SFTP_STATUS. '
. 'Got packet type: ' . $this->packet_type);
}
// if $status isn't SSH_FX_OK it's probably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED
list($status) = Strings::unpackSSH2('N', $response);
if ($status != NET_SFTP_STATUS_OK) {
$this->logError($response, $status);
return false;
}
// don't move the stat cache entry over since this operation could very well change the
// atime and mtime attributes
//$this->update_stat_cache($newname, $this->query_stat_cache($oldname));
$this->remove_from_stat_cache($oldname);
$this->remove_from_stat_cache($newname);
return true;
}
/**
* Parse Attributes
*
* See '7. File Attributes' of draft-ietf-secsh-filexfer-13 for more info.
*
* @param string $response
* @return array
* @access private
*/
private function parseAttributes(&$response)
{
$attr = [];
list($flags) = Strings::unpackSSH2('N', $response);
// SFTPv4+ have a type field (a byte) that follows the above flag field
foreach ($this->attributes as $key => $value) {
switch ($flags & $key) {
case NET_SFTP_ATTR_SIZE: // 0x00000001
// The size attribute is defined as an unsigned 64-bit integer.
// The following will use floats on 32-bit platforms, if necessary.
// As can be seen in the BigInteger class, floats are generally
// IEEE 754 binary64 "double precision" on such platforms and
// as such can represent integers of at least 2^50 without loss
// of precision. Interpreted in filesize, 2^50 bytes = 1024 TiB.
list($upper, $size) = Strings::unpackSSH2('NN', $response);
$attr['size'] = $upper ? 4294967296 * $upper : 0;
$attr['size']+= $size < 0 ? ($size & 0x7FFFFFFF) + 0x80000000 : $size;
break;
case NET_SFTP_ATTR_UIDGID: // 0x00000002 (SFTPv3 only)
list($attr['uid'], $attr['gid']) = Strings::unpackSSH2('NN', $response);
break;
case NET_SFTP_ATTR_PERMISSIONS: // 0x00000004
list($attr['permissions']) = Strings::unpackSSH2('N', $response);
// mode == permissions; permissions was the original array key and is retained for bc purposes.
// mode was added because that's the more industry standard terminology
$attr+= ['mode' => $attr['permissions']];
$fileType = $this->parseMode($attr['permissions']);
if ($fileType !== false) {
$attr+= ['type' => $fileType];
}
break;
case NET_SFTP_ATTR_ACCESSTIME: // 0x00000008
list($attr['atime'], $attr['mtime']) = Strings::unpackSSH2('NN', $response);
break;
case NET_SFTP_ATTR_EXTENDED: // 0x80000000
list($count) = Strings::unpackSSH2('N', $response);
for ($i = 0; $i < $count; $i++) {
list($key, $value) = Strings::unpackSSH2('ss', $response);
$attr[$key] = $value;
}
}
}
return $attr;
}
/**
* Attempt to identify the file type
*
* Quoting the SFTP RFC, "Implementations MUST NOT send bits that are not defined" but they seem to anyway
*
* @param int $mode
* @return int
* @access private
*/
private function parseMode($mode)
{
// values come from http://lxr.free-electrons.com/source/include/uapi/linux/stat.h#L12
// see, also, http://linux.die.net/man/2/stat
switch ($mode & 0170000) {// ie. 1111 0000 0000 0000
case 0000000: // no file type specified - figure out the file type using alternative means
return false;
case 0040000:
return NET_SFTP_TYPE_DIRECTORY;
case 0100000:
return NET_SFTP_TYPE_REGULAR;
case 0120000:
return NET_SFTP_TYPE_SYMLINK;
// new types introduced in SFTPv5+
// http://tools.ietf.org/html/draft-ietf-secsh-filexfer-05#section-5.2
case 0010000: // named pipe (fifo)
return NET_SFTP_TYPE_FIFO;
case 0020000: // character special
return NET_SFTP_TYPE_CHAR_DEVICE;
case 0060000: // block special
return NET_SFTP_TYPE_BLOCK_DEVICE;
case 0140000: // socket
return NET_SFTP_TYPE_SOCKET;
case 0160000: // whiteout
// "SPECIAL should be used for files that are of
// a known type which cannot be expressed in the protocol"
return NET_SFTP_TYPE_SPECIAL;
default:
return NET_SFTP_TYPE_UNKNOWN;
}
}
/**
* Parse Longname
*
* SFTPv3 doesn't provide any easy way of identifying a file type. You could try to open
* a file as a directory and see if an error is returned or you could try to parse the
* SFTPv3-specific longname field of the SSH_FXP_NAME packet. That's what this function does.
* The result is returned using the
* {@link http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-5.2 SFTPv4 type constants}.
*
* If the longname is in an unrecognized format bool(false) is returned.
*
* @param string $longname
* @return mixed
* @access private
*/
private function parseLongname($longname)
{
// http://en.wikipedia.org/wiki/Unix_file_types
// http://en.wikipedia.org/wiki/Filesystem_permissions#Notation_of_traditional_Unix_permissions
if (preg_match('#^[^/]([r-][w-][xstST-]){3}#', $longname)) {
switch ($longname[0]) {
case '-':
return NET_SFTP_TYPE_REGULAR;
case 'd':
return NET_SFTP_TYPE_DIRECTORY;
case 'l':
return NET_SFTP_TYPE_SYMLINK;
default:
return NET_SFTP_TYPE_SPECIAL;
}
}
return false;
}
/**
* Sends SFTP Packets
*
* See '6. General Packet Format' of draft-ietf-secsh-filexfer-13 for more info.
*
* @param int $type
* @param string $data
* @see self::_get_sftp_packet()
* @see self::send_channel_packet()
* @return bool
* @access private
*/
private function send_sftp_packet($type, $data, $request_id = 1)
{
$packet = $this->use_request_id ?
pack('NCNa*', strlen($data) + 5, $type, $request_id, $data) :
pack('NCa*', strlen($data) + 1, $type, $data);
$start = microtime(true);
$result = $this->send_channel_packet(self::CHANNEL, $packet);
$stop = microtime(true);
if (defined('NET_SFTP_LOGGING')) {
$packet_type = '-> ' . $this->packet_types[$type] .
' (' . round($stop - $start, 4) . 's)';
if (NET_SFTP_LOGGING == self::LOG_REALTIME) {
echo "<pre>\r\n" . $this->format_log([$data], [$packet_type]) . "\r\n</pre>\r\n";
flush();
ob_flush();
} else {
$this->packet_type_log[] = $packet_type;
if (NET_SFTP_LOGGING == self::LOG_COMPLEX) {
$this->packet_log[] = $data;
}
}
}
return $result;
}
/**
* Resets a connection for re-use
*
* @param int $reason
* @access private
*/
protected function reset_connection($reason)
{
parent::reset_connection($reason);
$this->use_request_id = false;
$this->pwd = false;
$this->requestBuffer = [];
}
/**
* Receives SFTP Packets
*
* See '6. General Packet Format' of draft-ietf-secsh-filexfer-13 for more info.
*
* Incidentally, the number of SSH_MSG_CHANNEL_DATA messages has no bearing on the number of SFTP packets present.
* There can be one SSH_MSG_CHANNEL_DATA messages containing two SFTP packets or there can be two SSH_MSG_CHANNEL_DATA
* messages containing one SFTP packet.
*
* @see self::_send_sftp_packet()
* @return string
* @access private
*/
private function get_sftp_packet($request_id = null)
{
if (isset($request_id) && isset($this->requestBuffer[$request_id])) {
$this->packet_type = $this->requestBuffer[$request_id]['packet_type'];
$temp = $this->requestBuffer[$request_id]['packet'];
unset($this->requestBuffer[$request_id]);
return $temp;
}
// in SSH2.php the timeout is cumulative per function call. eg. exec() will
// timeout after 10s. but for SFTP.php it's cumulative per packet
$this->curTimeout = $this->timeout;
$start = microtime(true);
// SFTP packet length
while (strlen($this->packet_buffer) < 4) {
$temp = $this->get_channel_packet(self::CHANNEL, true);
if (is_bool($temp)) {
$this->packet_type = false;
$this->packet_buffer = '';
return false;
}
$this->packet_buffer.= $temp;
}
if (strlen($this->packet_buffer) < 4) {
return false;
}
extract(unpack('Nlength', Strings::shift($this->packet_buffer, 4)));
/** @var integer $length */
$tempLength = $length;
$tempLength-= strlen($this->packet_buffer);
// 256 * 1024 is what SFTP_MAX_MSG_LENGTH is set to in OpenSSH's sftp-common.h
if ($tempLength > 256 * 1024) {
throw new \RuntimeException('Invalid Size');
}
// SFTP packet type and data payload
while ($tempLength > 0) {
$temp = $this->get_channel_packet(self::CHANNEL, true);
if (is_bool($temp)) {
$this->packet_type = false;
$this->packet_buffer = '';
return false;
}
$this->packet_buffer.= $temp;
$tempLength-= strlen($temp);
}
$stop = microtime(true);
$this->packet_type = ord(Strings::shift($this->packet_buffer));
if ($this->use_request_id) {
extract(unpack('Npacket_id', Strings::shift($this->packet_buffer, 4))); // remove the request id
$length-= 5; // account for the request id and the packet type
} else {
$length-= 1; // account for the packet type
}
$packet = Strings::shift($this->packet_buffer, $length);
if (defined('NET_SFTP_LOGGING')) {
$packet_type = '<- ' . $this->packet_types[$this->packet_type] .
' (' . round($stop - $start, 4) . 's)';
if (NET_SFTP_LOGGING == self::LOG_REALTIME) {
echo "<pre>\r\n" . $this->format_log([$packet], [$packet_type]) . "\r\n</pre>\r\n";
flush();
ob_flush();
} else {
$this->packet_type_log[] = $packet_type;
if (NET_SFTP_LOGGING == self::LOG_COMPLEX) {
$this->packet_log[] = $packet;
}
}
}
if (isset($request_id) && $this->use_request_id && $packet_id != $request_id) {
$this->requestBuffer[$packet_id] = array(
'packet_type' => $this->packet_type,
'packet' => $packet
);
return $this->_get_sftp_packet($request_id);
}
return $packet;
}
/**
* Returns a log of the packets that have been sent and received.
*
* Returns a string if NET_SFTP_LOGGING == self::LOG_COMPLEX, an array if NET_SFTP_LOGGING == self::LOG_SIMPLE and false if !defined('NET_SFTP_LOGGING')
*
* @access public
* @return array|string
*/
public function getSFTPLog()
{
if (!defined('NET_SFTP_LOGGING')) {
return false;
}
switch (NET_SFTP_LOGGING) {
case self::LOG_COMPLEX:
return $this->format_log($this->packet_log, $this->packet_type_log);
break;
//case self::LOG_SIMPLE:
default:
return $this->packet_type_log;
}
}
/**
* Returns all errors
*
* @return array
* @access public
*/
public function getSFTPErrors()
{
return $this->sftp_errors;
}
/**
* Returns the last error
*
* @return string
* @access public
*/
public function getLastSFTPError()
{
return count($this->sftp_errors) ? $this->sftp_errors[count($this->sftp_errors) - 1] : '';
}
/**
* Get supported SFTP versions
*
* @return array
* @access public
*/
public function getSupportedVersions()
{
$temp = ['version' => $this->version];
if (isset($this->extensions['versions'])) {
$temp['extensions'] = $this->extensions['versions'];
}
return $temp;
}
/**
* Disconnect
*
* @param int $reason
* @return bool
* @access protected
*/
protected function disconnect_helper($reason)
{
$this->pwd = false;
parent::disconnect_helper($reason);
}
}
| qrux/phputils | inc/phpseclib/Net/SFTP.php | PHP | mit | 99,629 |
/*
--------------------------------------------------------------------------------
Based on class found at: http://ai.stanford.edu/~gal/Code/FindMotifs/
--------------------------------------------------------------------------------
*/
#include "Platform/StableHeaders.h"
#include "Util/Helper/ConfigFile.h"
//------------------------------------------------------------------------------
namespace Dangine {
//------------------------------------------------------------------------------
Config::Config(String filename, String delimiter, String comment, String sentry)
: myDelimiter(delimiter)
, myComment(comment)
, mySentry(sentry)
{
// Construct a Config, getting keys and values from given file
std::ifstream in(filename.c_str());
if (!in) throw file_not_found(filename);
in >> (*this);
}
//------------------------------------------------------------------------------
Config::Config()
: myDelimiter(String(1,'='))
, myComment(String(1,'#'))
{
// Construct a Config without a file; empty
}
//------------------------------------------------------------------------------
void Config::remove(const String& key)
{
// Remove key and its value
myContents.erase(myContents.find(key));
return;
}
//------------------------------------------------------------------------------
bool Config::keyExists(const String& key) const
{
// Indicate whether key is found
mapci p = myContents.find(key);
return (p != myContents.end());
}
//------------------------------------------------------------------------------
/* static */
void Config::trim(String& s)
{
// Remove leading and trailing whitespace
static const char whitespace[] = " \n\t\v\r\f";
s.erase(0, s.find_first_not_of(whitespace));
s.erase(s.find_last_not_of(whitespace) + 1U);
}
//------------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, const Config& cf)
{
// Save a Config to os
for (Config::mapci p = cf.myContents.begin();
p != cf.myContents.end();
++p)
{
os << p->first << " " << cf.myDelimiter << " ";
os << p->second << std::endl;
}
return os;
}
//------------------------------------------------------------------------------
std::istream& operator>>(std::istream& is, Config& cf)
{
// Load a Config from is
// Read in keys and values, keeping internal whitespace
typedef String::size_type pos;
const String& delim = cf.myDelimiter; // separator
const String& comm = cf.myComment; // comment
const String& sentry = cf.mySentry; // end of file sentry
const pos skip = delim.length(); // length of separator
String nextline = ""; // might need to read ahead to see where value ends
while (is || nextline.length() > 0)
{
// Read an entire line at a time
String line;
if (nextline.length() > 0)
{
line = nextline; // we read ahead; use it now
nextline = "";
}
else
{
std::getline(is, line);
}
// Ignore comments
line = line.substr(0, line.find(comm));
// Check for end of file sentry
if (sentry != "" && line.find(sentry) != String::npos) return is;
// Parse the line if it contains a delimiter
pos delimPos = line.find(delim);
if (delimPos < String::npos)
{
// Extract the key
String key = line.substr(0, delimPos);
line.replace(0, delimPos+skip, "");
// See if value continues on the next line
// Stop at blank line, next line with a key, end of stream,
// or end of file sentry
bool terminate = false;
while(!terminate && is)
{
std::getline(is, nextline);
terminate = true;
String nlcopy = nextline;
Config::trim(nlcopy);
if (nlcopy == "") continue;
nextline = nextline.substr(0, nextline.find(comm));
if (nextline.find(delim) != String::npos)
continue;
if (sentry != "" && nextline.find(sentry) != String::npos)
continue;
nlcopy = nextline;
Config::trim(nlcopy);
if (nlcopy != "") line += "\n";
line += nextline;
terminate = false;
}
// Store key and value
Config::trim(key);
Config::trim(line);
cf.myContents[key] = line; // overwrites if key is repeated
}
}
return is;
}
//------------------------------------------------------------------------------
} // namespace Dangine
//------------------------------------------------------------------------------ | danielsefton/Dangine | Engine/Util/Helper/src/ConfigFile.cpp | C++ | mit | 4,492 |
# frozen_string_literal: true
module Webdrone
class MethodLogger < Module
class << self
attr_accessor :last_time, :screenshot
end
def initialize(methods = nil)
super()
@methods = methods
end
if Gem::Version.new(RUBY_VERSION) < Gem::Version.new('2.7')
def included(base)
@methods ||= base.instance_methods(false)
method_list = @methods
base.class_eval do
method_list.each do |method_name|
original_method = instance_method(method_name)
define_method method_name do |*args, &block|
caller_location = Kernel.caller_locations[0]
cl_path = caller_location.path
cl_line = caller_location.lineno
if @a0.conf.logger && Gem.path.none? { |path| cl_path.include? path }
ini = ::Webdrone::MethodLogger.last_time ||= Time.new
::Webdrone::MethodLogger.screenshot = nil
args_log = [args].compact.reject(&:empty?).map(&:to_s).join(' ')
begin
result = original_method.bind(self).call(*args, &block)
fin = ::Webdrone::MethodLogger.last_time = Time.new
@a0.logs.trace(ini, fin, cl_path, cl_line, base, method_name, args_log, result, nil, ::Webdrone::MethodLogger.screenshot)
result
rescue StandardError => exception
fin = ::Webdrone::MethodLogger.last_time = Time.new
@a0.logs.trace(ini, fin, cl_path, cl_line, base, method_name, args_log, nil, exception, ::Webdrone::MethodLogger.screenshot)
raise exception
end
else
original_method.bind(self).call(*args, &block)
end
end
end
end
end
else
def included(base)
@methods ||= base.instance_methods(false)
method_list = @methods
base.class_eval do
method_list.each do |method_name|
original_method = instance_method(method_name)
define_method method_name do |*args, **kwargs, &block|
caller_location = Kernel.caller_locations[0]
cl_path = caller_location.path
cl_line = caller_location.lineno
if @a0.conf.logger && Gem.path.none? { |path| cl_path.include? path }
ini = ::Webdrone::MethodLogger.last_time ||= Time.new
::Webdrone::MethodLogger.screenshot = nil
args_log = [args, kwargs].compact.reject(&:empty?).map(&:to_s).join(' ')
begin
result = original_method.bind(self).call(*args, **kwargs, &block)
fin = ::Webdrone::MethodLogger.last_time = Time.new
@a0.logs.trace(ini, fin, cl_path, cl_line, base, method_name, args_log, result, nil, ::Webdrone::MethodLogger.screenshot)
result
rescue StandardError => exception
fin = ::Webdrone::MethodLogger.last_time = Time.new
@a0.logs.trace(ini, fin, cl_path, cl_line, base, method_name, args_log, nil, exception, ::Webdrone::MethodLogger.screenshot)
raise exception
end
else
original_method.bind(self).call(*args, **kwargs, &block)
end
end
end
end
end
end
end
class Browser
def logs
@logs ||= Logs.new self
end
end
class Logs
attr_reader :a0
def initialize(a0)
@a0 = a0
@group_trace_count = []
setup_format
setup_trace
end
def trace(ini, fin, from, lineno, base, method_name, args, result, exception, screenshot)
exception = "#{exception.class}: #{exception}" if exception
printf @format, (fin - ini), base, method_name, args, (result || exception) unless a0.conf.logger.to_s == 'quiet'
CSV.open(@path, "a+") do |csv|
csv << [ini.strftime('%Y-%m-%d %H:%M:%S.%L %z'), (fin - ini), from, lineno, base, method_name, args, result, exception, screenshot]
end
@group_trace_count = @group_trace_count.map { |x| x + 1 }
end
def with_group(name, abort_error: false)
ini = Time.new
caller_location = Kernel.caller_locations[0]
cl_path = caller_location.path
cl_line = caller_location.lineno
result = {}
@group_trace_count << 0
exception = nil
begin
yield
rescue StandardError => e
exception = e
bindings = Kernel.binding.callers
bindings[0..].each do |binding|
location = { path: binding.source_location[0], lineno: binding.source_location[1] }
next unless Gem.path.none? { |path| location[:path].include? path }
result[:exception] = {}
result[:exception][:line] = location[:lineno]
result[:exception][:path] = location[:path]
break
end
end
result[:trace_count] = @group_trace_count.pop
fin = Time.new
trace(ini, fin, cl_path, cl_line, Logs, :with_group, [name, { abort_error: abort_error }], result, exception, nil)
puts "abort_error: #{abort_error} exception: #{exception}"
exit if abort_error == true && exception
end
def setup_format
begin
cols, _line = HighLine.default_instance.terminal.terminal_size
rescue StandardError => error
puts "ignoring error: #{error}"
end
cols ||= 120
total = 6 + 15 + 11 + 5
w = cols - total
w /= 2
w1 = w
w2 = cols - total - w1
w1 = 20 if w1 < 20
w2 = 20 if w2 < 20
@format = "%5.3f %14.14s %10s %#{w1}.#{w1}s => %#{w2}.#{w2}s\n"
end
def setup_trace
@path = File.join(a0.conf.outdir, 'a0_webdrone_trace.csv')
CSV.open(@path, "a+") do |csv|
os = "Windows" if OS.windows?
os = "Linux" if OS.linux?
os = "OS X" if OS.osx?
bits = OS.bits
hostname = Socket.gethostname
browser_name = a0.driver.capabilities[:browser_name]
browser_version = a0.driver.capabilities[:version]
browser_platform = a0.driver.capabilities[:platform]
webdrone_version = Webdrone::VERSION
webdrone_platform = "#{RUBY_ENGINE}-#{RUBY_VERSION} #{RUBY_PLATFORM}"
csv << %w.OS ARCH HOSTNAME BROWSER\ NAME BROWSER\ VERSION BROWSER\ PLATFORM WEBDRONE\ VERSION WEBDRONE\ PLATFORM.
csv << [os, bits, hostname, browser_name, browser_version, browser_platform, webdrone_version, webdrone_platform]
end
CSV.open(@path, "a+") do |csv|
csv << %w.DATE DUR FROM LINENO MODULE CALL PARAMS RESULT EXCEPTION SCREENSHOT.
end
end
end
class Clic
include MethodLogger.new %i[id css link button on option xpath]
end
class Conf
include MethodLogger.new %i[timeout= outdir= error= developer= logger=]
end
class Ctxt
include MethodLogger.new %i[create_tab close_tab with_frame reset with_alert ignore_alert with_conf]
end
class Find
include MethodLogger.new %i[id css link button on option xpath]
end
class Form
include MethodLogger.new %i[with_xpath save set get clic mark submit xlsx]
end
class Html
include MethodLogger.new %i[id css link button on option xpath]
end
class Mark
include MethodLogger.new %i[id css link button on option xpath]
end
class Open
include MethodLogger.new %i[url reload]
end
class Shot
include MethodLogger.new %i[screen]
end
class Text
include MethodLogger.new %i[id css link button on option xpath]
end
class Vrfy
include MethodLogger.new %i[id css link button on option xpath]
end
class Wait
include MethodLogger.new %i[for time]
end
class Xlsx
include MethodLogger.new %i[dict rows both save reset]
end
end
| a0/a0-webdrone-ruby | lib/webdrone/logg.rb | Ruby | mit | 7,845 |
.pad {
padding:30px 30px 30px 30px !important;
}
.button-gm {
min-height: 30px;
line-height: 30px;
font-size: 14px
}
.button-me {
border-color: transparent;
background-color: #00c0f5;
color: #FFF;
position: relative;
display: inline-block;
margin: 10px 0;
padding: 0 12px;
min-width: 52px;
min-height: 32px;
border-width: 1px;
border-style: solid;
border-radius: 4px;
vertical-align: top;
text-align: center;
text-overflow: ellipsis;
font-size: 16px;
line-height: 30px;
cursor: pointer;
}
.footer {
color: #444;
position: absolute;
bottom: 0;
right: 0;
left: 0;
width: 100%;
height: 100px;
}
.weui_uploader_input_wrp {
float: left;
position: relative;
margin-right: 9px;
margin-bottom: 9px;
width: 77px;
height: 77px;
border: 1px solid #D9D9D9;
}
.weui_uploader_input_wrp:before,
.weui_uploader_input_wrp:after {
content: " ";
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
background-color: #D9D9D9;
}
.weui_uploader_input_wrp:before {
width: 2px;
height: 39.5px;
}
.weui_uploader_input_wrp:after {
width: 39.5px;
height: 2px;
}
.weui_uploader_input_wrp:active {
border-color: #999999;
}
.weui_uploader_input_wrp:active:before,
.weui_uploader_input_wrp:active:after {
background-color: #999999;
}
.center-in-center{
position: absolute;
top: 40%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
} | gitminingOrg/AirDevice | reception/src/main/webapp/www/css/share.css | CSS | mit | 1,816 |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#if XR_MANAGEMENT_ENABLED
using UnityEngine.XR.Management;
#endif // XR_MANAGEMENT_ENABLED
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// Utilities that abstract XR settings functionality so that the MRTK need not know which
/// implementation is being used.
/// </summary>
public static class XRSettingsUtilities
{
#if !UNITY_2020_2_OR_NEWER && UNITY_2019_3_OR_NEWER && XR_MANAGEMENT_ENABLED
private static bool? isXRSDKEnabled = null;
#endif // !UNITY_2020_2_OR_NEWER && UNITY_2019_3_OR_NEWER && XR_MANAGEMENT_ENABLED
/// <summary>
/// Checks if an XR SDK plug-in is installed that disables legacy VR. Returns false if so.
/// </summary>
public static bool XRSDKEnabled
{
get
{
#if UNITY_2020_2_OR_NEWER
return true;
#elif UNITY_2019_3_OR_NEWER && XR_MANAGEMENT_ENABLED
if (!isXRSDKEnabled.HasValue)
{
XRGeneralSettings currentSettings = XRGeneralSettings.Instance;
if (currentSettings != null && currentSettings.AssignedSettings != null)
{
#pragma warning disable CS0618 // Suppressing the warning to support xr management plugin 3.x and 4.x
isXRSDKEnabled = currentSettings.AssignedSettings.loaders.Count > 0;
#pragma warning restore CS0618
}
else
{
isXRSDKEnabled = false;
}
}
return isXRSDKEnabled.Value;
#else
return false;
#endif // UNITY_2020_2_OR_NEWER
}
}
}
}
| DDReaper/MixedRealityToolkit-Unity | Assets/MRTK/Core/Utilities/XRSettingsUtilities.cs | C# | mit | 1,780 |
const Koa = require('koa');
const http = require('http');
const destroyable = require('server-destroy');
const bodyParser = require('koa-bodyparser');
const session = require('koa-session');
const passport = require('koa-passport');
const serve = require('koa-static');
const db = require('./db');
const config = require('./config');
const router = require('./routes');
const authStrategies = require('./authStrategies');
const User = require('./models/User');
const app = new Koa();
app.use(bodyParser());
app.keys = [config.get('session_secret')];
app.use(session({}, app));
authStrategies.forEach(passport.use, passport);
passport.serializeUser((user, done) => {
done(null, user.twitterId);
});
passport.deserializeUser(async (twitterId, done) => {
const user = await User.findOne({ twitterId });
done(null, user);
});
app.use(passport.initialize());
app.use(passport.session());
app.use(router.routes());
app.use(router.allowedMethods());
app.use(serve('public'));
app.use(async (ctx, next) => {
await next();
if (ctx.status === 404) {
ctx.redirect('/');
}
});
const server = http.createServer(app.callback());
module.exports = {
start() {
db.start().then(() => {
server.listen(config.get('port'));
destroyable(server);
});
},
stop() {
server.destroy();
db.stop();
},
};
| xz64/image-sharing | server.js | JavaScript | mit | 1,341 |
<?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new AppBundle\AppBundle(),
// Add your dependencies
new Sonata\CoreBundle\SonataCoreBundle(),
new Sonata\BlockBundle\SonataBlockBundle(),
new Knp\Bundle\MenuBundle\KnpMenuBundle(),
//...
// If you haven't already, add the storage bundle
// This example uses SonataDoctrineORMAdmin but
// it works the same with the alternatives
new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),
// Then add SonataAdminBundle
new Sonata\AdminBundle\SonataAdminBundle(),
// ...
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
| justinecavaglieri/EasySymfony | app/AppKernel.php | PHP | mit | 1,993 |
<?php
namespace app\base;
use Yii;
use yii\base\Component;
class MailService extends Component {
public function init()
{
parent::init();
if ($this->_mail === null) {
$this->_mail = Yii::$app->getMailer();
//$this->_mail->htmlLayout = Yii::getAlias($this->id . '/mails/layouts/html');
//$this->_mail->textLayout = Yii::getAlias($this->id . '/mails/layouts/text');
$this->_mail->viewPath = '@app/modules/' . $module->id . '/mails/views';
if (isset(Yii::$app->params['robotEmail']) && Yii::$app->params['robotEmail'] !== null) {
$this->_mail->messageConfig['from'] = !isset(Yii::$app->params['robotName']) ? Yii::$app->params['robotEmail'] : [Yii::$app->params['robotEmail'] => Yii::$app->params['robotName']];
}
}
return $this->_mail;
}
}
| artkost/yii2-starter-kit | app/base/MailService.php | PHP | mit | 876 |
<link rel="import" href="../../polymer/polymer-element.html">
<link rel="import" href="../overlay-mixin.html">
<dom-module id="sample-overlay">
<template>
<style>
:host {
background: #ddd;
display: block;
height: 200px;
position: absolute;
width: 200px;
}
:host(:focus) {
border: 2px solid dodgerblue;
}
</style>
Hello!!!
</template>
<script>
class SampleOverlay extends OverlayMixin(Polymer.Element) {
static get is() {return 'sample-overlay';}
}
customElements.define(SampleOverlay.is, SampleOverlay);
</script>
</dom-module> | sharedlabs/overlay-container | demo/sample-overlay.html | HTML | mit | 648 |
using System;
using Xamarin.Forms;
namespace EmployeeApp
{
public partial class ClaimDetailPage : ContentPage
{
private ClaimViewModel model;
public ClaimDetailPage(ClaimViewModel cl)
{
InitializeComponent();
model = cl;
BindingContext = model;
ToolbarItem optionbutton = new ToolbarItem
{
Text = "Options",
Order = ToolbarItemOrder.Default,
Priority = 0
};
ToolbarItems.Add(optionbutton);
optionbutton.Clicked += OptionsClicked;
if (model.ImageUrl.StartsWith("http:") || model.ImageUrl.StartsWith("https:"))
{
claimCellImage.Source = new UriImageSource { CachingEnabled = false, Uri = new Uri(model.ImageUrl) };
}
claimHintStackLayout.SetBinding(IsVisibleProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminShowDetailHintConvert(), Mode = BindingMode.OneWay });
claimHintIcon.SetBinding(Image.IsVisibleProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminShowDetailHintIconConvert(), Mode = BindingMode.OneWay });
claimHintTitle.SetBinding(Label.TextProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminDetailHintTitleConvert(), Mode = BindingMode.OneWay });
claimHintMessage.SetBinding(Label.TextProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminDetailHintMessageConvert(), Mode = BindingMode.OneWay });
claimHintFrame.SetBinding(Frame.BackgroundColorProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminDetailHintBkConvert(), Mode = BindingMode.OneWay });
claimHintMessage.SetBinding(Label.TextColorProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminDetailHintMsgColorConvert(), Mode = BindingMode.OneWay });
InitGridView();
this.Title = "#" + cl.Name;
}
private void InitGridView()
{
if (mainPageGrid.RowDefinitions.Count == 0)
{
claimDetailStackLayout.Padding = new Thickness(0, Display.Convert(40));
claimHintStackLayout.HeightRequest = Display.Convert(110);
Display.SetGridRowsHeight(claimHintGrid, new string[] { "32", "36" });
claimHintIcon.WidthRequest = Display.Convert(32);
claimHintIcon.HeightRequest = Display.Convert(32);
Display.SetGridRowsHeight(mainPageGrid, new string[] { "50", "46", "20", "54", "176", "30", "40", "54", "36", "44", "440", "1*"});
claimDescription.Margin = new Thickness(0, Display.Convert(14));
}
}
public async void OptionsClicked(object sender, EventArgs e)
{
var action = await DisplayActionSheet(null, "Cancel", null, "Approve", "Contact policy holder", "Decline");
switch (action)
{
case "Approve":
model.Status = ClaimStatus.Approved;
model.isNew = false;
break;
case "Decline":
model.Status = ClaimStatus.Declined;
model.isNew = false;
break;
}
}
}
}
| TBag/canviz | Mobile/EmployeeApp/EmployeeApp/EmployeeApp/Views/ClaimDetailPage.xaml.cs | C# | mit | 3,471 |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
<link rel="stylesheet" href="../css/weui.css"/>
<link rel="stylesheet" href="../css/weuix.css"/>
<script src="../js/zepto.min.js"></script>
<script src="../js/zepto.weui.js"></script>
<script src="../js/clipboard.min.js"></script>
</head>
<body ontouchstart>
<div class="page-hd">
<h1 class="page-hd-title">
字体大小/颜色/背景/标题
</h1>
<p class="page-hd-desc"></p>
</div>
<h1>字体大小与颜色</h1>
<h2>字体大小与颜色</h2>
<h3>字体大小与颜色</h3>
<h4>字体大小与颜色</h4>
<h5>字体大小与颜色</h5>
<h6>字体大小与颜色</h6>
<br>
字体f11-55
<span class='f11'>字体f11</span><span class='f12'>字体f12</span><span class='f13'>字体f13</span><span class='f114'>字体f14</span><span class='f15'>字体15</span><span class='f116'>字体f16</span><span class='f31'>字体f31</span><span class='f32'>字体f32</span><span class='f35'>字体f35</span><span class='f40'>字体f40</span><span class='f45'>字体f45</span><span class='f50'>字体f50</span><span class='f55'>字体f55</span>
<br>
<span class='f-red'>红色f-red</span><span class='f-green'>绿色f-green</span>
<span class='f-blue'>蓝色f-blue</span><span class='f-black'>f-black</span>
<span class='f-white bg-blue'>f-white</span> <span class='f-zi'>f-zi</span> <span class='f-gray'>灰色f-gray</span> <span class='f-yellow'>黄色</span><span class='f-orange'>f-orange</span><span class='f-white bg-blue'>背景蓝色bg-blue</span>
<br>
<span class='bg-orange f-white'>bg-orange</span>
<span class='weui-btn_primary f-white'>背景绿色weui-btn_primary</span>
<span class='weui-btn_warn f-white'>weui-btn_warn</span>
<span class='weui-btn_default f-red'>weui-btn_default</span>
<div class="weui-cells__title">9种常见颜色值</div>
<div class="weui-cells weui-cells_form">
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#FA5151">红色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#FA5151" style="background:#FA5151;color:white"/>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#07C160">绿色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#07C160" style="background:#07C160;color:white"/>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#10AEFF">蓝色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#10AEFF" style="background:#10AEFF;color:white"/>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#333">黑色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#333" style="background:#333;color:white"/>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#FF33CC">紫色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#FF33CC" style="background:#FF33CC;color:white"/>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#CCC">灰色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#CCC" style="background:#CCC;color:white"/>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#FFFF66">黄色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#FFFF66" style="background:#FFFF66;color:white"/>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#FF6600">橙色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#FF6600" style="background:#FF6600;color:white"/>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd"><a href="javascript:void(0);" class="jsclip" data-url="#FFF">白色</a></div>
<div class="weui-cell__bd">
<input class="weui-input" type="text" value="#FFF" style="background:#FFF;color:white"/>
</div>
</div>
</div>
</div>
<script>
var clipboard = new Clipboard('.jsclip', {
text: function(e) {
return $(e).data('url')||$(e).data('href');
}
});
clipboard.on('success', function(e) {
$.toast('复制成功');
});
</script>
<br>
<br>
<div class="weui-footer weui-footer_fixed-bottom">
<p class="weui-footer__links">
<a href="../index.html" class="weui-footer__link">WeUI首页</a>
</p>
<p class="weui-footer__text">Copyright © Yoby</p>
</div>
</body>
</html> | logoove/weui2 | demo/base3.html | HTML | mit | 5,385 |
/*
Copyright (C) 2013-2015 MetaMorph Software, Inc
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data 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 Data.
THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
=======================
This version of the META tools is a fork of an original version produced
by Vanderbilt University's Institute for Software Integrated Systems (ISIS).
Their license statement:
Copyright (C) 2011-2014 Vanderbilt University
Developed with the sponsorship of the Defense Advanced Research Projects
Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights
as defined in DFARS 252.227-7013.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data 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 Data.
THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
*/
using System;
using System.Runtime.InteropServices;
using GME.Util;
using GME.MGA;
namespace GME.CSharp
{
abstract class ComponentConfig
{
// Set paradigm name. Provide * if you want to register it for all paradigms.
public const string paradigmName = "CyPhyML";
// Set the human readable name of the interpreter. You can use white space characters.
public const string componentName = "CyPhyPrepareIFab";
// Specify an icon path
public const string iconName = "CyPhyPrepareIFab.ico";
public const string tooltip = "CyPhyPrepareIFab";
// If null, updated with the assembly path + the iconName dynamically on registration
public static string iconPath = null;
// Uncomment the flag if your component is paradigm independent.
public static componenttype_enum componentType = componenttype_enum.COMPONENTTYPE_INTERPRETER;
public const regaccessmode_enum registrationMode = regaccessmode_enum.REGACCESS_SYSTEM;
public const string progID = "MGA.Interpreter.CyPhyPrepareIFab";
public const string guid = "D3B4ECEE-36EC-4753-9B10-312084B48F2A";
}
}
| pombredanne/metamorphosys-desktop | metamorphosys/META/src/CyPhyPrepareIFab/ComponentConfig.cs | C# | mit | 3,987 |
package cellsociety_team05;
public class SimulationException extends Exception {
public SimulationException(String s) {
super(s);
}
}
| dpak96/CellSociety | src/cellsociety_team05/SimulationException.java | Java | mit | 139 |
PhotoAlbums.Router.map(function() {
this.resource('login');
this.resource('album', {path: '/:album_id'});
this.resource('photo', {path: 'photos/:photo_id'});
});
| adamstegman/photo_albums | app/assets/javascripts/router.js | JavaScript | mit | 168 |
from __future__ import annotations
from collections import defaultdict
from collections.abc import Generator, Iterable, Mapping, MutableMapping
from contextlib import contextmanager
import logging
import re
import textwrap
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, NamedTuple
from markdown_it.rules_block.html_block import HTML_SEQUENCES
from mdformat import codepoints
from mdformat._compat import Literal
from mdformat._conf import DEFAULT_OPTS
from mdformat.renderer._util import (
RE_CHAR_REFERENCE,
decimalify_leading,
decimalify_trailing,
escape_asterisk_emphasis,
escape_underscore_emphasis,
get_list_marker_type,
is_tight_list,
is_tight_list_item,
longest_consecutive_sequence,
maybe_add_link_brackets,
)
from mdformat.renderer.typing import Postprocess, Render
if TYPE_CHECKING:
from mdformat.renderer import RenderTreeNode
LOGGER = logging.getLogger(__name__)
# A marker used to point a location where word wrap is allowed
# to occur.
WRAP_POINT = "\x00"
# A marker used to indicate location of a character that should be preserved
# during word wrap. Should be converted to the actual character after wrap.
PRESERVE_CHAR = "\x00"
def make_render_children(separator: str) -> Render:
def render_children(
node: RenderTreeNode,
context: RenderContext,
) -> str:
return separator.join(child.render(context) for child in node.children)
return render_children
def hr(node: RenderTreeNode, context: RenderContext) -> str:
thematic_break_width = 70
return "_" * thematic_break_width
def code_inline(node: RenderTreeNode, context: RenderContext) -> str:
code = node.content
all_chars_are_whitespace = not code.strip()
longest_backtick_seq = longest_consecutive_sequence(code, "`")
if longest_backtick_seq:
separator = "`" * (longest_backtick_seq + 1)
return f"{separator} {code} {separator}"
if code.startswith(" ") and code.endswith(" ") and not all_chars_are_whitespace:
return f"` {code} `"
return f"`{code}`"
def html_block(node: RenderTreeNode, context: RenderContext) -> str:
content = node.content.rstrip("\n")
# Need to strip leading spaces because we do so for regular Markdown too.
# Without the stripping the raw HTML and Markdown get unaligned and
# semantic may change.
content = content.lstrip()
return content
def html_inline(node: RenderTreeNode, context: RenderContext) -> str:
return node.content
def _in_block(block_name: str, node: RenderTreeNode) -> bool:
while node.parent:
if node.parent.type == block_name:
return True
node = node.parent
return False
def hardbreak(node: RenderTreeNode, context: RenderContext) -> str:
if _in_block("heading", node):
return "<br /> "
return "\\" + "\n"
def softbreak(node: RenderTreeNode, context: RenderContext) -> str:
if context.do_wrap and _in_block("paragraph", node):
return WRAP_POINT
return "\n"
def text(node: RenderTreeNode, context: RenderContext) -> str:
"""Process a text token.
Text should always be a child of an inline token. An inline token
should always be enclosed by a heading or a paragraph.
"""
text = node.content
# Escape backslash to prevent it from making unintended escapes.
# This escape has to be first, else we start multiplying backslashes.
text = text.replace("\\", "\\\\")
text = escape_asterisk_emphasis(text) # Escape emphasis/strong marker.
text = escape_underscore_emphasis(text) # Escape emphasis/strong marker.
text = text.replace("[", "\\[") # Escape link label enclosure
text = text.replace("]", "\\]") # Escape link label enclosure
text = text.replace("<", "\\<") # Escape URI enclosure
text = text.replace("`", "\\`") # Escape code span marker
# Escape "&" if it starts a sequence that can be interpreted as
# a character reference.
text = RE_CHAR_REFERENCE.sub(r"\\\g<0>", text)
# The parser can give us consecutive newlines which can break
# the markdown structure. Replace two or more consecutive newlines
# with newline character's decimal reference.
text = text.replace("\n\n", " ")
# If the last character is a "!" and the token next up is a link, we
# have to escape the "!" or else the link will be interpreted as image.
next_sibling = node.next_sibling
if text.endswith("!") and next_sibling and next_sibling.type == "link":
text = text[:-1] + "\\!"
if context.do_wrap and _in_block("paragraph", node):
text = re.sub(r"\s+", WRAP_POINT, text)
return text
def fence(node: RenderTreeNode, context: RenderContext) -> str:
info_str = node.info.strip()
lang = info_str.split(maxsplit=1)[0] if info_str else ""
code_block = node.content
# Info strings of backtick code fences cannot contain backticks.
# If that is the case, we make a tilde code fence instead.
fence_char = "~" if "`" in info_str else "`"
# Format the code block using enabled codeformatter funcs
if lang in context.options.get("codeformatters", {}):
fmt_func = context.options["codeformatters"][lang]
try:
code_block = fmt_func(code_block, info_str)
except Exception:
# Swallow exceptions so that formatter errors (e.g. due to
# invalid code) do not crash mdformat.
assert node.map is not None, "A fence token must have `map` attribute set"
filename = context.options.get("mdformat", {}).get("filename", "")
warn_msg = (
f"Failed formatting content of a {lang} code block "
f"(line {node.map[0] + 1} before formatting)"
)
if filename:
warn_msg += f". Filename: {filename}"
LOGGER.warning(warn_msg)
# The code block must not include as long or longer sequence of `fence_char`s
# as the fence string itself
fence_len = max(3, longest_consecutive_sequence(code_block, fence_char) + 1)
fence_str = fence_char * fence_len
return f"{fence_str}{info_str}\n{code_block}{fence_str}"
def code_block(node: RenderTreeNode, context: RenderContext) -> str:
return fence(node, context)
def image(node: RenderTreeNode, context: RenderContext) -> str:
description = _render_inline_as_text(node, context)
if context.do_wrap:
# Prevent line breaks
description = description.replace(WRAP_POINT, " ")
ref_label = node.meta.get("label")
if ref_label:
context.env["used_refs"].add(ref_label)
ref_label_repr = ref_label.lower()
if description.lower() == ref_label_repr:
return f"![{description}]"
return f"![{description}][{ref_label_repr}]"
uri = node.attrs["src"]
assert isinstance(uri, str)
uri = maybe_add_link_brackets(uri)
title = node.attrs.get("title")
if title is not None:
return f'![{description}]({uri} "{title}")'
return f"![{description}]({uri})"
def _render_inline_as_text(node: RenderTreeNode, context: RenderContext) -> str:
"""Special kludge for image `alt` attributes to conform CommonMark spec.
Don't try to use it! Spec requires to show `alt` content with
stripped markup, instead of simple escaping.
"""
def text_renderer(node: RenderTreeNode, context: RenderContext) -> str:
return node.content
def image_renderer(node: RenderTreeNode, context: RenderContext) -> str:
return _render_inline_as_text(node, context)
inline_renderers: Mapping[str, Render] = defaultdict(
lambda: make_render_children(""),
{
"text": text_renderer,
"image": image_renderer,
"link": link,
"softbreak": softbreak,
},
)
inline_context = RenderContext(
inline_renderers, context.postprocessors, context.options, context.env
)
return make_render_children("")(node, inline_context)
def link(node: RenderTreeNode, context: RenderContext) -> str:
if node.info == "auto":
autolink_url = node.attrs["href"]
assert isinstance(autolink_url, str)
# The parser adds a "mailto:" prefix to autolink email href. We remove the
# prefix if it wasn't there in the source.
if autolink_url.startswith("mailto:") and not node.children[
0
].content.startswith("mailto:"):
autolink_url = autolink_url[7:]
return "<" + autolink_url + ">"
text = "".join(child.render(context) for child in node.children)
if context.do_wrap:
# Prevent line breaks
text = text.replace(WRAP_POINT, " ")
ref_label = node.meta.get("label")
if ref_label:
context.env["used_refs"].add(ref_label)
ref_label_repr = ref_label.lower()
if text.lower() == ref_label_repr:
return f"[{text}]"
return f"[{text}][{ref_label_repr}]"
uri = node.attrs["href"]
assert isinstance(uri, str)
uri = maybe_add_link_brackets(uri)
title = node.attrs.get("title")
if title is None:
return f"[{text}]({uri})"
assert isinstance(title, str)
title = title.replace('"', '\\"')
return f'[{text}]({uri} "{title}")'
def em(node: RenderTreeNode, context: RenderContext) -> str:
text = make_render_children(separator="")(node, context)
indicator = node.markup
return indicator + text + indicator
def strong(node: RenderTreeNode, context: RenderContext) -> str:
text = make_render_children(separator="")(node, context)
indicator = node.markup
return indicator + text + indicator
def heading(node: RenderTreeNode, context: RenderContext) -> str:
text = make_render_children(separator="")(node, context)
if node.markup == "=":
prefix = "# "
elif node.markup == "-":
prefix = "## "
else: # ATX heading
prefix = node.markup + " "
# There can be newlines in setext headers, but we make an ATX
# header always. Convert newlines to spaces.
text = text.replace("\n", " ")
# If the text ends in a sequence of hashes (#), the hashes will be
# interpreted as an optional closing sequence of the heading, and
# will not be rendered. Escape a line ending hash to prevent this.
if text.endswith("#"):
text = text[:-1] + "\\#"
return prefix + text
def blockquote(node: RenderTreeNode, context: RenderContext) -> str:
marker = "> "
with context.indented(len(marker)):
text = make_render_children(separator="\n\n")(node, context)
lines = text.splitlines()
if not lines:
return ">"
quoted_lines = (f"{marker}{line}" if line else ">" for line in lines)
quoted_str = "\n".join(quoted_lines)
return quoted_str
def _wrap(text: str, *, width: int | Literal["no"]) -> str:
"""Wrap text at locations pointed by `WRAP_POINT`s.
Converts `WRAP_POINT`s to either a space or newline character, thus
wrapping the text. Already existing whitespace will be preserved as
is.
"""
text, replacements = _prepare_wrap(text)
if width == "no":
return _recover_preserve_chars(text, replacements)
wrapper = textwrap.TextWrapper(
break_long_words=False,
break_on_hyphens=False,
width=width,
expand_tabs=False,
replace_whitespace=False,
)
wrapped = wrapper.fill(text)
wrapped = _recover_preserve_chars(wrapped, replacements)
return " " + wrapped if text.startswith(" ") else wrapped
def _prepare_wrap(text: str) -> tuple[str, str]:
"""Prepare text for wrap.
Convert `WRAP_POINT`s to spaces. Convert whitespace to
`PRESERVE_CHAR`s. Return a tuple with the prepared string, and
another string consisting of replacement characters for
`PRESERVE_CHAR`s.
"""
result = ""
replacements = ""
for c in text:
if c == WRAP_POINT:
if not result or result[-1] != " ":
result += " "
elif c in codepoints.UNICODE_WHITESPACE:
result += PRESERVE_CHAR
replacements += c
else:
result += c
return result, replacements
def _recover_preserve_chars(text: str, replacements: str) -> str:
replacement_iterator = iter(replacements)
return "".join(
next(replacement_iterator) if c == PRESERVE_CHAR else c for c in text
)
def paragraph(node: RenderTreeNode, context: RenderContext) -> str: # noqa: C901
inline_node = node.children[0]
text = inline_node.render(context)
if context.do_wrap:
wrap_mode = context.options["mdformat"]["wrap"]
if isinstance(wrap_mode, int):
wrap_mode -= context.env["indent_width"]
wrap_mode = max(1, wrap_mode)
text = _wrap(text, width=wrap_mode)
# A paragraph can start or end in whitespace e.g. if the whitespace was
# in decimal representation form. We need to re-decimalify it, one reason being
# to enable "empty" paragraphs with whitespace only.
text = decimalify_leading(codepoints.UNICODE_WHITESPACE, text)
text = decimalify_trailing(codepoints.UNICODE_WHITESPACE, text)
lines = text.split("\n")
for i in range(len(lines)):
# Strip whitespace to prevent issues like a line starting tab that is
# interpreted as start of a code block.
lines[i] = lines[i].strip()
# If a line looks like an ATX heading, escape the first hash.
if re.match(r"#{1,6}( |\t|$)", lines[i]):
lines[i] = f"\\{lines[i]}"
# Make sure a paragraph line does not start with ">"
# (otherwise it will be interpreted as a block quote).
if lines[i].startswith(">"):
lines[i] = f"\\{lines[i]}"
# Make sure a paragraph line does not start with "*", "-" or "+"
# followed by a space, tab, or end of line.
# (otherwise it will be interpreted as list item).
if re.match(r"[-*+]( |\t|$)", lines[i]):
lines[i] = f"\\{lines[i]}"
# If a line starts with a number followed by "." or ")" followed by
# a space, tab or end of line, escape the "." or ")" or it will be
# interpreted as ordered list item.
if re.match(r"[0-9]+\)( |\t|$)", lines[i]):
lines[i] = lines[i].replace(")", "\\)", 1)
if re.match(r"[0-9]+\.( |\t|$)", lines[i]):
lines[i] = lines[i].replace(".", "\\.", 1)
# Consecutive "-", "*" or "_" sequences can be interpreted as thematic
# break. Escape them.
space_removed = lines[i].replace(" ", "").replace("\t", "")
if len(space_removed) >= 3:
if all(c == "*" for c in space_removed):
lines[i] = lines[i].replace("*", "\\*", 1) # pragma: no cover
elif all(c == "-" for c in space_removed):
lines[i] = lines[i].replace("-", "\\-", 1)
elif all(c == "_" for c in space_removed):
lines[i] = lines[i].replace("_", "\\_", 1) # pragma: no cover
# A stripped line where all characters are "=" or "-" will be
# interpreted as a setext heading. Escape.
stripped = lines[i].strip(" \t")
if all(c == "-" for c in stripped):
lines[i] = lines[i].replace("-", "\\-", 1)
elif all(c == "=" for c in stripped):
lines[i] = lines[i].replace("=", "\\=", 1)
# Check if the line could be interpreted as an HTML block.
# If yes, prefix it with 4 spaces to prevent this.
for html_seq_tuple in HTML_SEQUENCES:
can_break_paragraph = html_seq_tuple[2]
opening_re = html_seq_tuple[0]
if can_break_paragraph and opening_re.search(lines[i]):
lines[i] = f" {lines[i]}"
break
text = "\n".join(lines)
return text
def list_item(node: RenderTreeNode, context: RenderContext) -> str:
"""Return one list item as string.
This returns just the content. List item markers and indentation are
added in `bullet_list` and `ordered_list` renderers.
"""
block_separator = "\n" if is_tight_list_item(node) else "\n\n"
text = make_render_children(block_separator)(node, context)
if not text.strip():
return ""
return text
def bullet_list(node: RenderTreeNode, context: RenderContext) -> str:
marker_type = get_list_marker_type(node)
first_line_indent = " "
indent = " " * len(marker_type + first_line_indent)
block_separator = "\n" if is_tight_list(node) else "\n\n"
with context.indented(len(indent)):
text = ""
for child_idx, child in enumerate(node.children):
list_item = child.render(context)
formatted_lines = []
line_iterator = iter(list_item.split("\n"))
first_line = next(line_iterator)
formatted_lines.append(
f"{marker_type}{first_line_indent}{first_line}"
if first_line
else marker_type
)
for line in line_iterator:
formatted_lines.append(f"{indent}{line}" if line else "")
text += "\n".join(formatted_lines)
if child_idx != len(node.children) - 1:
text += block_separator
return text
def ordered_list(node: RenderTreeNode, context: RenderContext) -> str:
consecutive_numbering = context.options.get("mdformat", {}).get(
"number", DEFAULT_OPTS["number"]
)
marker_type = get_list_marker_type(node)
first_line_indent = " "
block_separator = "\n" if is_tight_list(node) else "\n\n"
list_len = len(node.children)
starting_number = node.attrs.get("start")
if starting_number is None:
starting_number = 1
assert isinstance(starting_number, int)
if consecutive_numbering:
indent_width = len(
f"{list_len + starting_number - 1}{marker_type}{first_line_indent}"
)
else:
indent_width = len(f"{starting_number}{marker_type}{first_line_indent}")
text = ""
with context.indented(indent_width):
for list_item_index, list_item in enumerate(node.children):
list_item_text = list_item.render(context)
formatted_lines = []
line_iterator = iter(list_item_text.split("\n"))
first_line = next(line_iterator)
if consecutive_numbering:
# Prefix first line of the list item with consecutive numbering,
# padded with zeros to make all markers of even length.
# E.g.
# 002. This is the first list item
# 003. Second item
# ...
# 112. Last item
number = starting_number + list_item_index
pad = len(str(list_len + starting_number - 1))
number_str = str(number).rjust(pad, "0")
formatted_lines.append(
f"{number_str}{marker_type}{first_line_indent}{first_line}"
if first_line
else f"{number_str}{marker_type}"
)
else:
# Prefix first line of first item with the starting number of the
# list. Prefix following list items with the number one
# prefixed by zeros to make the list item marker of even length
# with the first one.
# E.g.
# 5321. This is the first list item
# 0001. Second item
# 0001. Third item
first_item_marker = f"{starting_number}{marker_type}"
other_item_marker = (
"0" * (len(str(starting_number)) - 1) + "1" + marker_type
)
if list_item_index == 0:
formatted_lines.append(
f"{first_item_marker}{first_line_indent}{first_line}"
if first_line
else first_item_marker
)
else:
formatted_lines.append(
f"{other_item_marker}{first_line_indent}{first_line}"
if first_line
else other_item_marker
)
for line in line_iterator:
formatted_lines.append(" " * indent_width + line if line else "")
text += "\n".join(formatted_lines)
if list_item_index != len(node.children) - 1:
text += block_separator
return text
DEFAULT_RENDERERS: Mapping[str, Render] = MappingProxyType(
{
"inline": make_render_children(""),
"root": make_render_children("\n\n"),
"hr": hr,
"code_inline": code_inline,
"html_block": html_block,
"html_inline": html_inline,
"hardbreak": hardbreak,
"softbreak": softbreak,
"text": text,
"fence": fence,
"code_block": code_block,
"link": link,
"image": image,
"em": em,
"strong": strong,
"heading": heading,
"blockquote": blockquote,
"paragraph": paragraph,
"bullet_list": bullet_list,
"ordered_list": ordered_list,
"list_item": list_item,
}
)
class RenderContext(NamedTuple):
"""A collection of data that is passed as input to `Render` and
`Postprocess` functions."""
renderers: Mapping[str, Render]
postprocessors: Mapping[str, Iterable[Postprocess]]
options: Mapping[str, Any]
env: MutableMapping
@contextmanager
def indented(self, width: int) -> Generator[None, None, None]:
self.env["indent_width"] += width
try:
yield
finally:
self.env["indent_width"] -= width
@property
def do_wrap(self) -> bool:
wrap_mode = self.options.get("mdformat", {}).get("wrap", DEFAULT_OPTS["wrap"])
return isinstance(wrap_mode, int) or wrap_mode == "no"
def with_default_renderer_for(self, *syntax_names: str) -> RenderContext:
renderers = dict(self.renderers)
for syntax in syntax_names:
if syntax in DEFAULT_RENDERERS:
renderers[syntax] = DEFAULT_RENDERERS[syntax]
else:
renderers.pop(syntax, None)
return RenderContext(
MappingProxyType(renderers), self.postprocessors, self.options, self.env
)
| executablebooks/mdformat | src/mdformat/renderer/_context.py | Python | mit | 22,558 |
package com.globalforge.infix;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.globalforge.infix.api.InfixSimpleActions;
import com.google.common.collect.ListMultimap;
/*-
The MIT License (MIT)
Copyright (c) 2019-2020 Global Forge LLC
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.
*/
public class TestAndOrSimple {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
private ListMultimap<String, String> getResults(String sampleRule) throws Exception {
InfixSimpleActions rules = new InfixSimpleActions(sampleRule);
String result = rules.transformFIXMsg(TestAndOrSimple.sampleMessage1);
return StaticTestingUtils.parseMessage(result);
}
@Test
public void t1() {
try {
String sampleRule = "&45==0 && &47==0 ? &50=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("50").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t2() {
try {
String sampleRule = "&45==1 && &47==0 ? &50=1 : &50=2";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("2", resultStore.get("50").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t3() {
try {
String sampleRule = "&45!=1 && &47==0 ? &50=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("50").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t4() {
try {
String sampleRule = "&45==0 && &47 != 1 ? &50=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("50").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t9() {
try {
String sampleRule = "&45==0 && &47==0 && &48==1.5 ? &45=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("0", resultStore.get("47").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t10() {
try {
String sampleRule = "&45==1 && &47==0 && &48==1.5 ? &45=1 : &47=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("1", resultStore.get("47").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t11() {
try {
String sampleRule = "&45==0 && &47==1 && &48==1.5 ? &45=1 : &47=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("1", resultStore.get("47").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t12() {
try {
String sampleRule = "&45==0 && &47==0 && &48==1.6 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("0", resultStore.get("47").get(0));
Assert.assertEquals("1", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t13() {
try {
String sampleRule = "&45==0 || &47==0 && &48==1.6 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("0", resultStore.get("47").get(0));
Assert.assertEquals("1", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t14() {
try {
String sampleRule = "&45==0 && &47==0 || &48==1.6 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("0", resultStore.get("47").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t15() {
try {
String sampleRule = "&45==0 || &47==0 && &48==1.6 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("0", resultStore.get("47").get(0));
Assert.assertEquals("1", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t16() {
try {
String sampleRule = "(&45==0 || &47==0) && (&48==1.6) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("0", resultStore.get("47").get(0));
Assert.assertEquals("1", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t17() {
try {
String sampleRule = "&45==0 || (&47==0 && &48==1.6) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("0", resultStore.get("47").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t18() {
try {
String sampleRule = "^&45 && ^&47 && ^&48 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t19() {
try {
String sampleRule = "^&45 && ^&47 && ^&50 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("1", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t20() {
try {
String sampleRule = "^&45 || ^&47 || ^&50 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t21() {
try {
String sampleRule = "!&50 && !&51 && !&52 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t22() {
try {
String sampleRule = "^&45 || !&51 && !&52 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t23() {
try {
String sampleRule = "(^&45 || !&51) && !&52 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t24() {
try {
String sampleRule = "^&45 || (!&51 && !&52) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t25() {
try {
String sampleRule = "!&50 || !&45 && !&52 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t26() {
try {
String sampleRule = "(!&50 || !&45) && !&52 ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t27() {
try {
String sampleRule = "!&50 || (!&45 && !&52) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t28() {
try {
String sampleRule = "!&55 && (!&54 && (!&53 && (!&47 && !&52))) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("1", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t29() {
try {
String sampleRule = "!&55 && (!&54 && (!&53 && (!&56 && !&52))) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t30() {
try {
String sampleRule = "(!&55 || (!&54 || (!&53 || (!&52 && !&47)))) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t31() {
try {
String sampleRule = "((((!&55 || !&54) || !&53) || !&52) && !&47) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("0", resultStore.get("45").get(0));
Assert.assertEquals("1", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t32() {
try {
String sampleRule = "(&382[1]->&655!=\"tarz\" || (&382[0]->&655==\"fubi\" "
+ "|| (&382[1]->&375==3 || (&382 >= 2 || (&45 > -1 || (&48 <=1.5 && &47 < 0.0001)))))) ? &45=1 : &48=1";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("45").get(0));
Assert.assertEquals("1.5", resultStore.get("48").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t34() {
try {
// left to right
String sampleRule = "&45 == 0 || &43 == -100 && &207 == \"USA\" ? &43=1 : &43=2";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("2", resultStore.get("43").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void t35() {
try {
String sampleRule = "&45 == 0 || (&43 == -100 && &207 == \"USA\") ? &43=1 : &43=2";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("1", resultStore.get("43").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
static final String sampleMessage1 = "8=FIX.4.4" + '\u0001' + "9=1000" + '\u0001' + "35=8"
+ '\u0001' + "44=3.142" + '\u0001' + "60=20130412-19:30:00.686" + '\u0001' + "75=20130412"
+ '\u0001' + "45=0" + '\u0001' + "47=0" + '\u0001' + "48=1.5" + '\u0001' + "49=8dhosb"
+ '\u0001' + "382=2" + '\u0001' + "375=1.5" + '\u0001' + "655=fubi" + '\u0001' + "375=3"
+ '\u0001' + "655=yubl" + '\u0001' + "10=004";
@Test
public void t36() {
try {
// 45=0,
String sampleRule = "(&45 == 0 || &43 == -100) && &207 == \"USA\" ? &43=1 : &43=2";
ListMultimap<String, String> resultStore = getResults(sampleRule);
Assert.assertEquals("2", resultStore.get("43").get(0));
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
}
| globalforge/infix | src/test/java/com/globalforge/infix/TestAndOrSimple.java | Java | mit | 16,486 |
<?php
namespace App\Controllers;
use App\Models\Queries\ArticleSQL;
use App\Models\Queries\CategorieSQL;
use Core\Language;
use Core\View;
use Core\Controller;
use Helpers\Twig;
use Helpers\Url;
class Categories extends Controller {
public function __construct() {
parent::__construct();
}
public function getCategorie() {
$categorieSQL = new CategorieSQL();
$categorie = $categorieSQL->prepareFindAll()->execute();
$data['categories'] = $categorie;
$data['url'] = SITEURL;
$data['title'] = "Toutes les catégories";
View::rendertemplate('header', $data);
Twig::render('Categorie/index', $data);
View::rendertemplate('footer', $data);
}
public function detailCategorie($id) {
$categorieSQL = new CategorieSQL();
$categorie = $categorieSQL->findById($id);
if($categorie){
$articleSQL = new ArticleSQL();
//$article = $articleSQL->findById($id);
$article = $articleSQL->prepareFindWithCondition("id_categorie = ".$id)->execute();
$data['categorie'] = $categorie;
$data['article'] = $article;
$data['url'] = SITEURL;
$data['title'] = $categorie->titre;
View::rendertemplate('header', $data);
Twig::render('Categorie/detail', $data);
View::rendertemplate('footer', $data);
}else{
$this->getCategorie();
}
}
}
| HelleboidQ/WordPress-en-mieux | app/Controllers/Categories.php | PHP | mit | 1,507 |
import Icon from '../components/Icon.vue'
Icon.register({"arrows":{"width":1792,"height":1792,"paths":[{"d":"M1792 896q0 26-19 45l-256 256q-19 19-45 19t-45-19-19-45v-128h-384v384h128q26 0 45 19t19 45-19 45l-256 256q-19 19-45 19t-45-19l-256-256q-19-19-19-45t19-45 45-19h128v-384h-384v128q0 26-19 45t-45 19-45-19l-256-256q-19-19-19-45t19-45l256-256q19-19 45-19t45 19 19 45v128h384v-384h-128q-26 0-45-19t-19-45 19-45l256-256q19-19 45-19t45 19l256 256q19 19 19 45t-19 45-45 19h-128v384h384v-128q0-26 19-45t45-19 45 19l256 256q19 19 19 45z"}]}})
| shikun2014010800/manga | web/console/node_modules/vue-awesome/icons/arrows.js | JavaScript | mit | 542 |
require 'test_helper'
require 'bearychat/rtm'
class BearychatTest < Minitest::Test
MOCK_HOOK_URI = 'https://hook.bearychat.com/mock/incoming/hook'
def test_that_it_has_a_version_number
refute_nil ::Bearychat::VERSION
end
def test_incoming_build_by_module
assert_equal true, ::Bearychat.incoming(MOCK_HOOK_URI).is_a?(::Bearychat::Incoming)
end
def test_incoming_send
incoming_stub = stub_request(:post, MOCK_HOOK_URI).with(body: hash_including(:text))
::Bearychat.incoming(MOCK_HOOK_URI).send
assert_requested(incoming_stub)
end
def test_rtm_send
rtm_stub = stub_request(:post, Bearychat::RTM::MESSAGE_URL).with(body: hash_including(:token))
token = 'TOKEN'
::Bearychat.rtm(token).send text: 'test'
assert_requested(rtm_stub)
end
end
| pokka/bearychat-rb | test/bearychat_test.rb | Ruby | mit | 792 |
package iron_hippo_exe
import (
"fmt"
"io"
"net/http"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/appengine"
"google.golang.org/appengine/log"
"google.golang.org/appengine/urlfetch"
)
const ProjectID = "cpb101demo1"
type DataflowTemplatePostBody struct {
JobName string `json:"jobName"`
GcsPath string `json:"gcsPath"`
Parameters struct {
InputTable string `json:"inputTable"`
OutputProjectID string `json:"outputProjectId"`
OutputKind string `json:"outputKind"`
} `json:"parameters"`
Environment struct {
TempLocation string `json:"tempLocation"`
Zone string `json:"zone"`
} `json:"environment"`
}
func init() {
http.HandleFunc("/cron/start", handler)
}
func handler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
client := &http.Client{
Transport: &oauth2.Transport{
Source: google.AppEngineTokenSource(ctx, "https://www.googleapis.com/auth/cloud-platform"),
Base: &urlfetch.Transport{Context: ctx},
},
}
res, err := client.Post(fmt.Sprintf("https://dataflow.googleapis.com/v1b3/projects/%s/templates", ProjectID), "application/json", r.Body)
if err != nil {
log.Errorf(ctx, "ERROR dataflow: %s", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
_, err = io.Copy(w, res.Body)
if err != nil {
log.Errorf(ctx, "ERROR Copy API response: %s", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(res.StatusCode)
}
| sinmetal/iron-hippo | appengine/iron_hippo.go | GO | mit | 1,489 |
Title: On Git and GitHub Flow
Date: 2015-01-01
Recently, I have been making an added effort to seek out and contribute to open source projects on GitHub. The motivation behind this was largely the [24 Pull Requests](http://24pullrequests.com) project, which encourages developers to submit one pull request for each day in December leading up to Christmas. The prospect of being a new contributor to a large, open source project can be daunting, especially to the novice programmer, so this little bit of extrinsic motivation was a nudge in the right direction.
In learning how to properly make use of Git and GitHub, I've referenced a multitude of different resources. With 2015 having just arrived, I'm sure many people have "contribute to more open source projects" on their list of New Year's resolutions as well, so hopefully this article serves as a useful starting point.
## Finding a Project
Choosing a project is left as an exercise to the reader. However, here are my suggestions:
- Look to see if any software you use on a regular basis is open source. Given your familiarity with the software, you will likely be able to identify (and hack on) some bugs or additional features.
- Check out [trending GitHub repositories](https://github.com/trending) for languages that you're familiar with or ones that you're interested in learning, and pick one that seems friendly towards new contributors (most projects on GitHub are) and well-maintained. This technique is useful as you'll be browsing across projects that your fellow open source developers have also deemed interesting.
Remember that even if you can't contribute directly to the codebase due to lack of experience or being overwhelmed by the scale of the project, open source projects appreciate all sorts of contributions. While not as "prestigious", documentation and unit tests are areas that inevitability need to be addressed, and are a good way to become familiar with the project.
## Getting Started
The first step to using Git is installing it. You can do that from Git's [download page](http://git-scm.com/downloads), or through a package manager like Homebrew. My suggestion is to learn Git from the command line, and to avoid using other Git clients; the command line is universal, so being familiar with it to start with will be beneficial in the long run.
That being said, I do have [GitHub for Mac](https://mac.github.com) installed and I use it fairly frequently for selectively choosing specific parts of a file to commit, which is fairly cumbersome to do from the command line. Also, I find looking through the changes that have been made is much easier with the GitHub application compared to using `git diff`.
## Overview
Git tracks content modifications. It does so primarily through the use of commits. Commits can be thought of as snapshots in the development process, and contain authorship and timestamp information among other pieces of metadata. By committing frequently, it becomes trivial to rollback to an old commit if something goes disastrously (or if your simply don't like the changes you made). Because of this, Git (and any other version control system) is extremely powerful, even for projects that aren't collaborative in nature.
There is a convention behind the formatting of commit messages that should be followed, given the collaborative nature of open source projects. The first (or only) line of the commit is a summary of the changes, 50 characters at most, in the imperative tense (as in *add*, not *added*). If you want to expand further, you should leave a blank line and on the third line, begin an extended description wrapped to 72 characters.
Unfortunately, after prolonged periods of time, the quality of commit messages tends to degrade ([relevant XKCD](http://xkcd.com/1296/)). Don't worry about this, though, as you can avoid forcing others to look at your horribly crafted commit messages through a process known as *rebasing*, discussed later in this article.
## Branches and Pull Requests
One concept that is central to Git and GitHub flow is branching. Branches are pointers to commits. When working on feature additions or fixes in a project, it is advisable to *always* work in a separate branch, and either merge or rebase -- discussed later in much more detail -- into the master branch upon competition.
When you open a pull request on GitHub, the branch that you chose is noted. Pushing additional commits to that specific branch will result in them appearing in the pull request. This is one of the strongest cases for using a new branch for every feature or bug fix -- it makes it trivial to open a pull request for that specific change, without incorporating any unrelated changes.
## To Merge or Not to Merge
Merging is the process of merging the commits made in two branches into one branch. This is done when a branch that is being worked on is deemed complete, and the changes are to be merged into the master branch. In the simplest case (where the only commits that have been made are in the topic branch), this is known as a fast-forward merge, and the commits are "played on top of" the master branch. Fast-forward merges can be performed automatically by Git and require no additional effort on the part of the user performing the merge. In other cases, merging either results in a merge commit or the manual resolution of merge conflicts (if the changes made in the branches contradict one another).
Something that Git tutorials tend to gloss over is the rebase command. The reason for this is that rebasing involves *rewriting history*. When you rebase a set of commits, they will change, and if the older set of commits have already been pushed to a remote repository that others have pulled from, pushing new changes will cause a break in continuity for others who try to pull these newly pushed commits. Because of this, it is recommended to only rebase local commits in most cases.
```sh
$ git rebase -i HEAD~n # rebase the last n commits
```
The `-i` flag stands for *interactive*. Upon executing the command, your `$EDITOR` of choice will open with a list of commits from least recent to most recent preceded by the word "pick":
```
#!text
pick a5b977a Ensure all expected resource files exist
pick f08e801 Add problems 311–320
pick 969f9e5 Update tests to ensure resource correspondence
```
Below the list of commits are some instructions about rebasing, including the available commands. To actually rebase, you make changes to the text in the editor and then close it. Here are the operations that you can perform:
- Delete the line, which will remove the commit entirely.
- Change "pick" to a different command, causing the rebase to execute that command instead.
- Rearrange the lines, which will rearrange the order of the commits.
Typically, a project maintainer might ask for you to squash your pull request. What this actually involves doing is rebasing and using the "squash" command to turn multiple commits into just one or a couple logical commits. For example, if you wanted to turn the three commits listed above into one larger commit, you would edit the file to look like the following:
```
#!text
pick a5b977a Ensure all expected resource files exist
squash f08e801 Add problems 311–320
squash 969f9e5 Update tests to ensure resource correspondence
```
Upon closing the editor, a new editor will open up that allows you to edit the commit message of the newly created single commit. The commit messages of each of the commits being squashed are included for the sake of convenience, and when the editor is closed, the non-commented lines become the new commit message.
I mentioned before that rebasing should only be done with local changes that have not been pushed to a remote repository, but in a pull request, by definition, the commits have already been pushed to your fork of the main repository. In this case, it is fine to rebase and push, since it can be assumed that people have not been actively making changes on the feature/fix branch that your pull request is based on. However, Git will not let you push the rebased commits using `git push` out of safety; you have to use `git push -f` to *force* the push to happen.
## Putting It All Together
After forking the project on GitHub, the typical GitHub workflow might look something like this:
```
#!sh
git clone https://github.com/YOUR_GITHUB_USERNAME/PROJECT_NAME.git
cd PROJECT_NAME
git branch my-feature
git checkout my-feature
nano README.md
rm silly-file.txt
git add -A
git commit
git push -u origin my-feature
```
1. Clone your fork to your local development machine.
2. Change the current directory to the project folder.
3. Create a branch called `my-feature`.
4. Switch to the newly created `my-feature` branch.
5. Make changes to `README.md`.
6. Remove `silly-file.txt`.
7. Stage all (`-A`) changes made, including file creations and deletions. You can specify certain files rather than using the `-A` flag to selectively stage changes.
8. Commit the changes that have been staged. Continue to commit new changes and rebase when needed.
9. Push the `my-feature` branch to remote repository aliased as `origin` (your fork), using the `-u` flag to add the branch as a remote tracking branch. (Subsequent pushes will only requre a `git push` with no additional parameters.) Then, open a pull request using GitHub's web interface!
For other Git-related problems that one may run into, Google can usually provide the answer. Be sure to look at [GitHub's help page](https://help.github.com) and the [Git documentation](http://git-scm.com/doc) itself. Here's to lots of open source contributions in 2015!
| iKevinY/iKevinY.github.io | content/1501-on-git-and-github-flow.md | Markdown | mit | 9,682 |
--[[
File: src/animation/frame.lua
Author: Daniel "lytedev" Flanagan
Website: http://dmf.me
Contains the data to specify a piece of a texture over a period of time.
]]--
local Frame = Class{}
function Frame.generate(w, h, imgw, imgh, num, time, frames, offset, start)
local start = start or 0
local tw = math.floor(imgw / w)
local th = math.floor(imgh / h)
local num = num or (tw * th)
local framesArray = {}
for i = start, num - 1, 1 do
-- To change left-to-right-down, modify xid and yid calcs
local xid = i % tw
local yid = math.floor(i / tw)
local frame = Frame(Vector(xid * w, yid * h), Vector(w, h), time, frames, offset)
table.insert(framesArray, frame)
end
return framesArray
end
function Frame:init(source, size, time, frames, offset)
self.source = source or Vector(0, 0)
self.size = size or Vector(16, 16)
self.offset = offset or Vector(0, 0)
self.time = time or 0.2
self.frames = frames or nil
end
function Frame:__tostring()
return string.format("Source: (%s), Size: (%s), Time: %ds, Frames: %i, Offset: (%s)", tostring(self.source), tostring(self.size), self.time, self.frames or 0, tostring(self.offset))
end
return Frame
| lytedev/love2d-bootstrap | lib/animation/frame.lua | Lua | mit | 1,198 |
# Input Number
Simple jQuery plugin to add plus and minus controls to an input element
## Installation
Installation can be done through bower
```
bower install develo-input-number --save
```
Then add the script and jQuery to your page.
## Example Usage
```
// Default options, feel free to override them.
var options = {
// Style customisations
className: 'develo-quantity-helper',
buttonClassName: 'button',
// Min and max
max: null,
min: null,
// Plus and minus buttons. Supports html
minusHtml: '-',
plusHtml: '+',
// Callbacks
onDecreased: function( value ){},
onIncreased: function( value ){}
};
$( 'input' ).develoInputNumber();
```
| develodesign/input-number | README.md | Markdown | mit | 659 |
/**
* Your Copyright Here
*
* Appcelerator Titanium is Copyright (c) 2009-2010 by Appcelerator, Inc.
* and licensed under the Apache Public License (version 2)
*/
#import <UIKit/UIKit.h>
#import "TiModule.h"
@class iPhoneHTTPServerViewController;
@class HTTPServer;
@interface Com0x82WebserverModule : TiModule
{
HTTPServer *httpServer;
BOOL wasRunning;
}
@property (nonatomic, assign) NSNumber* disconnectsInBackground;
-(id)startServer:(id)args;
@end | rubenfonseca/titanium-webserver | Classes/Com0x82WebserverModule.h | C | mit | 465 |
# Awful Recruiters
This used to be a list of third party recruiters. This was on the website:
> I am definitely not saying these companies are awful. Simply that they are a source of undesirable email. This site is simply a list of domains. No claims are being made about the owners or their intentions.
Ideally, it was just a list of third-party recruiters. “Awful” was intended to be humorous. Some people over reacted a bit. Instead of constantly trying to explain myself, I think it's best to just remove the list. The whole point was to get less email. It's easier to ignore irrelevant job emails than empty legal threats.
| soffes/awfulrecruiters.com | Readme.markdown | Markdown | mit | 635 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="white">
<title>My App</title>
<!-- Path to Framework7 Library CSS-->
<link rel="stylesheet" href="https://framework7.io/dist/css/framework7.ios.min.css">
<link rel="stylesheet" href="https://framework7.io/dist/css/framework7.ios.colors.min.css">
<!-- Path to your custom app styles-->
<link rel="stylesheet" href="css/Framework7.QuickActions.css">
<link rel="stylesheet" href="css/my-app.css">
</head>
<body>
<!-- Status bar overlay for fullscreen mode-->
<div class="statusbar-overlay"></div>
<!-- Panels overlay-->
<div class="panel-overlay"></div>
<!-- Left panel with reveal effect-->
<div class="panel panel-left panel-reveal">
<div class="content-block">
<p>Left panel content goes here</p>
</div>
</div>
<!-- Right panel with cover effect-->
<div class="panel panel-right panel-cover">
<div class="content-block">
<p>Right panel content goes here</p>
</div>
</div>
<!-- Views-->
<div class="views">
<!-- Your main view, should have "view-main" class-->
<div class="view view-main">
<!-- Top Navbar-->
<div class="navbar">
<!-- Navbar inner for Index page-->
<div data-page="index" class="navbar-inner">
<!-- We have home navbar without left link-->
<div class="center sliding">Awesome App</div>
<div class="right">
<!-- Right link contains only icon - additional "icon-only" class--><a href="#" class="link icon-only open-panel"> <i class="icon icon-bars"></i></a>
</div>
</div>
<!-- Navbar inner for About page-->
<div data-page="about" class="navbar-inner cached">
<div class="left sliding"><a href="#" class="back link"> <i class="icon icon-back"></i><span>Back</span></a></div>
<div class="center sliding">About Us</div>
</div>
<!-- Navbar inner for Services page-->
<div data-page="services" class="navbar-inner cached">
<div class="left sliding"><a href="#" class="back link"> <i class="icon icon-back"></i><span>Back</span></a></div>
<div class="center sliding">Services</div>
</div>
<!-- Navbar inner for Form page-->
<div data-page="form" class="navbar-inner cached">
<div class="left sliding"><a href="#" class="back link"> <i class="icon icon-back"></i><span>Back</span></a></div>
<div class="center sliding">Form</div>
</div>
</div>
<!-- Pages, because we need fixed-through navbar and toolbar, it has additional appropriate classes-->
<div class="pages navbar-through toolbar-through">
<!-- Index Page-->
<div data-page="index" class="page">
<!-- Scrollable page content-->
<div class="page-content">
<div class="content-block-title">Welcome To My Awesome App</div>
<div class="content-block">
<div class="content-block-inner">
<p>Couple of worlds here because my app is so awesome!</p>
<p><a href="#" quick-actions-target="#action1" class="link quick-actions">Duis sed</a> <a href="#" data-href='hi @ds' class="peekPop">erat ac</a> eros ultrices pharetra id ut tellus. Praesent rhoncus enim ornare ipsum aliquet ultricies. Pellentesque sodales erat quis elementum sagittis.</p>
</div>
</div>
<div class="content-block-title">What about simple navigation?</div>
<div class="list-block">
<ul>
<li><a href="#about" class="item-link">
<div class="item-content">
<div class="item-inner">
<div class="item-title">About</div>
</div>
</div></a></li>
<li><a href="#services" class="item-link">
<div class="item-content">
<div class="item-inner">
<div class="item-title">Services</div>
</div>
</div></a></li>
<li><a href="#form" class="item-link">
<div class="item-content">
<div class="item-inner">
<div class="item-title">Form</div>
</div>
</div></a></li>
</ul>
</div>
<div class="content-block-title">Side panels</div>
<div class="content-block">
<div class="row">
<div class="col-50"><a href="#" data-panel="left" class="button open-panel">Left Panel</a></div>
<div class="col-50"><a href="#" data-panel="right" class="button open-panel">Right Panel</a></div>
</div>
</div>
</div>
</div>
<!-- About Page-->
<div data-page="about" class="page cached">
<div class="page-content">
<div class="content-block">
<p>You may go <a href="#" class="back">back</a> or load <a href="#services">Services</a> page.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vel commodo massa, eu adipiscing mi. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Phasellus ultricies dictum neque, non varius tortor fermentum at. Curabitur auctor cursus imperdiet. Nam molestie nisi nec est lacinia volutpat in a purus. Maecenas consectetur condimentum viverra. Donec ultricies nec sem vel condimentum. Phasellus eu tincidunt enim, sit amet convallis orci. Vestibulum quis fringilla dolor. </p>
<p>Mauris commodo lacus at nisl lacinia, nec facilisis erat rhoncus. Sed eget pharetra nunc. Aenean vitae vehicula massa, sed sagittis ante. Quisque luctus nec velit dictum convallis. Nulla facilisi. Ut sed erat nisi. Donec non dolor massa. Mauris malesuada dolor velit, in suscipit leo consectetur vitae. Duis tempus ligula non eros pretium condimentum. Cras sed dolor odio.</p>
<p>Suspendisse commodo adipiscing urna, a aliquet sem egestas in. Sed tincidunt dui a magna facilisis bibendum. Nunc euismod consectetur lorem vitae molestie. Proin mattis tellus libero, non hendrerit neque eleifend ac. Pellentesque interdum velit at lacus consectetur scelerisque et id dui. Praesent non fringilla dui, a elementum purus. Proin vitae lacus libero. Nunc eget lectus non mi iaculis interdum vel a velit. Nullam tincidunt purus id lacus ornare, at elementum turpis euismod. Cras mauris enim, congue eu nisl sit amet, pulvinar semper erat. Suspendisse sed mauris diam.</p>
<p>Nam eu mauris leo. Pellentesque aliquam vehicula est, sed lobortis tellus malesuada facilisis. Fusce at hendrerit ligula. Donec eu nibh convallis, pulvinar enim quis, lacinia diam. Ut semper ac magna nec ornare. Integer placerat justo sed nunc suscipit facilisis. Vestibulum ac tincidunt augue. Duis eu aliquet mauris, vel luctus mauris. Nulla non augue nec diam pharetra posuere at in mauris.</p>
</div>
</div>
</div>
<!-- Services Page-->
<div data-page="services" class="page cached">
<div class="page-content">
<div class="content-block">
<p>You may go <a href="#" class="back">back</a> or load <a href="#about">About</a> page.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vel commodo massa, eu adipiscing mi. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Phasellus ultricies dictum neque, non varius tortor fermentum at. Curabitur auctor cursus imperdiet. Nam molestie nisi nec est lacinia volutpat in a purus. Maecenas consectetur condimentum viverra. Donec ultricies nec sem vel condimentum. Phasellus eu tincidunt enim, sit amet convallis orci. Vestibulum quis fringilla dolor. </p>
<p>Mauris commodo lacus at nisl lacinia, nec facilisis erat rhoncus. Sed eget pharetra nunc. Aenean vitae vehicula massa, sed sagittis ante. Quisque luctus nec velit dictum convallis. Nulla facilisi. Ut sed erat nisi. Donec non dolor massa. Mauris malesuada dolor velit, in suscipit leo consectetur vitae. Duis tempus ligula non eros pretium condimentum. Cras sed dolor odio.</p>
<p>Suspendisse commodo adipiscing urna, a aliquet sem egestas in. Sed tincidunt dui a magna facilisis bibendum. Nunc euismod consectetur lorem vitae molestie. Proin mattis tellus libero, non hendrerit neque eleifend ac. Pellentesque interdum velit at lacus consectetur scelerisque et id dui. Praesent non fringilla dui, a elementum purus. Proin vitae lacus libero. Nunc eget lectus non mi iaculis interdum vel a velit. Nullam tincidunt purus id lacus ornare, at elementum turpis euismod. Cras mauris enim, congue eu nisl sit amet, pulvinar semper erat. Suspendisse sed mauris diam.</p>
<p>Nam eu mauris leo. Pellentesque aliquam vehicula est, sed lobortis tellus malesuada facilisis. Fusce at hendrerit ligula. Donec eu nibh convallis, pulvinar enim quis, lacinia diam. Ut semper ac magna nec ornare. Integer placerat justo sed nunc suscipit facilisis. Vestibulum ac tincidunt augue. Duis eu aliquet mauris, vel luctus mauris. Nulla non augue nec diam pharetra posuere at in mauris. </p>
</div>
</div>
</div>
<!-- Form Page-->
<div data-page="form" class="page cached">
<div class="page-content">
<div class="content-block-title">Form Example</div>
<div class="list-block">
<ul>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-name"></i></div>
<div class="item-inner">
<div class="item-title label">Name</div>
<div class="item-input">
<input type="text" placeholder="Your name">
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-email"></i></div>
<div class="item-inner">
<div class="item-title label">E-mail</div>
<div class="item-input">
<input type="email" placeholder="E-mail">
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-url"></i></div>
<div class="item-inner">
<div class="item-title label">URL</div>
<div class="item-input">
<input type="url" placeholder="URL">
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-password"></i></div>
<div class="item-inner">
<div class="item-title label">Password</div>
<div class="item-input">
<input type="password" placeholder="Password">
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-tel"></i></div>
<div class="item-inner">
<div class="item-title label">Phone</div>
<div class="item-input">
<input type="tel" placeholder="Phone">
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-gender"></i></div>
<div class="item-inner">
<div class="item-title label">Gender</div>
<div class="item-input">
<select>
<option>Male</option>
<option>Female</option>
</select>
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-calendar"></i></div>
<div class="item-inner">
<div class="item-title label">Birth date</div>
<div class="item-input">
<input type="date" placeholder="Birth day" value="2014-04-30">
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-toggle"></i></div>
<div class="item-inner">
<div class="item-title label">Switch</div>
<div class="item-input">
<label class="label-switch">
<input type="checkbox">
<div class="checkbox"></div>
</label>
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-media"><i class="icon icon-form-settings"></i></div>
<div class="item-inner">
<div class="item-title label">Slider</div>
<div class="item-input">
<div class="range-slider">
<input type="range" min="0" max="100" value="50" step="0.1">
</div>
</div>
</div>
</div>
</li>
<li class="align-top">
<div class="item-content">
<div class="item-media"><i class="icon icon-form-comment"></i></div>
<div class="item-inner">
<div class="item-title label">Textarea</div>
<div class="item-input">
<textarea></textarea>
</div>
</div>
</div>
</li>
</ul>
</div>
<div class="content-block">
<div class="row">
<div class="col-50"><a href="#" class="button button-big button-fill color-red">Cancel</a></div>
<div class="col-50">
<input type="submit" value="Submit" class="button button-big button-fill color-green">
</div>
</div>
</div>
<div class="content-block-title">Checkbox group</div>
<div class="list-block">
<ul>
<li>
<label class="label-checkbox item-content">
<input type="checkbox" name="ks-checkbox" value="Books" checked>
<div class="item-media"><i class="icon icon-form-checkbox"></i></div>
<div class="item-inner">
<div class="item-title">Books</div>
</div>
</label>
</li>
<li>
<label class="label-checkbox item-content">
<input type="checkbox" name="ks-checkbox" value="Movies">
<div class="item-media"><i class="icon icon-form-checkbox"></i></div>
<div class="item-inner">
<div class="item-title">Movies</div>
</div>
</label>
</li>
<li>
<label class="label-checkbox item-content">
<input type="checkbox" name="ks-checkbox" value="Food">
<div class="item-media"><i class="icon icon-form-checkbox"></i></div>
<div class="item-inner">
<div class="item-title">Food</div>
</div>
</label>
</li>
<li>
<label class="label-checkbox item-content">
<input type="checkbox" name="ks-checkbox" value="Drinks">
<div class="item-media"><i class="icon icon-form-checkbox"></i></div>
<div class="item-inner">
<div class="item-title">Drinks</div>
</div>
</label>
</li>
</ul>
</div>
<div class="content-block-title">Radio buttons group</div>
<div class="list-block">
<ul>
<li>
<label class="label-radio item-content">
<input type="radio" name="ks-radio" value="Books" checked>
<div class="item-inner">
<div class="item-title">Books</div>
</div>
</label>
</li>
<li>
<label class="label-radio item-content">
<input type="radio" name="ks-radio" value="Movies">
<div class="item-inner">
<div class="item-title">Movies</div>
</div>
</label>
</li>
<li>
<label class="label-radio item-content">
<input type="radio" name="ks-radio" value="Food">
<div class="item-inner">
<div class="item-title">Food</div>
</div>
</label>
</li>
<li>
<label class="label-radio item-content">
<input type="radio" name="ks-radio" value="Drinks">
<div class="item-inner">
<div class="item-title">Drinks</div>
</div>
</label>
</li>
</ul>
</div>
</div>
</div>
</div>
<!-- Bottom Toolbar-->
<div class="toolbar">
<div class="toolbar-inner">
<a href="#" class="link">Link 1</a>
<a href="#" class="link">Link 2</a></div>
</div>
</div>
</div>
<!-- Quick actions -->
<ul id="action1" class="quick-actions-menu">
<li class="quickaction-item sub-menu-item">
<a class="quickaction-link" href="#">New message</a>
</li>
<li class="quickaction-item sub-menu-item">
<a class="quickaction-link" href="#">Inbox</a>
</li>
</ul>
<!-- Peek and Pop -->
<!-- Path to Framework7 Library JS-->
<script type="text/javascript" src="https://framework7.io/dist/js/framework7.min.js"></script>
<!-- Path to your app js-->
<script type="text/javascript" src="js/Hammer.js"></script>
<!-- Maybe in future: script type="text/javascript" src="js/Forcify.js"></script-->
<script type="text/javascript" src="js/Framework7.QuickActions.js"></script>
<script type="text/javascript" src="js/my-app.js"></script>
</body>
</html>
| dalisoft/Framework7-QuickAction | index.html | HTML | mit | 20,660 |
# Controllers
- [Introduction](#introduction)
- [Writing Controllers](#writing-controllers)
- [Basic Controllers](#basic-controllers)
- [Single Action Controllers](#single-action-controllers)
- [Controller Middleware](#controller-middleware)
- [Resource Controllers](#resource-controllers)
- [Partial Resource Routes](#restful-partial-resource-routes)
- [Nested Resources](#restful-nested-resources)
- [Naming Resource Routes](#restful-naming-resource-routes)
- [Naming Resource Route Parameters](#restful-naming-resource-route-parameters)
- [Scoping Resource Routes](#restful-scoping-resource-routes)
- [Localizing Resource URIs](#restful-localizing-resource-uris)
- [Supplementing Resource Controllers](#restful-supplementing-resource-controllers)
- [Dependency Injection & Controllers](#dependency-injection-and-controllers)
<a name="introduction"></a>
## Introduction
Instead of defining all of your request handling logic as closures in your route files, you may wish to organize this behavior using "controller" classes. Controllers can group related request handling logic into a single class. For example, a `UserController` class might handle all incoming requests related to users, including showing, creating, updating, and deleting users. By default, controllers are stored in the `app/Http/Controllers` directory.
<a name="writing-controllers"></a>
## Writing Controllers
<a name="basic-controllers"></a>
### Basic Controllers
Let's take a look at an example of a basic controller. Note that the controller extends the base controller class included with Laravel: `App\Http\Controllers\Controller`:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
class UserController extends Controller
{
/**
* Show the profile for a given user.
*
* @param int $id
* @return \Illuminate\View\View
*/
public function show($id)
{
return view('user.profile', [
'user' => User::findOrFail($id)
]);
}
}
You can define a route to this controller method like so:
use App\Http\Controllers\UserController;
Route::get('/user/{id}', [UserController::class, 'show']);
When an incoming request matches the specified route URI, the `show` method on the `App\Http\Controllers\UserController` class will be invoked and the route parameters will be passed to the method.
> {tip} Controllers are not **required** to extend a base class. However, you will not have access to convenient features such as the `middleware` and `authorize` methods.
<a name="single-action-controllers"></a>
### Single Action Controllers
If a controller action is particularly complex, you might find it convenient to dedicate an entire controller class to that single action. To accomplish this, you may define a single `__invoke` method within the controller:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
class ProvisionServer extends Controller
{
/**
* Provision a new web server.
*
* @return \Illuminate\Http\Response
*/
public function __invoke()
{
// ...
}
}
When registering routes for single action controllers, you do not need to specify a controller method. Instead, you may simply pass the name of the controller to the router:
use App\Http\Controllers\ProvisionServer;
Route::post('/server', ProvisionServer::class);
You may generate an invokable controller by using the `--invokable` option of the `make:controller` Artisan command:
```shell
php artisan make:controller ProvisionServer --invokable
```
> {tip} Controller stubs may be customized using [stub publishing](/docs/{{version}}/artisan#stub-customization).
<a name="controller-middleware"></a>
## Controller Middleware
[Middleware](/docs/{{version}}/middleware) may be assigned to the controller's routes in your route files:
Route::get('profile', [UserController::class, 'show'])->middleware('auth');
Or, you may find it convenient to specify middleware within your controller's constructor. Using the `middleware` method within your controller's constructor, you can assign middleware to the controller's actions:
class UserController extends Controller
{
/**
* Instantiate a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware('log')->only('index');
$this->middleware('subscribed')->except('store');
}
}
Controllers also allow you to register middleware using a closure. This provides a convenient way to define an inline middleware for a single controller without defining an entire middleware class:
$this->middleware(function ($request, $next) {
return $next($request);
});
<a name="resource-controllers"></a>
## Resource Controllers
If you think of each Eloquent model in your application as a "resource", it is typical to perform the same sets of actions against each resource in your application. For example, imagine your application contains a `Photo` model and a `Movie` model. It is likely that users can create, read, update, or delete these resources.
Because of this common use case, Laravel resource routing assigns the typical create, read, update, and delete ("CRUD") routes to a controller with a single line of code. To get started, we can use the `make:controller` Artisan command's `--resource` option to quickly create a controller to handle these actions:
```shell
php artisan make:controller PhotoController --resource
```
This command will generate a controller at `app/Http/Controllers/PhotoController.php`. The controller will contain a method for each of the available resource operations. Next, you may register a resource route that points to the controller:
use App\Http\Controllers\PhotoController;
Route::resource('photos', PhotoController::class);
This single route declaration creates multiple routes to handle a variety of actions on the resource. The generated controller will already have methods stubbed for each of these actions. Remember, you can always get a quick overview of your application's routes by running the `route:list` Artisan command.
You may even register many resource controllers at once by passing an array to the `resources` method:
Route::resources([
'photos' => PhotoController::class,
'posts' => PostController::class,
]);
<a name="actions-handled-by-resource-controller"></a>
#### Actions Handled By Resource Controller
Verb | URI | Action | Route Name
----------|------------------------|--------------|---------------------
GET | `/photos` | index | photos.index
GET | `/photos/create` | create | photos.create
POST | `/photos` | store | photos.store
GET | `/photos/{photo}` | show | photos.show
GET | `/photos/{photo}/edit` | edit | photos.edit
PUT/PATCH | `/photos/{photo}` | update | photos.update
DELETE | `/photos/{photo}` | destroy | photos.destroy
<a name="customizing-missing-model-behavior"></a>
#### Customizing Missing Model Behavior
Typically, a 404 HTTP response will be generated if an implicitly bound resource model is not found. However, you may customize this behavior by calling the `missing` method when defining your resource route. The `missing` method accepts a closure that will be invoked if an implicitly bound model can not be found for any of the resource's routes:
use App\Http\Controllers\PhotoController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
Route::resource('photos', PhotoController::class)
->missing(function (Request $request) {
return Redirect::route('photos.index');
});
<a name="specifying-the-resource-model"></a>
#### Specifying The Resource Model
If you are using [route model binding](/docs/{{version}}/routing#route-model-binding) and would like the resource controller's methods to type-hint a model instance, you may use the `--model` option when generating the controller:
```shell
php artisan make:controller PhotoController --model=Photo --resource
```
<a name="generating-form-requests"></a>
#### Generating Form Requests
You may provide the `--requests` option when generating a resource controller to instruct Artisan to generate [form request classes](/docs/{{version}}/validation#form-request-validation) for the controller's storage and update methods:
```shell
php artisan make:controller PhotoController --model=Photo --resource --requests
```
<a name="restful-partial-resource-routes"></a>
### Partial Resource Routes
When declaring a resource route, you may specify a subset of actions the controller should handle instead of the full set of default actions:
use App\Http\Controllers\PhotoController;
Route::resource('photos', PhotoController::class)->only([
'index', 'show'
]);
Route::resource('photos', PhotoController::class)->except([
'create', 'store', 'update', 'destroy'
]);
<a name="api-resource-routes"></a>
#### API Resource Routes
When declaring resource routes that will be consumed by APIs, you will commonly want to exclude routes that present HTML templates such as `create` and `edit`. For convenience, you may use the `apiResource` method to automatically exclude these two routes:
use App\Http\Controllers\PhotoController;
Route::apiResource('photos', PhotoController::class);
You may register many API resource controllers at once by passing an array to the `apiResources` method:
use App\Http\Controllers\PhotoController;
use App\Http\Controllers\PostController;
Route::apiResources([
'photos' => PhotoController::class,
'posts' => PostController::class,
]);
To quickly generate an API resource controller that does not include the `create` or `edit` methods, use the `--api` switch when executing the `make:controller` command:
```shell
php artisan make:controller PhotoController --api
```
<a name="restful-nested-resources"></a>
### Nested Resources
Sometimes you may need to define routes to a nested resource. For example, a photo resource may have multiple comments that may be attached to the photo. To nest the resource controllers, you may use "dot" notation in your route declaration:
use App\Http\Controllers\PhotoCommentController;
Route::resource('photos.comments', PhotoCommentController::class);
This route will register a nested resource that may be accessed with URIs like the following:
/photos/{photo}/comments/{comment}
<a name="scoping-nested-resources"></a>
#### Scoping Nested Resources
Laravel's [implicit model binding](/docs/{{version}}/routing#implicit-model-binding-scoping) feature can automatically scope nested bindings such that the resolved child model is confirmed to belong to the parent model. By using the `scoped` method when defining your nested resource, you may enable automatic scoping as well as instruct Laravel which field the child resource should be retrieved by. For more information on how to accomplish this, please see the documentation on [scoping resource routes](#restful-scoping-resource-routes).
<a name="shallow-nesting"></a>
#### Shallow Nesting
Often, it is not entirely necessary to have both the parent and the child IDs within a URI since the child ID is already a unique identifier. When using unique identifiers such as auto-incrementing primary keys to identify your models in URI segments, you may choose to use "shallow nesting":
use App\Http\Controllers\CommentController;
Route::resource('photos.comments', CommentController::class)->shallow();
This route definition will define the following routes:
Verb | URI | Action | Route Name
----------|-----------------------------------|--------------|---------------------
GET | `/photos/{photo}/comments` | index | photos.comments.index
GET | `/photos/{photo}/comments/create` | create | photos.comments.create
POST | `/photos/{photo}/comments` | store | photos.comments.store
GET | `/comments/{comment}` | show | comments.show
GET | `/comments/{comment}/edit` | edit | comments.edit
PUT/PATCH | `/comments/{comment}` | update | comments.update
DELETE | `/comments/{comment}` | destroy | comments.destroy
<a name="restful-naming-resource-routes"></a>
### Naming Resource Routes
By default, all resource controller actions have a route name; however, you can override these names by passing a `names` array with your desired route names:
use App\Http\Controllers\PhotoController;
Route::resource('photos', PhotoController::class)->names([
'create' => 'photos.build'
]);
<a name="restful-naming-resource-route-parameters"></a>
### Naming Resource Route Parameters
By default, `Route::resource` will create the route parameters for your resource routes based on the "singularized" version of the resource name. You can easily override this on a per resource basis using the `parameters` method. The array passed into the `parameters` method should be an associative array of resource names and parameter names:
use App\Http\Controllers\AdminUserController;
Route::resource('users', AdminUserController::class)->parameters([
'users' => 'admin_user'
]);
The example above generates the following URI for the resource's `show` route:
/users/{admin_user}
<a name="restful-scoping-resource-routes"></a>
### Scoping Resource Routes
Laravel's [scoped implicit model binding](/docs/{{version}}/routing#implicit-model-binding-scoping) feature can automatically scope nested bindings such that the resolved child model is confirmed to belong to the parent model. By using the `scoped` method when defining your nested resource, you may enable automatic scoping as well as instruct Laravel which field the child resource should be retrieved by:
use App\Http\Controllers\PhotoCommentController;
Route::resource('photos.comments', PhotoCommentController::class)->scoped([
'comment' => 'slug',
]);
This route will register a scoped nested resource that may be accessed with URIs like the following:
/photos/{photo}/comments/{comment:slug}
When using a custom keyed implicit binding as a nested route parameter, Laravel will automatically scope the query to retrieve the nested model by its parent using conventions to guess the relationship name on the parent. In this case, it will be assumed that the `Photo` model has a relationship named `comments` (the plural of the route parameter name) which can be used to retrieve the `Comment` model.
<a name="restful-localizing-resource-uris"></a>
### Localizing Resource URIs
By default, `Route::resource` will create resource URIs using English verbs. If you need to localize the `create` and `edit` action verbs, you may use the `Route::resourceVerbs` method. This may be done at the beginning of the `boot` method within your application's `App\Providers\RouteServiceProvider`:
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
Route::resourceVerbs([
'create' => 'crear',
'edit' => 'editar',
]);
// ...
}
Once the verbs have been customized, a resource route registration such as `Route::resource('fotos', PhotoController::class)` will produce the following URIs:
/fotos/crear
/fotos/{foto}/editar
<a name="restful-supplementing-resource-controllers"></a>
### Supplementing Resource Controllers
If you need to add additional routes to a resource controller beyond the default set of resource routes, you should define those routes before your call to the `Route::resource` method; otherwise, the routes defined by the `resource` method may unintentionally take precedence over your supplemental routes:
use App\Http\Controller\PhotoController;
Route::get('/photos/popular', [PhotoController::class, 'popular']);
Route::resource('photos', PhotoController::class);
> {tip} Remember to keep your controllers focused. If you find yourself routinely needing methods outside of the typical set of resource actions, consider splitting your controller into two, smaller controllers.
<a name="dependency-injection-and-controllers"></a>
## Dependency Injection & Controllers
<a name="constructor-injection"></a>
#### Constructor Injection
The Laravel [service container](/docs/{{version}}/container) is used to resolve all Laravel controllers. As a result, you are able to type-hint any dependencies your controller may need in its constructor. The declared dependencies will automatically be resolved and injected into the controller instance:
<?php
namespace App\Http\Controllers;
use App\Repositories\UserRepository;
class UserController extends Controller
{
/**
* The user repository instance.
*/
protected $users;
/**
* Create a new controller instance.
*
* @param \App\Repositories\UserRepository $users
* @return void
*/
public function __construct(UserRepository $users)
{
$this->users = $users;
}
}
<a name="method-injection"></a>
#### Method Injection
In addition to constructor injection, you may also type-hint dependencies on your controller's methods. A common use-case for method injection is injecting the `Illuminate\Http\Request` instance into your controller methods:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Store a new user.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$name = $request->name;
//
}
}
If your controller method is also expecting input from a route parameter, list your route arguments after your other dependencies. For example, if your route is defined like so:
use App\Http\Controllers\UserController;
Route::put('/user/{id}', [UserController::class, 'update']);
You may still type-hint the `Illuminate\Http\Request` and access your `id` parameter by defining your controller method as follows:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Update the given user.
*
* @param \Illuminate\Http\Request $request
* @param string $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
}
| laravel/docs | controllers.md | Markdown | mit | 19,334 |
using NUnit.Framework;
using Ploeh.AutoFixture;
using RememBeer.Models.Dtos;
using RememBeer.Tests.Utils;
namespace RememBeer.Tests.Models.Dtos
{
[TestFixture]
public class BeerDtoTests : TestClassBase
{
[Test]
public void Setters_ShouldSetProperties()
{
var id = this.Fixture.Create<int>();
var breweryId = this.Fixture.Create<int>();
var name = this.Fixture.Create<string>();
var breweryName = this.Fixture.Create<string>();
var dto = new BeerDto();
dto.Id = id;
dto.BreweryId = breweryId;
dto.Name = name;
dto.BreweryName = breweryName;
Assert.AreEqual(id, dto.Id);
Assert.AreEqual(breweryId, dto.BreweryId);
Assert.AreSame(name, dto.Name);
Assert.AreSame(breweryName, dto.BreweryName);
}
}
}
| J0hnyBG/RememBeerMe | src/RememBeer.Tests/Models/Dtos/BeerDtoTests.cs | C# | mit | 908 |
import teca.utils as tecautils
import teca.ConfigHandler as tecaconf
import unittest
class TestFileFilter(unittest.TestCase):
def setUp(self):
self.conf = tecaconf.ConfigHandler(
"tests/test_data/configuration.json",
{"starting_path": "tests/test_data/images"}
)
self.files_list = [
"foo.doc",
"yukinon.jpg",
"cuteflushadoingflushathings.webm"
]
def test_dothefiltering(self):
self.assertTrue("foo.doc" not in
tecautils.filterImages(self.files_list,
self.conf))
self.assertTrue("yukinon.jpg" in
tecautils.filterImages(self.files_list,
self.conf))
def test_nofiles(self):
self.assertEqual(0, len(tecautils.filterImages([], self.conf)))
| alfateam123/Teca | tests/test_utils.py | Python | mit | 902 |
<?php
/*
* This file is part of the Integrated package.
*
* (c) e-Active B.V. <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Integrated\Bundle\AssetBundle\Tests\Manager;
use Integrated\Bundle\AssetBundle\Manager\AssetManager;
/**
* @author Ger Jan van den Bosch <[email protected]>
*/
class AssetManagerTest extends \PHPUnit_Framework_TestCase
{
/**
* @var AssetManager
*/
private $manager;
/**
*/
protected function setUp()
{
$this->manager = new AssetManager();
}
/**
*/
public function testDuplicateFunction()
{
$this->manager->add('script.js');
$this->manager->add('script2.js');
$this->manager->add('script.js');
$this->assertCount(2, $this->manager->getAssets());
}
/**
*/
public function testInlineFunction()
{
$inline = 'html { color: red; }';
$this->manager->add($inline, true);
$asset = $this->manager->getAssets()[0];
$this->assertTrue($asset->isInline());
$this->assertEquals($inline, $asset->getContent());
}
/**
*/
public function testExceptionFunction()
{
$this->setExpectedException('\InvalidArgumentException');
$this->manager->add('script.js', false, 'invalid');
}
/**
*/
public function testPrependFunction()
{
$this->manager->add('script2.js');
$this->manager->add('script3.js', false, AssetManager::MODE_APPEND);
$this->manager->add('script1.js', false, AssetManager::MODE_PREPEND);
$assets = $this->manager->getAssets();
$this->assertEquals('script1.js', $assets[0]->getContent());
$this->assertEquals('script2.js', $assets[1]->getContent());
$this->assertEquals('script3.js', $assets[2]->getContent());
}
}
| integratedfordevelopers/integrated-asset-bundle | Tests/Manager/AssetManagerTest.php | PHP | mit | 1,949 |
import { h, Component } from 'preact';
import moment from 'moment';
const MonthPicker = ({ onChange, ...props }) => (
<select onChange={onChange} id="select-month">{ optionsFor("month", props.date) }</select>
);
const DayPicker = ({ onChange, ...props }) => (
<select onChange={onChange} id="select-date">{ optionsFor("day", props.date) }</select>
);
const YearPicker = ({ onChange, ...props }) => (
<select onChange={onChange} id="select-year">{ optionsFor("year", props.date) }</select>
);
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
const startYear = 1930;
const endYear = 2018;
function optionsFor(field, selectedDate) {
if (field === 'year') {
selected = selectedDate.year();
return [...Array(endYear-startYear).keys()].map((item, i) => {
var isSelected = (startYear + item) == selected;
return (
<option value={startYear + item} selected={isSelected ? 'selected' : ''}>{startYear + item}</option>
);
});
}
else if (field === 'month') {
selected = selectedDate.month();
return months.map((item, i) => {
var isSelected = i == selected;
return (
<option value={i} selected={isSelected ? 'selected' : ''}>{item}</option>
);
});
}
else if (field === 'day') {
var selected = selectedDate.date();
var firstDay = 1;
var lastDay = moment(selectedDate).add(1, 'months').date(1).subtract(1, 'days').date() + 1;
return [...Array(lastDay-firstDay).keys()].map((item, i) => {
var isSelected = (item + 1) == selected;
return (
<option value={item + 1} selected={isSelected ? 'selected': ''}>{item + 1}</option>
)
});
}
}
export default class DatePicker extends Component {
constructor(props) {
super(props);
this.state = {
date: props.date
};
this.onChange = this.onChange.bind(this);
}
onChange(event) {
var month = document.getElementById('select-month').value;
var day = document.getElementById('select-date').value;
var year = document.getElementById('select-year').value;
var newDate = moment().year(year).month(month).date(day);
this.setState({ date: newDate })
this.props.onChange(newDate);
}
render() {
return (
<div>
<MonthPicker date={this.state.date} onChange={this.onChange} />
<DayPicker date={this.state.date} onChange={this.onChange} />
<YearPicker date={this.state.date} onChange={this.onChange} />
</div>
)
}
} | jc4p/natal-charts | app/src/components/DatePicker.js | JavaScript | mit | 2,568 |
'use strict';
angular.module('users').factory('Permissions', ['Authentication', '$location',
function(Authentication, $location) {
// Permissions service logic
// ...
// Public API
return {
//check if user suits the right permissions for visiting the page, Otherwise go to 401
userRolesContains: function (role) {
if (!Authentication.user || Authentication.user.roles.indexOf(role) === -1) {
return false;
} else {
return true;
}
},
//This function returns true if the user is either admin or maintainer
adminOrMaintainer: function () {
if (Authentication.user && (Authentication.user.roles.indexOf('admin')> -1 || Authentication.user.roles.indexOf('maintainer')> -1)) {
return true;
} else {
return false;
}
},
isPermissionGranted: function (role) {
if (!Authentication.user || Authentication.user.roles.indexOf(role) === -1) {
$location.path('/401');
}
},
isAdmin: function () {
if (Authentication.user && (Authentication.user.roles.indexOf('admin') > -1)) {
return true;
} else {
return false;
}
}
};
}
]); | hacor/gamwbras | public/modules/users/services/permissions.client.service.js | JavaScript | mit | 1,228 |
import $ from 'jquery';
import keyboard from 'virtual-keyboard';
$.fn.addKeyboard = function () {
return this.keyboard({
openOn: null,
stayOpen: false,
layout: 'custom',
customLayout: {
'normal': ['7 8 9 {c}', '4 5 6 {del}', '1 2 3 {sign}', '0 0 {dec} {a}'],
},
position: {
// null (attach to input/textarea) or a jQuery object (attach elsewhere)
of: null,
my: 'center top',
at: 'center top',
// at2 is used when "usePreview" is false (centers keyboard at the bottom
// of the input/textarea)
at2: 'center top',
collision: 'flipfit flipfit'
},
reposition: true,
css: {
input: 'form-control input-sm',
container: 'center-block dropdown-menu',
buttonDefault: 'btn btn-default',
buttonHover: 'btn-light',
// used when disabling the decimal button {dec}
// when a decimal exists in the input area
buttonDisabled: 'enabled',
},
});
};
| kamillamagna/NMF_Tool | app/javascript/components/addKeyboard.js | JavaScript | mit | 971 |
require 'nokogiri'
require 'ostruct'
require 'active_support/core_ext/string'
require 'active_support/core_ext/date'
module Lifebouy
class MalformedRequestXml < StandardError
def initialize(xml_errors)
@xml_errors = xml_errors
end
def message
"The request contains the following errors:\n\t#{@xml_errors.join("\n\t")}"
end
end
class MalformedResponseData < MalformedRequestXml
def message
"The response contains the following errors:\n\t#{@xml_errors.join("\n\t")}"
end
end
class RequestHandler
attr_reader :request_error, :schema, :request_doc, :response_error
attr_accessor :response_data
def initialize(wsdl_file, request_xml)
@wsdl = Nokogiri::XML(File.read(wsdl_file))
# Find the root schema node
schema_namespace = @wsdl.namespaces.select { |k,v| v =~ /XMLSchema/ }.first
target_namespace_url = @wsdl.root['targetNamespace']
@target_namespace = @wsdl.namespaces.select { |k,v| v == target_namespace_url}.first
@schema_prefix = schema_namespace.first.split(/:/).last
schema_root = @wsdl.at_xpath("//#{@schema_prefix}:schema").dup
schema_root.add_namespace_definition(@target_namespace.first.split(/:/).last, @target_namespace.last)
# Create a document to store the schema and the parse it into a Schema for validation
@schema_doc = Nokogiri::XML::Document.new
@schema_doc << schema_root
@schema = Nokogiri::XML::Schema(@schema_doc.to_xml)
envelope = Nokogiri::XML(request_xml)
request_data = envelope.at_xpath("//#{envelope.root.namespace.prefix}:Body").first_element_child
@request_doc = Nokogiri::XML::Document.new
@request_doc << request_data
@response_data = OpenStruct.new
end
def validate_request_xml?
begin
validate_request_xml!
return true
rescue MalformedRequestXml => e
@request_error = e
return false
end
end
def validate_request_xml!
request_errors = []
@schema.validate(request_doc).each do |error|
request_errors << "Line #{error.line}: #{error.message}"
end
raise MalformedRequestXml.new(request_errors) unless request_errors.empty?
end
def request_data
@request_data ||= build_request_data
end
def validate_response?
begin
validate_response!
return true
rescue MalformedResponseData => e
@response_error = e
return false
end
end
def validate_response!
raise MalformedResponseData.new(["Empty Responses Not Allowed"]) if response_data.to_h.empty?
@response_xml = nil
response_errors = []
@schema.validate(response_xml).each do |error|
response_errors << "Line #{error.line}: #{error.message}"
end
raise MalformedResponseData.new(response_errors) unless response_errors.empty?
end
def response_xml
@response_xml ||= build_response_xml
end
def response_soap
end
private
def build_response_xml
xml = Nokogiri::XML::Document.new
symbols_and_names = {}
@schema_doc.xpath("//#{@schema_prefix}:element").each do |e_node|
symbols_and_names[e_node[:name].underscore.to_sym] = e_node[:name]
end
xml << ostruct_to_node(@response_data, xml, symbols_and_names)
xml
end
def ostruct_to_node(ostruct, xml, symbols_and_names)
raise MalformedResponseData.new(["Structure Must Contain a Node Name"]) if ostruct.name.blank?
ele = xml.create_element(ostruct.name)
ele.add_namespace_definition(nil, @target_namespace.last)
ostruct.each_pair do |k,v|
next if k == :name
if v.is_a?(OpenStruct)
ele << ostruct_to_node(v, xml, symbols_and_names)
else
ele << create_element_node(xml, symbols_and_names[k], v)
end
end
ele
end
def create_element_node(xml, node_name, value)
t_node = @schema_doc.at_xpath("//#{@schema_prefix}:element[@name='#{node_name}']")
formatted_value = value.to_s
begin
case type_for_element_name(node_name)
when 'integer', 'int'
formatted_value = '%0d' % value
when 'boolean'
formatted_value = (value == true ? 'true' : 'false')
when 'date', 'time', 'dateTime'
formatted_value = value.strftime('%m-%d-%Y')
end
rescue Exception => e
raise MalformedResponseException.new([e.message])
end
to_add = xml.create_element(node_name, formatted_value)
to_add.add_namespace_definition(nil, @target_namespace.last)
to_add
end
def build_request_data
@request_data = node_to_ostruct(@request_doc.first_element_child)
end
def node_to_ostruct(node)
ret = OpenStruct.new
ret[:name] = node.node_name
node.element_children.each do |ele|
if ele.element_children.count > 0
ret[ele.node_name.underscore.to_sym] = node_to_ostruct(ele)
else
ret[ele.node_name.underscore.to_sym] = xml_to_type(ele)
end
end
ret
end
def xml_to_type(node)
return nil if node.text.blank?
case type_for_element_name(node.node_name)
when 'decimal', 'float', 'double'
node.text.to_f
when 'integer', 'int'
node.text.to_i
when 'boolean'
node.text == 'true'
when 'date', 'time', 'dateTime'
Date.parse(node.text)
else
node.text
end
end
def type_for_element_name(node_name)
t_node = @schema_doc.at_xpath("//#{@schema_prefix}:element[@name='#{node_name}']")
raise "No type defined for #{node_name}" unless t_node
t_node[:type].gsub(/#{@schema_prefix}:/, '')
end
end
end | reedswenson/lifebouy | lib/lifebouy/request_handler.rb | Ruby | mit | 5,812 |
/**
* Trait class
*/
function Trait(methods, allTraits) {
allTraits = allTraits || [];
this.traits = [methods];
var extraTraits = methods.$traits;
if (extraTraits) {
if (typeof extraTraits === "string") {
extraTraits = extraTraits.replace(/ /g, '').split(',');
}
for (var i = 0, c = extraTraits.length; i < c; i++) {
this.use(allTraits[extraTraits[i]]);
}
}
}
Trait.prototype = {
constructor: Trait,
use: function (trait) {
if (trait) {
this.traits = this.traits.concat(trait.traits);
}
return this;
},
useBy: function (obj) {
for (var i = 0, c = this.traits.length; i < c; i++) {
var methods = this.traits[i];
for (var prop in methods) {
if (prop !== '$traits' && !obj[prop] && methods.hasOwnProperty(prop)) {
obj[prop] = methods[prop];
}
}
}
}
};
module.exports = Trait;
| azproduction/node-jet | lib/plugins/app/lib/Trait.js | JavaScript | mit | 1,059 |
require 'integrity'
require 'fileutils'
module Integrity
class Notifier
class Artifacts < Notifier::Base
def initialize(commit, config={})
@project = commit.project
super
end
def deliver!
return unless self.commit.successful?
self.publish_artifacts
self.generate_indexes if should_generate_indexes
end
def generate_indexes
Artifacts.generate_index(self.artifact_root, false)
Artifacts.generate_index(File.join(self.artifact_root, @project.name), true)
Artifacts.generate_index(self.artifact_archive_dir, true)
end
def publish_artifacts
self.artifacts.each do |name, config|
next if config.has_key?('disabled') && config['disabled']
artifact_output_dir = File.expand_path(File.join(self.working_dir, config['output_dir']))
if File.exists?(artifact_output_dir)
FileUtils::Verbose.mkdir_p(self.artifact_archive_dir) unless File.exists?(self.artifact_archive_dir)
FileUtils::Verbose.mv artifact_output_dir, self.artifact_archive_dir, :force => true
end
end
end
def artifacts
# If the configuration is missing, try rcov for kicks
@artifacts ||= self.load_config_yaml
@artifacts ||= {'rcov' => { 'output_dir' => 'coverage' }}
@artifacts
end
def artifact_archive_dir
@artifact_archive_dir ||= File.expand_path(File.join(self.artifact_root, @project.name, self.commit.short_identifier))
@artifact_archive_dir
end
def artifact_root
# If the configuration is missing, assume that the export_directory is {integrity_dir}/builds
@artifact_root ||= self.load_artifact_root
@artifact_root ||= Artifacts.default_artifact_path
@artifact_root
end
def working_dir
@working_dir ||= Integrity.config[:export_directory] / "#{Integrity::SCM.working_tree_path(@project.uri)}-#{@project.branch}"
@working_dir
end
def should_generate_indexes
@config.has_key?('generate_indexes') ? @config['generate_indexes'] == '1' : false
end
protected
def load_artifact_root
if @config.has_key?('artifact_root')
root_path = @config['artifact_root']
unless File.exists?(root_path)
default_path = Artifacts.default_artifact_path
Integrity.log "WARNING: Configured artifact_root: #{root_path} does not exist. Using default: #{default_path}"
root_path = default_path
end
end
root_path
end
def load_config_yaml
config = nil
if @config.has_key?('config_yaml')
config_yaml = File.expand_path(File.join(working_dir, @config['config_yaml']))
if File.exists?(config_yaml)
config = YAML.load_file(config_yaml)
else
Integrity.log "WARNING: Configured yaml file: #{config_yaml} does not exist! Using default configuration."
end
end
config
end
class << self
def to_haml
File.read(File.dirname(__FILE__) + "/config.haml")
end
def default_artifact_path
File.expand_path(File.join(Integrity.config[:export_directory], '..', 'public', 'artifacts'))
end
def generate_index(dir, link_to_parent)
hrefs = build_hrefs(dir, link_to_parent)
rendered = render_index(dir, hrefs)
write_index(dir, rendered)
end
def build_hrefs(dir, link_to_parent)
hrefs = {}
Dir.entries(dir).each do |name|
# skip dot files
next if name.match(/^\./)
hrefs[name] = name
hrefs[name] << "/index.html" if File.directory?(File.join(dir, name))
end
hrefs['..'] = '../index.html' if link_to_parent
hrefs
end
def render_index(dir, hrefs)
index_haml = File.read(File.dirname(__FILE__) + '/index.haml')
engine = ::Haml::Engine.new(index_haml, {})
engine.render(nil, {:dir => dir, :hrefs => hrefs})
end
def write_index(dir, content)
index_path = File.join(dir, 'index.html')
File.open(index_path, 'w') {|f| f.write(content) }
end
end
end
register Artifacts
end
end
| subakva/integrity-artifacts | lib/integrity/notifier/artifacts.rb | Ruby | mit | 4,391 |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="http://www.entwicklungshilfe.nrw/typo3conf/ext/wmdb_base_ewh/Resources/Public/img/favicon.ico" type="image/x-icon">
<title>oh-my-zsh Präsentation von Php-Schulung Entwicklungshilfe</title>
<meta name="description" content="oh-my-zsh - Terminal effektiv mit Plugins nutzen PHP-Schulung">
<meta name="author" content="Entwicklungshilfe NRW">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/black.css">
<link rel="stylesheet" href="css/theme/eh.css">
<link rel="stylesheet" href="#" id="theme">
<!-- Code syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
<script type="text/javascript">
if(window.location.search.substring(1)){
document.getElementById("theme").href = "css/theme/"+window.location.search.substring(1)+".css";
}
</script>
</head>
<body>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<h1>oh-my-zsh</h1>
<h3>Entwicklungshilfe</h3>
<p>
<a href="http://entwicklungshilfe.nrw" target="_blank">entwicklungshilfe.nrw</a> / <a href="http://twitter.com/help_for_devs" target="_blank">@help_for_devs</a> /
<a href="https://www.facebook.com/entwicklungshilfe.nrw" target="_blank">FB/entwicklungshilfe.nrw</a><br>
<small>
<a href="#" onclick="document.getElementById('theme').setAttribute('href','css/theme/black.css'); return false;">Black</a>
<a href="#" onclick="document.getElementById('theme').setAttribute('href','css/theme/white.css'); return false;">White</a>
<a href="#" onclick="document.getElementById('theme').setAttribute('href',''); return false;">EH</a>
</small>
</p>
<aside class="notes">
Don't forget notes
</aside>
</section>
<section>
<section>
<p>
<h3>Powerline font</h3>
<a href="https://github.com/powerline/fonts/blob/master/Meslo/Meslo%20LG%20L%20DZ%20Regular%20for%20Powerline.otf" target="_blank">
https://github.com/powerline/fonts/blob/master/Meslo/Meslo%20LG%20L%20DZ%20Regular%20for%20Powerline.otf
</a><br>
press raw and install <br>
<h4>ZSH installieren</h4>
<a href="https://github.com/robbyrussell/oh-my-zsh" target="_blank">https://github.com/robbyrussell/oh-my-zsh</a><br>
curl -L https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh | sh<br>
or<br>
wget https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O - | sh
</p>
</section>
<section>
<h2>Installation</h2>
<h3>Solarized Theme</h3>
<a href="http://ethanschoonover.com/solarized/files/solarized.zip" target="_blank">http://ethanschoonover.com/solarized/files/solarized.zip</a><br>
unpack and in folder "iterm2-colors-solarized" the "Solrized Dark.itermcolors" double click
</section>
<section>
<h2>Installation</h2>
Open iTerm and pres "cmd + ," at colors "Load Presents" dropdown "Solarized dark".
<p>
<img src="img/oh-my-zsh/SOLARIZED-THEME.png" alt="SOLARIZED THEME iTerm">
</p>
</section>
<section>
<h2>Installation</h2>
Set the new font
<p>
<img src="img/oh-my-zsh/font-settings.png" alt="iTerm font setting">
</p>
</section>
<section>
<h2>Installation</h2>
brew install fortune <br>
brew install cowsay <br>
vim .zshrc<br>
ZSH_THEME="agnoster"<br>
plugins=(git jump jira osx z extract chucknorris history zsh-syntax-highlighting vi-mode web-search history-substring-search)<br>
Iterm restart or open new tab. Enter this command<br>
echo -e "\ue0a0 \ue0a1 \ue0a2 \ue0b0 \ue0b1 \ue0b2"
<p>
<img src="img/oh-my-zsh/test-output.png" alt="oh-my-zsh output">
</p>
</section>
</section>
<section>
<section>
<h2>Sources</h2>
Plugin wiki<br>
<a href="https://github.com/robbyrussell/oh-my-zsh/wiki/Plugins" target="_blank">https://github.com/robbyrussell/oh-my-zsh/wiki/Plugins</a><br>
Cheatsheet<br>
<a href="https://github.com/robbyrussell/oh-my-zsh/wiki/Cheatsheet" target="_blank">https://github.com/robbyrussell/oh-my-zsh/wiki/Cheatsheet</a>
</section>
<section>
<h2>Directories</h2>
<table>
<thead>
<tr>
<th>Alias</th>
<th>Command</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><em>alias</em></td>
<td align="left">list all aliases</td>
</tr>
<tr>
<td align="left">..</td>
<td align="left">cd ..</td>
</tr>
<tr>
<td align="left">...</td>
<td align="left">cd ../..</td>
</tr>
<tr>
<td align="left">....</td>
<td align="left">cd ../../..</td>
</tr>
<tr>
<td align="left">.....</td>
<td align="left">cd ../../../..</td>
</tr>
<tr>
<td align="left">/</td>
<td align="left">cd /</td>
</tr>
<tr>
<td align="left"><em>md</em></td>
<td align="left">mkdir -p</td>
</tr>
<tr>
<td align="left"><em>rd</em></td>
<td align="left">rmdir</td>
</tr>
<tr>
<td align="left"><em>d</em></td>
<td align="left">dirs -v (lists last used directories)</td>
</tr>
<tr>
<td align="left"><em>~3</em></td>
<td align="left">cd to dir -v 3</td>
</tr>
</tbody>
</table>
</section>
<section>
<h2>Usefull git alias</h2>
<table>
<thead>
<tr>
<th>Alias</th>
<th>Command</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><em>gst</em></td>
<td align="left">git status</td>
</tr>
<tr>
<td align="left"><em>gf</em></td>
<td align="left">git fetch</td>
</tr>
<tr>
<td align="left"><em>gl</em></td>
<td align="left">git pull</td>
</tr>
<tr>
<td align="left"><em>gp</em></td>
<td align="left">git push</td>
</tr>
<tr>
<td align="left"><em>gaa</em></td>
<td align="left">git add --all</td>
</tr>
<tr>
<td align="left"><em>gco</em></td>
<td align="left">git checkout</td>
</tr>
<tr>
<td align="left"><em>gcmsg</em></td>
<td align="left">git commit -m</td>
</tr>
<tr>
<td align="left"><em>gclean</em></td>
<td align="left">git clean -fd</td>
</tr>
<tr>
<td align="left"><em>gcb</em></td>
<td align="left">git checkout -b</td>
</tr>
<tr>
<td align="left"><em>gcm</em></td>
<td align="left">git checkout master</td>
</tr>
</tbody>
</table>
</section>
<section>
<h2>Jump plugin</h2>
<table>
<thead>
<tr>
<th>Alias</th>
<th>Command</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><em>mark</em></td>
<td align="left">mark actual folder with name as mark</td>
</tr>
<tr>
<td align="left"><em>mark yourname</em></td>
<td align="left">mark actual folder with yourname as mark</td>
</tr>
<tr>
<td align="left"><em>jump yourname</em></td>
<td align="left">jump to folder yourname</td>
</tr>
<tr>
<td align="left"><em>unmark yourname</em></td>
<td align="left">remove</td>
</tr>
</tbody>
</table>
</section>
<section>
<h2>OSX plugin</h2>
<table>
<thead>
<tr>
<th align="left">Command</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><em>tab</em></td>
<td align="left">open the current directory in a new tab</td>
</tr>
<tr>
<td align="left"><em>cdf</em></td>
<td align="left">cd to the current Finder directory</td>
</tr>
</tbody>
</table>
</section>
<section>
<h2>JIRA plugin</h2>
<table>
<thead>
<tr>
<th align="left">Command</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><em>jira</em></td>
<td align="left">Open new issue form in browser</td>
</tr>
<tr>
<td align="left"><em>jira ABC-123</em></td>
<td align="left">Open issue in browser</td>
</tr>
</tbody>
</table>
</section>
<section>
<h2>History plugin</h2>
<table>
<thead>
<tr>
<th align="left">Alias</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><em>h</em></td>
<td align="left">List your command history. Equivalent to using <code>history</code>
</td>
</tr>
<tr>
<td align="left"><em>hsi</em></td>
<td align="left">When called without an argument you will get help on <code>grep</code> arguments</td>
</tr>
</tbody>
</table>
</section>
<section>
<h2>Extract plugin</h2>
<table>
<thead>
<tr>
<th align="left">Alias</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><em>extract filename</em></td>
<td align="left">Extract any compressed file<code>history</code>
</td>
</tr>
</tbody>
</table>
</section>
</section>
<section style="text-align: left;">
<h1>Questions?</h1>
</section>
<section style="text-align: left;">
<h1>Thanks</h1>
</section>
<section style="text-align: left;">
<h1>Follow us!</h1>
<div class="col"><i class="follow-icon"><img src="img/twitter.png" alt="Entwicklungshilfe NRW Twitter"></i> <a href="https://twitter.com/help_for_devs" target="_blank">https://twitter.com/help_for_devs</a></div>
<div class="col"><i class="follow-icon"><img src="img/facebook.png" alt="Entwicklungshilfe NRW Facebook"></i> <a href="https://www.facebook.com/entwicklungshilfe.nrw" target="_blank">https://www.facebook.com/entwicklungshilfe.nrw</a></div>
<div class="col"><i class="follow-icon"><img src="img/github.png" alt="Entwicklungshilfe NRW Github"></i> <a href="https://github.com/entwicklungshilfe-nrw" target="_blank">https://github.com/entwicklungshilfe-nrw</a></div>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.js"></script>
<script>
// Full list of configuration options available at:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: true,
progress: true,
history: true,
center: true,
transition: 'slide', // none/fade/slide/convex/concave/zoom
// Optional reveal.js plugins
dependencies: [
{ src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
{ src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/highlight/highlight.js', async: true, condition: function() { return !!document.querySelector( 'pre code' ); }, callback: function() { hljs.initHighlightingOnLoad(); } },
{ src: 'plugin/zoom-js/zoom.js', async: true },
{ src: 'plugin/notes/notes.js', async: true }
]
});
</script>
<script src="js/ga.js"></script>
</body>
</html>
| Entwicklungshilfe-NRW/Presentations | oh-my-zsh.html | HTML | mit | 19,608 |
import {Component, Input} from '@angular/core';
import {CORE_DIRECTIVES} from '@angular/common';
import {ROUTER_DIRECTIVES, Router} from '@angular/router-deprecated';
import {AuthService} from '../common/auth.service';
@Component({
selector: 'todo-navbar',
templateUrl: 'app/navbar/navbar.component.html',
directives: [ROUTER_DIRECTIVES, CORE_DIRECTIVES]
})
export class NavbarComponent {
@Input() brand: string;
@Input() routes: any[];
name: string;
constructor(private _authService: AuthService, private _router: Router) {
this._authService.profile.subscribe(profile => this.name = profile && profile.name);
}
getName() {
console.log('getName');
return this.name;
}
logout($event: Event) {
$event.preventDefault();
this._authService.logout();
this._router.navigateByUrl('/');
}
isLoggedIn() {
return Boolean(this.name);
}
}
| Boychenko/sample-todo-2016 | clients/angular2/app/navbar/navbar.component.ts | TypeScript | mit | 889 |
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Game = mongoose.model('Game'),
Team = mongoose.model('Team'),
Player = mongoose.model('Player'),
async = require('async');
exports.all = function(req, res) {
Game.find({'played': true}).exec(function(err, games) {
if (err) {
return res.json(500, {
error: 'fucked up grabbing dem games'
});
}
res.json(games);
});
};
exports.logGame = function(req, res, next) {
var loggedGame = req.body;
Game.findAllMatchesBetweenTeams([loggedGame.teams[0].teamId, loggedGame.teams[1].teamId], function(err, games) {
if (err) {
console.log('error finding matchups\n' + err);
res.json(500, 'fucked up finding dem games');
return;
}
var matchedGame;
var teamOneIndex;
var teamTwoIndex;
for (var gameIdx = 0; gameIdx < games.length; gameIdx += 1) {
if (games[gameIdx].teams[0].home === loggedGame.teams[0].home && games[gameIdx].teams[0].teamId.toString() === loggedGame.teams[0].teamId) {
matchedGame = games[gameIdx];
teamOneIndex = 0;
teamTwoIndex = 1;
break;
} else if (games[gameIdx].teams[1].home === loggedGame.teams[0].home && games[gameIdx].teams[1].teamId.toString() === loggedGame.teams[0].teamId) {
matchedGame = games[gameIdx];
teamOneIndex = 1;
teamTwoIndex = 0;
break;
}
}
if (!matchedGame) {
res.json(500, 'no matchup between those teams found');
return;
}
if (matchedGame.played) {
console.log('match already played!');
res.json(500, 'game already played');
return;
}
matchedGame.teams[teamOneIndex].goals = loggedGame.teams[0].goals;
matchedGame.teams[teamOneIndex].events = loggedGame.teams[0].events;
matchedGame.teams[teamTwoIndex].goals = loggedGame.teams[1].goals;
matchedGame.teams[teamTwoIndex].events = loggedGame.teams[1].events;
matchedGame.played = true;
var datePlayed = new Date();
matchedGame.datePlayed = datePlayed;
matchedGame.save(function(err) {
if (err) {
console.log('failed to save game -- ' + matchedGame + ' -- ' + err );
res.json(500, 'error saving game -- ' + err);
} else {
async.series([
function(callback) {
console.log('PROCESSING EVENTS');
processEvents(matchedGame, callback);
},
function(callback) {
console.log('UPDATING STANDINGS');
updateStandings(callback);
}
],
function(err, results) {
if (err) {
res.sendStatus(400);
console.log(err);
} else {
res.sendStatus(200);
}
});
}
});
});
var processEvents = function(game, callback) {
/*jshint -W083 */
var updatePlayerEvents = function(playerEvents, playerCallback) {
console.log('UPDATING EVENTS FOR PLAYER ' + playerEvents.events[0].player);
findOrCreateAndUpdatePlayer(playerEvents, playerEvents.teamId, playerCallback);
};
var processEventsForTeam = function(team, teamCallback) {
console.log('PROCESSING EVENTS FOR ' + team);
var playerEventMap = {};
for (var eventIdx = 0; eventIdx < team.events.length; eventIdx += 1) {
var playerEvent = team.events[eventIdx];
console.log('PROCESSING EVENT ' + playerEvent);
if (playerEventMap[playerEvent.player] === undefined) {
console.log('PLAYER NOT IN MAP, ADDING ' + playerEvent.player);
playerEventMap[playerEvent.player] = {teamId: team.teamId, events: [], gameDate: game.datePlayed};
}
playerEventMap[playerEvent.player].events.push(playerEvent);
}
console.log('player event map created: ' + playerEventMap);
var playerEventMapValues = [];
for (var key in playerEventMap) {
playerEventMapValues.push(playerEventMap[key]);
}
async.each(playerEventMapValues, updatePlayerEvents, function(err) {
if (err) {
teamCallback(err);
} else {
teamCallback();
}
});
};
async.each(game.teams, processEventsForTeam, function(err) {
if (err) {
callback(err);
} else {
callback();
}
});
};
var findOrCreateAndUpdatePlayer = function(playerEvents, teamId, playerCallback) {
console.log('finding/creating player -- ' + playerEvents + ' -- ' + teamId);
Player.findOne({name: playerEvents.events[0].player, teamId: teamId}, function(err, player) {
if (err) {
console.log('error processing events -- ' + JSON.stringify(playerEvents) + ' -- ' + err);
playerCallback(err);
}
if (!player) {
createAndUpdatePlayer(playerEvents, teamId, playerCallback);
} else {
incrementEvents(player, playerEvents, playerCallback);
}
});
};
var createAndUpdatePlayer = function(playerEvents, teamId, playerCallback) {
Player.create({name: playerEvents.events[0].player, teamId: teamId}, function(err, createdPlayer) {
if (err) {
console.log('error creating player while processing event -- ' + JSON.stringify(playerEvents) + ' -- ' + err);
}
incrementEvents(createdPlayer, playerEvents, playerCallback);
});
};
var incrementEvents = function(player, playerEvents, playerCallback) {
var suspended = false;
for (var eventIdx = 0; eventIdx < playerEvents.events.length; eventIdx += 1) {
var eventType = playerEvents.events[eventIdx].eventType;
if (eventType === 'yellow card') {
player.yellows += 1;
if (player.yellows % 5 === 0) {
suspended = true;
}
} else if (eventType === 'red card') {
player.reds += 1;
suspended = true;
} else if (eventType === 'goal') {
player.goals += 1;
} else if (eventType === 'own goal') {
player.ownGoals += 1;
}
}
player.save(function(err) {
if (err) {
console.log('error incrementing event for player -- ' + JSON.stringify(player) + ' -- ' + eventType);
playerCallback(err);
} else {
if (suspended) {
suspendPlayer(player, playerEvents.gameDate, playerCallback);
} else {
playerCallback();
}
}
});
};
var updateStandings = function(callback) {
Team.find({}, function(err, teams) {
if (err) {
console.log('error retrieving teams for standings update -- ' + err);
callback(err);
} else {
resetStandings(teams);
Game.find({'played': true}, null, {sort: {datePlayed : 1}}, function(err, games) {
if (err) {
console.log('error retrieving played games for standings update -- ' + err);
callback(err);
} else {
for (var gameIdx = 0; gameIdx < games.length; gameIdx += 1) {
processGameForStandings(games[gameIdx], teams);
}
saveStandings(teams, callback);
}
});
}
});
};
var saveStandings = function(teams, standingsCallback) {
var saveTeam = function(team, saveCallback) {
team.save(function(err){
if (err) {
console.log('error saving team -- ' + team + ' -- ' + err);
saveCallback(err);
} else {
saveCallback();
}
});
};
async.each(teams, saveTeam, function(err) {
if (err) {
standingsCallback(err);
} else {
standingsCallback();
}
});
};
var resetStandings = function(teams) {
for (var teamIdx in teams) {
teams[teamIdx].wins = 0;
teams[teamIdx].losses = 0;
teams[teamIdx].draws = 0;
teams[teamIdx].points = 0;
teams[teamIdx].goalsFor = 0;
teams[teamIdx].goalsAgainst = 0;
//teams[teamIdx].suspensions = [];
}
};
var processGameForStandings = function(game, teams) {
for (var teamResultIdx = 0; teamResultIdx < game.teams.length; teamResultIdx += 1) {
var teamResult = game.teams[teamResultIdx];
var opponentResult = game.teams[1 - teamResultIdx];
var team;
for (var teamIdx = 0; teamIdx < teams.length; teamIdx += 1) {
if (teams[teamIdx]._id.equals(teamResult.teamId)) {
team = teams[teamIdx];
break;
}
}
team.lastGamePlayed = game.datePlayed;
team.goalsFor += teamResult.goals;
team.goalsAgainst += opponentResult.goals;
if (teamResult.goals > opponentResult.goals) {
team.wins += 1;
team.points += 3;
} else if (teamResult.goals === opponentResult.goals) {
team.draws += 1;
team.points += 1;
} else {
team.losses += 1;
}
}
// game.played=false;
// game.datePlayed=undefined;
// for (var teamIdx = 0; teamIdx < game.teams.length; teamIdx += 1) {
// game.teams[teamIdx].goals = 0;
// game.teams[teamIdx].events = [];
// }
// game.save();
};
var suspendPlayer = function(player, gameDate, suspensionCallback) {
Team.findOne({_id: player.teamId}, function(err, team){
if (err) {
console.log('error loading team to suspend a dude -- ' + player);
suspensionCallback(err);
} else {
if (!team.suspensions) {
team.suspensions = [];
}
team.suspensions.push({player: player.name, dateSuspended: gameDate});
team.save(function(err) {
if (err) {
console.log('error saving suspension 4 dude -- ' + player + ' -- ' + team);
suspensionCallback(err);
} else {
suspensionCallback();
}
});
}
});
};
}; | javi7/epl-98 | packages/custom/league/server/controllers/games.js | JavaScript | mit | 9,754 |
package championpicker.console;
import com.googlecode.lanterna.gui.*;
import com.googlecode.lanterna.TerminalFacade;
import com.googlecode.lanterna.terminal.Terminal;
import com.googlecode.lanterna.terminal.TerminalSize;
import com.googlecode.lanterna.terminal.swing.SwingTerminal;
import com.googlecode.lanterna.gui.GUIScreen;
import com.googlecode.lanterna.gui.dialog.DialogButtons;
import com.googlecode.lanterna.gui.component.Button;
import com.googlecode.lanterna.gui.component.Panel;
import com.googlecode.lanterna.gui.component.Label;
import com.googlecode.lanterna.gui.Window;
import com.googlecode.lanterna.screen.Screen;
import com.googlecode.lanterna.screen.Screen;
import championpicker.Main;
import championpicker.console.mainStartUp;
import championpicker.console.queueWindow;
import javax.swing.JFrame;
public class mainMenu extends Window{
public mainMenu(String name){
super(name);
queueWindow win = new queueWindow();
addComponent(new Button("Queue!", new Action(){
public void doAction(){
System.out.println("Success!");
mainStartUp.gui.showWindow(win, GUIScreen.Position.CENTER);
}}));
}
} | DanielBoerlage/champion-picker | src/championpicker/console/mainMenu.java | Java | mit | 1,150 |
(function(){
'use strict';
angular.module('GamemasterApp')
.controller('DashboardCtrl', function ($scope, $timeout, $mdSidenav, $http) {
$scope.users = ['Fabio', 'Leonardo', 'Thomas', 'Gabriele', 'Fabrizio', 'John', 'Luis', 'Kate', 'Max'];
})
})(); | jswaldon/gamemaster | public/app/dashboard/dashboard.ctrl.js | JavaScript | mit | 273 |
require 'byebug'
module Vorm
module Validatable
class ValidationError
def clear_all
@errors = Hash.new { |k, v| k[v] = [] }
end
end
end
end
class Valid
include Vorm::Validatable
def self.reset!
@validators = nil
end
end
describe Vorm::Validatable do
before { Valid.reset! }
context "class methods" do
subject { Valid }
describe ".validates" do
it { is_expected.to respond_to(:validates) }
it "raises argument error when given arg is not string" do
expect { subject.validates(:email) }
.to raise_error(ArgumentError, "Field name must be a string")
end
it "raises argument error when no block given" do
expect { subject.validates("email") }
.to raise_error(ArgumentError, "You must provide a block")
end
it "stores a validator" do
subject.validates("email") { "required" }
expect(subject.instance_variable_get('@validators')["email"].length).to be(1)
end
it "stores multiple validators" do
subject.validates("email") { "required" }
subject.validates("email") { "not valid" }
subject.validates("password") { "required" }
expect(subject.instance_variable_get('@validators')["email"].length).to be(2)
expect(subject.instance_variable_get('@validators')["password"].length).to be(1)
end
end
end
context "instance methods" do
subject { Valid.new }
before { subject.errors.clear_all }
describe ".validate!" do
it { is_expected.to respond_to(:validate!) }
it "adds errors when invalid" do
Valid.validates("email") { true }
expect { subject.validate! }.to change { subject.errors.on("email").length }.by(1)
end
it "adds the validation messages to errors for the right field" do
Valid.validates("email") { "not valid" }
subject.valid?
expect(subject.errors.on("email")).to eq(["not valid"])
end
it "adds validation messages to each field when invalid" do
Valid.validates("email") { "required" }
Valid.validates("email") { "not valid" }
Valid.validates("password") { "too short" }
subject.validate!
expect(subject.errors.on("email").length).to be(2)
expect(subject.errors.on("password").length).to be(1)
expect(subject.errors.on("email")).to eq(["required", "not valid"])
expect(subject.errors.on("password")).to eq(["too short"])
end
end
describe ".valid?" do
it { is_expected.to respond_to(:valid?) }
it "calls .validate!" do
expect(subject).to receive(:validate!)
subject.valid?
end
it "calls .errors.empty?" do
expect(subject.errors).to receive(:empty?)
subject.valid?
end
it "returns true when no validations" do
expect(subject).to be_valid
end
it "returns true when validations pass" do
Valid.validates("email") { nil }
expect(subject).to be_valid
end
it "returns false when validations fail" do
Valid.validates("email") { "required" }
expect(subject).not_to be_valid
end
end
end
end
| vastus/vorm | spec/lib/vorm/validatable_spec.rb | Ruby | mit | 3,216 |
module Embratel
class PhoneBill
attr_reader :payables
def initialize(path)
@payables = CSVParser.parse(path)
end
def calls
@calls ||= payables.select(&:call?)
end
def fees
@fees ||= payables.select(&:fee?)
end
def total
@total ||= payables.inject(0) { |sum, payable| sum += payable.cost.to_f }
end
end
end
| mpereira/embratel | lib/embratel/phone_bill.rb | Ruby | mit | 374 |