code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
/*
* Copyright (c) 2009-2015 farmafene.com
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.farmafene.commons.j2ee.tools.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.sql.ConnectionEvent;
import javax.sql.ConnectionEventListener;
import javax.sql.PooledConnection;
import javax.sql.StatementEvent;
import javax.sql.StatementEventListener;
/**
* @author vlopez
*
*/
public class Connection2PooledConnection implements PooledConnection, PooledConnectionSubject, StatementEventListener {
private Connection connection;
private List<StatementEventListener> statementEventListeners;
private List<ConnectionEventListener> connectionEventListeners;
private final Set<PreparedStatement> preparedStatements;
/**
*
*/
private Connection2PooledConnection() {
this.statementEventListeners = new LinkedList<StatementEventListener>();
this.connectionEventListeners = new LinkedList<ConnectionEventListener>();
this.preparedStatements = new HashSet<PreparedStatement>();
addStatementEventListener(this);
}
/**
* Constuctor parametrizado
*
* @param connection
* @throws SQLException
*/
public Connection2PooledConnection(final Connection connection) throws SQLException {
this();
if (connection == null) {
throw new SQLException("Connection must be not null");
}
this.connection = new Connection4ConnectionPooled(connection, this);
}
/**
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()).append("={");
if (this.connection != null) {
sb.append("connection=");
sb.append(this.connection);
sb.append(", ");
}
if (this.statementEventListeners != null) {
sb.append("statementEventListeners=");
sb.append(this.statementEventListeners.size());
sb.append(", ");
}
if (this.connectionEventListeners != null) {
sb.append("connectionEventListeners=");
sb.append(this.connectionEventListeners.size());
sb.append(", ");
}
if (this.preparedStatements != null) {
sb.append("preparedStatements=");
sb.append(this.preparedStatements.size());
}
sb.append("}");
return sb.toString();
}
/**
* {@inheritDoc}
*
* @see javax.sql.PooledConnection#getConnection()
*/
@Override
public Connection getConnection() throws SQLException {
return this.connection;
}
/**
* {@inheritDoc}
*
* @see javax.sql.PooledConnection#addConnectionEventListener(javax.sql.
* ConnectionEventListener)
*/
@Override
public void addConnectionEventListener(final ConnectionEventListener listener) {
synchronized (this.connectionEventListeners) {
final List<ConnectionEventListener> list = new LinkedList<ConnectionEventListener>(this.connectionEventListeners);
list.add(listener);
this.connectionEventListeners = list;
}
}
/**
* {@inheritDoc}
*
* @see javax.sql.PooledConnection#removeConnectionEventListener(javax.sql.
* ConnectionEventListener)
*/
@Override
public void removeConnectionEventListener(final ConnectionEventListener listener) {
synchronized (this.connectionEventListeners) {
final List<ConnectionEventListener> list = new LinkedList<ConnectionEventListener>(this.connectionEventListeners);
list.remove(listener);
this.connectionEventListeners = list;
}
}
/**
* {@inheritDoc}
*
* @see javax.sql.PooledConnection#addStatementEventListener(javax.sql.
* StatementEventListener)
*/
@Override
public void addStatementEventListener(final StatementEventListener listener) {
synchronized (this.statementEventListeners) {
final List<StatementEventListener> list = new LinkedList<StatementEventListener>(this.statementEventListeners);
list.add(listener);
this.statementEventListeners = list;
}
}
/**
* {@inheritDoc}
*
* @see javax.sql.PooledConnection#removeStatementEventListener(javax.sql.
* StatementEventListener)
*/
@Override
public void removeStatementEventListener(final StatementEventListener listener) {
synchronized (this.statementEventListeners) {
final List<StatementEventListener> list = new LinkedList<StatementEventListener>(this.statementEventListeners);
list.remove(listener);
this.statementEventListeners = list;
}
}
/**
* {@inheritDoc}
*
* @see com.farmafene.aurius.mngt.jdbc.PooledConnectionSubject#connectionClosed
* (javax.sql.ConnectionEvent)
*/
@Override
public void connectionClosed(final SQLException e) {
List<ConnectionEventListener> list = null;
synchronized (this.connectionEventListeners) {
list = this.connectionEventListeners;
}
final ConnectionEvent event = new ConnectionEvent(this, e);
for (final ConnectionEventListener l : list) {
l.connectionClosed(event);
}
}
/**
* {@inheritDoc}
*
* @see com.farmafene.aurius.mngt.jdbc.PooledConnectionSubject#
* connectionErrorOccurred(javax.sql.ConnectionEvent)
*/
@Override
public void connectionErrorOccurred(final SQLException e) {
List<ConnectionEventListener> list = null;
synchronized (this.connectionEventListeners) {
list = this.connectionEventListeners;
}
final ConnectionEvent event = new ConnectionEvent(this, e);
for (final ConnectionEventListener l : list) {
l.connectionErrorOccurred(event);
}
}
/**
* {@inheritDoc}
*
* @see com.farmafene.aurius.mngt.jdbc.PooledConnectionSubject#statementClosed
* (javax.sql.StatementEvent)
*/
@Override
public void statementClosed(final PreparedStatement stmt, final SQLException e) {
List<StatementEventListener> list = null;
synchronized (this.statementEventListeners) {
list = this.statementEventListeners;
}
final StatementEvent event = new StatementEvent(this, stmt, e);
for (final StatementEventListener l : list) {
l.statementClosed(event);
}
}
/**
* {@inheritDoc}
*
* @see com.farmafene.aurius.mngt.jdbc.PooledConnectionSubject#addStatement(java.sql.PreparedStatement)
*/
@Override
public void addStatement(final PreparedStatement pstmt) {
if (null == this.preparedStatements) {
return;
}
// FIXME!!! Aquí empieza el caché
System.out.println("addStatement(" + pstmt + ")");
}
/**
* {@inheritDoc}
*
* @see javax.sql.StatementEventListener#statementClosed(javax.sql.StatementEvent
* )
*/
@Override
public void statementClosed(final StatementEvent event) {
System.out.println("statementClosed(" + event + ")");
try {
event.getStatement().close();
} catch (final SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* {@inheritDoc}
*
* @see javax.sql.StatementEventListener#statementErrorOccurred(javax.sql.StatementEvent)
*/
@Override
public void statementErrorOccurred(final StatementEvent event) {
System.out.println("statementErrorOccurred(" + event + ")");
}
/**
* {@inheritDoc}
*
* @see com.farmafene.aurius.mngt.jdbc.PooledConnectionSubject#statementErrorOccurred
* (javax.sql.StatementEvent)
*/
@Override
public void statementErrorOccurred(final PreparedStatement stmt, final SQLException e) {
List<StatementEventListener> list = null;
synchronized (this.statementEventListeners) {
list = this.statementEventListeners;
}
final StatementEvent event = new StatementEvent(this, stmt, e);
for (final StatementEventListener l : list) {
l.statementErrorOccurred(event);
}
}
/**
* {@inheritDoc}
*
* @see javax.sql.PooledConnection#close()
*/
@Override
public void close() throws SQLException {
SQLException th = null;
try {
this.connection.close();
} catch (final SQLException e) {
th = e;
throw th;
} catch (final Throwable t) {
th = new SQLException(t);
throw th;
} finally {
this.connection = null;
}
}
}
|
venanciolm/commons-j2ee-tools
|
src/main/java/com/farmafene/commons/j2ee/tools/jdbc/Connection2PooledConnection.java
|
Java
|
mit
| 9,383
|
<?php
namespace Surume\Console\Client\Boot;
use ReflectionClass;
use Surume\Console\Client\ConsoleClientInterface;
use Surume\Support\StringSupport;
class ConsoleBoot
{
/**
* @var mixed[]
*/
protected $controllerParams;
/**
* @var string
*/
protected $controllerClass;
/**
* @var string[]
*/
protected $params;
/**
*
*/
public function __construct()
{
$this->controllerParams = [];
$this->controllerClass = '\\Surume\\Console\\Client\\ConsoleClient';
$this->params = [
'prefix' => 'Surume',
'name' => 'Undefined'
];
}
/**
*
*/
public function __destruct()
{
unset($this->controllerParams);
unset($this->controllerClass);
unset($this->params);
}
/**
* @param string $class
* @return ProcessBoot
*/
public function controller($class)
{
$this->controllerClass = $class;
return $this;
}
/**
* @param mixed[] $args
* @return ProcessBoot
*/
public function constructor($args)
{
$this->controllerParams = $args;
return $this;
}
/**
* @param string[] $params
* @return ProcessBoot
*/
public function params($params)
{
$this->params = array_merge($this->params, $params);
return $this;
}
/**
* @param string $path
* @return ConsoleClientInterface
*/
public function boot($path)
{
$core = require(
realpath($path) . '/bootstrap/ConsoleClient/bootstrap.php'
);
$controller = (new ReflectionClass(
StringSupport::parametrize($this->controllerClass, $this->params)
))
->newInstanceArgs(
array_merge($this->controllerParams)
);
$controller
->setCore($core);
$core->config(
$controller->internalConfig($core)
);
$controller
->internalBoot($core);
$core
->boot();
$controller
->internalConstruct($core);
return $controller;
}
}
|
khelle/surume
|
src/Console/Client/Boot/ConsoleBoot.php
|
PHP
|
mit
| 2,192
|
#!/bin/bash
#
# author : Didier BONNEFOI <dbonnefoi@gmail.com>
#
[ -z "$BIN_OVS_VSCTL" ] && BIN_OVS_VSCTL=$(which ovs-vsctl)
# create a bridge in OVS
# usage : ovs_add_bridge <bridge>
function ovs_add_bridge
{
local ret=
_log_debug "OVS: adding bridge $1"
[ $# -lt 1 ] && echo "$_ERR_NO_BRIDGE_DEFINED" && return 1
$BIN_OVS_VSCTL -- --may-exist add-br $1
ret=$?
_log_debug "ret ovs_add_bridge=$ret"
return $ret
}
# remove a bridge from OVS
# usage : ovs_remove_bridge <bridge>
function ovs_remove_bridge
{
local ret=
_log_debug "OVS: removing bridge $1"
[ $# -lt 1 ] && echo "$_ERR_NO_BRIDGE_DEFINED" && return 1
$BIN_OVS_VSCTL del-br $1
ret=$?
_log_debug "ret ovs_remove_bridge=$ret"
}
# return ports binded to specified bridge
# usage : ovs_bridge_list_ports <bridge>
function ovs_bridge_list_ports
{
local brname=$1
$BIN_OVS_VSCTL list-ports $brname
}
# add/remove bridges from host's OpenVSwitch
# usage : ovs_set_host_bridge start|stop
function ovs_set_host_bridge
{
[ -z "$HOST_PETH" ] && echo "HOST_PETH not defined" && return 1
[ -z "$HOST_BRIDGE" ] && echo "HOST_BRIDGE not defined" && return 1
echo -e "\n== OVS : bridge's host $HOST_PETH/$HOST_BRIDGE ==\n"
case $1 in
start)
_log_debug "adding NIC $PHY_ETH to bridge $HOST_BRIDGE"
ovs_add_bridge $HOST_BRIDGE
$BIN_OVS_VSCTL -- --may-exist add-port $HOST_BRIDGE $HOST_PETH
# echo "OVS: removing OVS's ports on bridge $HOST_BRIDGE"
# for p in $(ovs_bridge_list_ports $HOST_BRIDGE | grep -v $HOST_PETH);
# do
# echo "- removing port $p"
# $BIN_OVS_VSCTL del-port $p
# done
;;
stop)
ovs_remove_bridge $HOST_BRIDGE
;;
*)
echo "start|stop"
;;
esac
return 0
}
# add/remove VM's bridges from OpenVSwitch configuration
# usage :
# start : ovs_set_VM_bridge <mode> <vbrname> <vbrIP>
# stop : ovs_set_VM_bridge <mode> <vbrname>
# mode : start|stop
# vbrname : bridge name, like vbr.123
# vbrIP : A.B.C.D (gateway for VM binded on this bridge)
function ovs_set_VM_bridge
{
local mode=$1
local vbrname=$2
local vbrIP=$3
[ "$vbrname" == "" ] && echo "vbrname missing" && return 1
local rule_for_dhcp="-host 255.255.255.255 $vbrname"
echo -e "\n== vbrname=$vbrname / vbrIP=$vbrIP ==\n"
case $mode in
start)
[ "$vbrIP" == "" ] && echo "vbrIP missing" && return 1
bridge_create $vbrname $vbrIP
route add $rule_for_dhcp
bridge_exists $vbrname && ovs_add_bridge $vbrname
echo "OVS ports on bridge $vbrname"
for p in $($BIN_OVS_VSCTL list-ports $vbrname)
do
# echo "- removing port $p"
# $BIN_OVS_VSCTL del-port $p
echo "- port $p present"
done
;;
# stop|forcestop)
stop)
local VMports=$(ovs_bridge_list_ports $vbrname)
echo -e "VMports=\n"$VMports
if [ "$VMports" == "" ]; then
ovs_remove_bridge $vbrname
bridge_delete $vbrname
else
echo "opened ports or bad bridge"
# forcing system to delete bridge
#if [ "$mode" == "forcestop" ]; then
# ovs_remove_bridge $vbrname
# bridge_delete $vbrname
#fi
fi
;;
*)
echo "start|stop"
;;
esac
}
# wrapper to add/remove all configured bridges
# usage : ovs_set_VM_bridges start|stop
function ovs_set_VM_bridges
{
local mode=$1
local br_conf=
local vbrname=
local vbrIP=
[ -z "$BRIDGES_CONF" ] && echo "BRIDGES_CONF not defined" && return 1
for br_conf in $BRIDGES_CONF
do
vbrname=$(echo $br_conf | cut -d'|' -f1)
vbrIP=$(echo $br_conf | cut -d'|' -f2)
ovs_set_VM_bridge $mode $vbrname $vbrIP
done
}
# wrapper to show OVS configuration
function ovs_show
{
$BIN_OVS_VSCTL show
}
|
bonidier/xen4-toolbox
|
ovs-bridges-maker/inc/bridge-OVS.lib.sh
|
Shell
|
mit
| 3,676
|
const jsonfile = require('jsonfile')
const stats = require("stats-lite");
const commandLineArgs = require("command-line-args");
const mqtt = require("mqtt");
const stringify = require("csv-stringify");
const fs = require("fs");
const client = mqtt.connect("mqtt://127.0.0.1:1883");
const options = commandLineArgs([
{ name: "sub_qos", type: Number },
{ name: "file", type: String, multiple: false, defaultOption: true }
]);
if (!options.file || options.sub_qos === undefined) {
console.error("You must specify --sub_qos and provide file for dump!");
process.exit(1)
}
let devices = {};
client.on("connect", () => {
client.subscribe("qos_testing/#", {
qos: options.sub_qos
});
});
client.on("message", (topic, message) => {
const device = topic.split("/")[1];
const i = parseInt(message.toString());
const ts = process.hrtime();
if(!devices[device]) {
devices[device] = {
last_i: i,
last_timestamp: ts,
messages: [ [Date.now(), i] ],
intervals: [],
seen: [],
duplicates: [],
out_of_order: []
}
} else {
let diff = process.hrtime(devices[device].last_timestamp);
diff = diff[0]*1000 + diff[1]/1000000.0;
devices[device].intervals.push(diff);
if (devices[device].seen.indexOf(i) > -1) {
devices[device].duplicates.push([Date.now(), i]);
} else if (devices[device].last_i >= i) {
devices[device].out_of_order.push([Date.now(), i]);
}
devices[device].last_i = i;
devices[device].seen.push(i);
devices[device].last_timestamp = ts;
devices[device].messages.push([Date.now(), i]);
}
});
setInterval(function() {
Object.keys(devices).forEach((device) => {
let d = devices[device];
let last_1k = d.intervals.slice(Math.max(0, d.intervals.length - 1000));
console.log("=====");
console.log("Status for device #" + device + " (stats for last 1k msgs)");
console.log("Msgs rcvd:", d.messages.length);
console.log("i:", d.last_i);
console.log("Mean interval:", stats.mean(last_1k));
console.log("stddev interval:", stats.stdev(last_1k));
console.log("95th percentile interval:", stats.percentile(last_1k, 0.95));
console.log("max interval:", Math.max(...last_1k));
console.log("number of duplicates:", d.duplicates.length);
console.log("number of out_of_order:", d.out_of_order.length);
});
}, 2000);
function dump(reason, add) {
console.log("Dumping state to " + options.file + ".json and " + options.file + "_intervals.csv");
jsonfile.writeFileSync(options.file + ".json", devices);
stringify([].concat.apply([], Object.keys(devices).map((device) => {
return devices[device].intervals.map((int) => {
return [device, int];
});
})), (err, out) => {
console.log(err);
fs.writeFileSync(options.file + "_intervals.csv", out);
console.log("Try running octave-cli --eval=\"hist(csvread('"+options.file+"_intervals.csv')(:,2), 25)\" --persist");
if(reason) {
console.log("Quiting because:", reason);
if(reason == "EXCEPTION") {
console.log(add);
}
process.exit();
}
});
}
process.on("SIGINT", dump.bind(null, "SIGINT"));
process.on("SIGHUP", dump.bind(null, false));
process.on("uncaughtException", dump.bind(null, "EXCEPTION"));
|
kacperzuk/mqtt_qos_analyzer
|
index.js
|
JavaScript
|
mit
| 3,536
|
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './heroFinder/heroFinder.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
|
postfab/postfab.github.io
|
src/main.ts
|
TypeScript
|
mit
| 384
|
#include <fstream>
#include <iostream>
#include "cmd_flags.h"
#include "filenames.h"
#include "simplify_points.h"
using std::string;
using cflags::Require;
DEFINE_string(filenames, kRequired, "", "The input filenames");
DEFINE_string(output_path, kOptional, ".", "The output path");
DEFINE_int(dim, kOptional, 256, "The maximum resolution");
DEFINE_float(offset, kOptional, 0.55f, "The offset value for handing thin shapes");
DEFINE_bool(avg_points, kOptional, true, "Average points as output");
DEFINE_bool(verbose, kOptional, true, "Output logs");
// The points must have normals! Can not deal with labela and feature! (TODO)
int main(int argc, char* argv[]) {
bool succ = cflags::ParseCmd(argc, argv);
if (!succ) {
cflags::PrintHelpInfo("\nUsage: simplify_points");
return 0;
}
// file path
string file_path = FLAGS_filenames;
string output_path = FLAGS_output_path;
if (output_path != ".") mkdir(output_path);
else output_path = extract_path(file_path);
output_path += "/";
vector<string> all_files;
get_all_filenames(all_files, file_path);
//#pragma omp parallel for
SimplifyPoints simplify_pts(FLAGS_dim, FLAGS_avg_points, FLAGS_offset);
for (int i = 0; i < all_files.size(); i++) {
string error_msg = simplify_pts.set_point_cloud(all_files[i]);
if (!error_msg.empty()) {
std::cout << error_msg << std::endl;
continue;
}
simplify_pts.simplify();
string filename = extract_filename(all_files[i]);
if (FLAGS_verbose) {
std::cout << "Processing: " + filename + "\n";
}
simplify_pts.write_point_cloud(output_path + filename + ".smp.points");
}
std::cout << "Done: " << FLAGS_filenames << std::endl;
return 0;
}
|
microsoft/O-CNN
|
octree/tools/simplify_points.cpp
|
C++
|
mit
| 1,715
|
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
# Password authenticatable
t.string :username
t.string :email
t.string :encrypted_password
# Confirmable
t.string :unconfirmed_email
t.string :confirmation_token
t.datetime :confirmation_token_sent_at
t.string :activated_at
# Rememberable
t.string :remember_token # Added for test. This field does not exist in the default settings.
t.datetime :remember_created_at
# Lockable
t.integer :failed_attempts, default: 0, null: false
t.datetime :locked_at
t.string :unlock_token
# Recoverable
t.string :reset_password_token
t.datetime :reset_password_token_sent_at
# Trackable
t.integer :login_count, default: 0, null: false
t.datetime :current_login_at
t.datetime :last_login_at
t.string :current_login_ip
t.string :last_login_ip
t.timestamps
end
add_index :users, :username, unique: true
add_index :users, :email, unique: true
add_index :users, :confirmation_token, unique: true
add_index :users, :unlock_token, unique: true
add_index :users, :reset_password_token, unique: true
end
end
|
kentaroi/goma
|
test/rails_app/db/migrate/20140524062919_create_users.rb
|
Ruby
|
mit
| 1,260
|
using DragonSpark.Model.Operations;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;
namespace DragonSpark.Application.Security.Identity.Model.Authenticators;
public interface IAddExternalSignin : ISelecting<ClaimsPrincipal, IdentityResult?> {}
|
DragonSpark/Framework
|
DragonSpark.Application/Security/Identity/Model/Authenticators/IAddExternalSignin.cs
|
C#
|
mit
| 267
|
package jutt.com.zcalenderviewextended.day;
import java.util.Calendar;
import java.util.List;
public interface WeekViewLoader {
/**
* Convert a date into a double that will be used to reference when you're loading data.
*
* All periods that have the same integer part, define one period. Dates that are later in time
* should have a greater return value.
*
* @param instance the date
* @return The period index in which the date falls (floating point number).
*/
double toWeekViewPeriodIndex(Calendar instance);
/**
* Load the events within the period
* @param periodIndex the period to load
* @return A list with the events of this period
*/
List<? extends WeekViewEvent> onLoad(int periodIndex);
}
|
Zulqurnain/ZCalenderViewExtended
|
zcalenderviewextended/src/main/java/jutt/com/zcalenderviewextended/day/WeekViewLoader.java
|
Java
|
mit
| 779
|
class Page
include PageObject
expected_title "Static Elements Page"
expected_element :hello0
link(:hello0, {:text => "Hello", :index => 0})
link(:hello1, {:text => "Hello", :index => 1})
link(:hello2, {:text => "Hello", :index => 2})
value_hooks = define_hooks do
before(:value).call(:before_callback)
after(:value).call(:after_callback)
before(:value=).call(:before_callback)
after(:value=).call(:after_callback)
end
text_field(:text_field_id, :id => "text_field_id", hooks: value_hooks)
text_field(:text_field_class, :class => "text_field_class")
text_field(:text_field_name, :name => "text_field_name")
text_field(:text_field_xpath, :xpath => "//input[@type='text']")
text_field(:text_field_css, :css => "input[type='text']")
text_field(:text_field_tag_name, :tag_name => "input[type='text']")
text_field(:text_field_index, :index => 0)
text_field(:text_field_text, :text => "")
text_field(:text_field_value, :value => "")
text_field(:text_field_label, :label => "Text Field")
text_field(:text_field_title, :title => 'text_field_title')
text_field(:text_field_data_field, :data_field => 'title')
text_field(:text_field_class_index, :class => "text_field_class", :index => 0)
text_field(:text_field_name_index, :name => "text_field_name", :index => 0)
text_field(:text_field_onfocus, :id => "onfocus_text_field")
text_field(:text_field_unfocus, :id => "unfocus_text_field")
text_area(:text_area_id, :id => "text_area_id")
text_area(:text_area_class, :class => "text_area_class")
text_area(:text_area_css, :css => ".text_area_class")
text_area(:text_area_name, :name => "text_area_name")
text_area(:text_area_xpath, :xpath => "//textarea")
text_area(:text_area_tag_name, :tag_name => "textarea")
text_area(:text_area_index, :index => 0)
text_area(:text_area_text, :text => "")
text_area(:text_area_value, :value => "")
text_area(:text_area_class_index, :class => "text_area_class", :index => 0)
text_area(:text_area_name_index, :name => "text_area_name", :index => 0)
text_area(:text_area_label, :label => "Text Area")
hidden_field(:hidden_field_id, :id => "hidden_field_id")
hidden_field(:hidden_field_class, :class => "hidden_field_class")
hidden_field(:hidden_field_css, :css => ".hidden_field_class")
hidden_field(:hidden_field_name, :name => "hidden_field_name")
hidden_field(:hidden_field_xpath, :xpath => "//input[@type='hidden']")
hidden_field(:hidden_field_tag_name, :tag_name => "input[type='hidden']")
hidden_field(:hidden_field_index, :index => 0)
hidden_field(:hidden_field_text, :text => "")
hidden_field(:hidden_field_value, :value => "12345")
hidden_field(:hidden_field_class_index, :class => "hidden_field_class", :index => 0)
hidden_field(:hidden_field_name_index, :name => "hidden_field_name", :index => 0)
link(:google_search_id, :id => "link_id")
link(:google_search_name, :name => "link_name")
link(:google_search_class, :class => "link_class")
link(:google_search_css, :css => ".link_class")
link(:google_search_xpath, :xpath => "//a[text()='Google Search']")
link(:google_search_link, :link => "Google Search")
link(:google_search_link_text, :link_text => "Google Search")
link(:google_search_href, :href => "success.html")
link(:google_search_text, :text => "Google Search")
link(:google_search_index, :index => 0)
link(:google_search_title, :title => "link_title")
select_list(:sel_list_id, :id => "sel_list_id")
select_list(:sel_list_class, :class => "sel_list_class")
select_list(:sel_list_css, :css => ".sel_list_class")
select_list(:sel_list_index, :index => 0)
select_list(:sel_list_name, :name => "sel_list_name")
select_list(:sel_list_value, :value => "option1")
select_list(:sel_list_xpath, :xpath => "//select")
select_list(:sel_list_text, :text => "Test 1")
select_list(:sel_list_class_index, :class => "sel_list_class", :index => 0)
select_list(:sel_list_name_index, :name => "sel_list_name", :index => 0)
select_list(:sel_list_multiple, :id => "sel_list_multiple")
select_list(:sel_list_label, :label => "Select List")
checkbox(:cb_id, :id => 'cb_id')
checkbox(:cb_name, :name => 'cb_name')
checkbox(:cb_class, :class => 'cb_class')
checkbox(:cb_css, :css => '.cb_class')
checkbox(:cb_index, :index => 0)
checkbox(:cb_xpath, :xpath => "//input[@type='checkbox']")
checkbox(:cb_value, :value => '1')
checkbox(:cb_class_index, :class => "cb_class", :index => 0)
checkbox(:cb_name_index, :name => "cb_name", :index => 0)
checkbox(:cb_label, :label => 'Checkbox')
radio_button(:milk_id, :id => 'milk_id')
radio_button(:milk_name, :name => 'milk_name')
radio_button(:milk_class, :class => 'milk_class')
radio_button(:milk_css, :css => '.milk_class')
radio_button(:milk_index, :index => 0)
radio_button(:milk_value, :value => 'Milk')
radio_button(:milk_xpath, :xpath => "//input[@type='radio']")
radio_button(:milk_class_index, :class => "milk_class", :index => 0)
radio_button(:milk_name_index, :name => "milk_name", :index => 0)
radio_button(:milk_label, :label => "Radio")
radio_button(:butter_id, :id => 'butter_id')
radio_button_group(:favorite_cheese, name: 'fav_cheese')
div(:div_id, :id => 'div_id')
div(:div_name, :name => 'div_name')
div(:div_class, :class => 'div_class')
div(:div_css, :css => '.div_class')
div(:div_text, :text => 'page-object rocks!')
div(:div_index, :index => 0)
div(:div_xpath, :xpath => '//div')
div(:div_title, :title => 'div_title')
div(:div_class_index, :class => "div_class", :index => 0)
div(:div_name_index, :name => "div_name", :index => 0)
div(:div_data_entity, :data_entity => "test")
span(:span_id, :id => 'span_id')
span(:span_name, :name => 'span_name')
span(:span_class, :class => 'span_class')
span(:span_css, :css => '.span_class')
span(:span_index, :index => 0)
span(:span_text, :text => 'My alert')
span(:span_title, :title => 'span_title')
span(:span_xpath, :xpath => '//span')
span(:span_class_index, :class => "span_class", :index => 0)
span(:span_name_index, :name => "span_name", :index => 0)
table(:table_id, :id => 'table_id')
table(:table_name, :name => 'table_name')
table(:table_class, :class => 'table_class')
table(:table_css, :css => '.table_class')
table(:table_index, :index => 0)
table(:table_xpath, :xpath => '//table')
table(:table_class_index, :class => "table_class", :index => 0)
table(:table_name_index, :name => "table_name", :index => 0)
table(:table_with_thead_id, :id => 'table_with_thead_id')
table(:table_with_regex, :id => 'table_with_regex')
cell(:cell_id, :id => 'cell_id')
cell(:cell_name, :name => 'cell_name')
cell(:cell_class, :class => 'cell_class')
cell(:cell_css, :css => '.cell_class')
cell(:cell_index, :index => 3)
cell(:cell_text, :text => 'Data4')
cell(:cell_xpath, :xpath => '//table//tr[2]//td[2]')
cell(:cell_class_index, :class => "cell_class", :index => 0)
cell(:cell_name_index, :name => "cell_name", :index => 0)
row(:tr_id, :id => 'tr_id')
row(:tr_class, :class => 'tr_class')
row(:tr_css, :css => '.tr_class')
row(:tr_index, :index => 1)
row(:tr_text, :text => 'Data1 Data2')
row(:tr_xpath, :xpath => '//table//tbody//tr[1]')
row(:tr_class_index, :class => "tr_class", :index => 0)
row(:tr_name_index, :name => "tr_name", :index => 0)
button(:button_id, :id => 'button_id')
button(:button_name, :name => 'button_name')
button(:button_class, :class => 'button_class')
button(:button_css, :css => '.button_class')
button(:button_index, :index => 0)
button(:button_xpath, :xpath=> "//input[@type='submit']")
button(:button_text, :text => 'Click Me')
button(:button_value, :value => 'Click Me')
button(:button_class_index, :class => "button_class", :index => 0)
button(:button_name_index, :name => "button_name", :index => 0)
button(:button_image_id, :id => 'button_image_id')
button(:button_image_src, :src => 'images/submit.gif')
button(:button_image_alt, :alt => 'Submit')
button(:btn_id, :id => 'btn_id')
button(:btn_name, :name => 'btn_name')
button(:btn_class, :class => 'btn_class')
button(:btn_css, :css => '.btn_class')
button(:btn_index, :index => 0)
button(:btn_text, :text => 'Click Me Too')
button(:btn_value, :value => 'Click Me Too')
button(:btn_class_index, :class => "btn_class", :index => 0)
button(:btn_name_index, :name => "btn_name", :index => 0)
button(:disabled_button, :value => 'Disabled')
image(:image_id, :id => 'image_id')
image(:image_name, :name => 'image_name')
image(:image_class, :class => 'image_class')
image(:image_css, :css => '.image_class')
image(:image_index, :index => 1)
image(:image_xpath, :xpath => '//img[2]')
image(:image_alt, :alt => 'image_alt')
image(:image_src, :src => 'images/circle.png')
image(:image_class_index, :class => "image_class", :index => 0)
image(:image_name_index, :name => "image_name", :index => 0)
image(:image_css, :css => ".image_class")
image(:image_broken, :id => "non_existent")
form(:form_id, :id => 'form_id')
form(:form_name, :id => 'form_name')
form(:form_class, :class => 'form_class')
form(:form_css, :css => '.form_class')
form(:form_index, :index => 0)
form(:form_xpath, :xpath => '//form')
form(:form_action, :action => "success.html")
form(:form_class_index, :class => "form_class", :index => 0)
form(:form_name_index, :name => "form_name", :index => 0)
list_item(:li_id, :id => 'li_id')
list_item(:li_name, :name => 'li_name')
list_item(:li_class, :class => 'li_class')
list_item(:li_css, :css => '.li_class')
list_item(:li_index, :index => 0)
list_item(:li_text, :text => 'Item One')
list_item(:li_xpath, :xpath => '//li[1]')
list_item(:li_class_index, :class => "li_class", :index => 0)
list_item(:li_name_index, :name => "li_name", :index => 0)
unordered_list(:ul_id, :id => 'ul_id')
unordered_list(:ul_name, :name => 'ul_name')
unordered_list(:ul_class, :class => 'ul_class')
unordered_list(:ul_css, :css => '.ul_class')
unordered_list(:ul_index, :index => 0)
unordered_list(:ul_xpath, :xpath => '//ul')
unordered_list(:ul_class_index, :class => "ul_class", :index => 0)
unordered_list(:ul_name_index, :name => "ul_name", :index => 0)
ordered_list(:ol_id, :id => 'ol_id')
ordered_list(:ol_name, :name => 'ol_name')
ordered_list(:ol_class, :class => 'ol_class')
ordered_list(:ol_css, :css => '.ol_class')
ordered_list(:ol_index, :index => 0)
ordered_list(:ol_xpath, :xpath => '//ol')
ordered_list(:ol_class_index, :class => "ol_class", :index => 0)
ordered_list(:ol_name_index, :name => "ol_name", :index => 0)
h1(:h1_id, :id => 'h1_id')
h1(:h1_class, :class => 'h1_class')
h1(:h1_css, :css => '.h1_class')
h1(:h1_name, :name => 'h1_name')
h1(:h1_index, :index => 0)
h1(:h1_xpath, :xpath => '//h1')
h1(:h1_class_index, :class => 'h1_class', :index => 0)
h1(:h1_name_index, :name => 'h1_name', :index => 0)
h2(:h2_id, :id => 'h2_id')
h2(:h2_class, :class => 'h2_class')
h2(:h2_css, :css => '.h2_class')
h2(:h2_name, :name => 'h2_name')
h2(:h2_index, :index => 0)
h2(:h2_xpath, :xpath => '//h2')
h2(:h2_class_index, :class => 'h2_class', :index => 0)
h2(:h2_name_index, :name => 'h2_name', :index => 0)
h3(:h3_id, :id => 'h3_id')
h3(:h3_class, :class => 'h3_class')
h3(:h3_css, :css => '.h3_class')
h3(:h3_name, :name => 'h3_name')
h3(:h3_index, :index => 0)
h3(:h3_xpath, :xpath => '//h3')
h3(:h3_class_index, :class => 'h3_class', :index => 0)
h3(:h3_name_index, :name => 'h3_name', :index => 0)
h4(:h4_id, :id => 'h4_id')
h4(:h4_class, :class => 'h4_class')
h4(:h4_css, :css => '.h4_class')
h4(:h4_name, :name => 'h4_name')
h4(:h4_index, :index => 0)
h4(:h4_xpath, :xpath => '//h4')
h4(:h4_class_index, :class => 'h4_class', :index => 0)
h4(:h4_name_index, :name => 'h4_name', :index => 0)
h5(:h5_id, :id => 'h5_id')
h5(:h5_class, :class => 'h5_class')
h5(:h5_css, :css => '.h5_class')
h5(:h5_name, :name => 'h5_name')
h5(:h5_index, :index => 0)
h5(:h5_xpath, :xpath => '//h5')
h5(:h5_class_index, :class => 'h5_class', :index => 0)
h5(:h5_name_index, :name => 'h5_name', :index => 0)
h6(:h6_id, :id => 'h6_id')
h6(:h6_class, :class => 'h6_class')
h6(:h6_css, :css => '.h6_class')
h6(:h6_name, :name => 'h6_name')
h6(:h6_index, :index => 0)
h6(:h6_xpath, :xpath => '//h6')
h6(:h6_class_index, :class => 'h6_class', :index => 0)
h6(:h6_name_index, :name => 'h6_name', :index => 0)
paragraph(:p_id, :id => 'p_id')
paragraph(:p_class, :class => 'p_class')
paragraph(:p_css, :css => '.p_class')
paragraph(:p_name, :name => 'p_name')
paragraph(:p_index, :index => 0)
paragraph(:p_xpath, :xpath => '//p')
paragraph(:p_class_index, :class => 'p_class', :index => 0)
paragraph(:p_name_index, :name => 'p_name', :index => 0)
button(:alert_button, :id => 'alert_button')
button(:alert_button_that_reloads, :id => 'alert_button_that_reloads')
button(:confirm_button, :id => 'confirm_button')
button(:confirm_button_that_reloads, :id => 'confirm_button_that_reloads')
button(:prompt_button, :id => 'prompt_button')
file_field(:file_field_id, :id => 'file_field_id')
file_field(:file_field_name, :name => 'file_field_name')
file_field(:file_field_class, :class => 'file_field_class')
file_field(:file_field_css, :css => '.file_field_class')
file_field(:file_field_index, :index => 0)
file_field(:file_field_title, :title => 'file_field_title')
file_field(:file_field_class_index, :class => 'file_field_class', :index => 0)
file_field(:file_field_name_index, :name => 'file_field_name', :index => 0)
file_field(:file_field_xpath, :xpath => "//input[@type='file']")
file_field(:file_field_label, :label => "File Field")
label(:label_id, :id => 'label_id')
label(:label_name, :name => 'label_name')
label(:label_class, :class => 'label_class')
label(:label_css, :css => '.label_class')
label(:label_text, :text => 'page-object is the best!')
label(:label_index, :index => 6)
label(:label_xpath, :xpath => '//label[7]')
label(:label_class_index, :class => "label_class", :index => 0)
label(:label_name_index, :name => "label_name", :index => 0)
link(:open_window, :text => 'New Window')
link(:open_another_window, :text => 'Another New Window')
link(:child, :id => 'child')
area(:area_id, :id => 'area')
area(:area_name, :name => 'area')
area(:area_class, :class => 'area')
area(:area_css, :css => '.area')
area(:area_index, :index => 0)
area(:area_xpath, :xpath => '//area')
area(:area_class_index, :class => 'area', :index => 0)
area(:area_name_index, :name => 'area', :index => 0)
canvas(:canvas_id, :id => 'canvas')
canvas(:canvas_name, :name => 'canvas')
canvas(:canvas_class, :class => 'canvas')
canvas(:canvas_css, :css => '.canvas')
canvas(:canvas_index, :index => 0)
canvas(:canvas_xpath, :xpath => '//canvas')
canvas(:canvas_class_index, :class => 'canvas', :index => 0)
canvas(:canvas_name_index, :name => 'canvas', :index => 0)
element(:article_id, :article, :id => 'article_id')
element(:header_id, :header, :id => 'header_id')
element(:footer_id, :footer, :id => 'footer_id')
element(:summary_id, :summary, :id => 'summary_id')
element(:details_id, :details, :id => 'details_id')
figure(:figure_id, :id => 'figure_id')
svg(:svg_id, :id => 'the_svg')
b(:b_id, :id => 'b_id')
b(:b_class, :class => 'b_class')
b(:b_css, :css => '.b_class')
b(:b_name, :name => 'b_name')
b(:b_index, :index => 0)
b(:b_xpath, :xpath => '//b')
b(:b_class_index, :class => 'b_class', :index => 0)
b(:b_name_index, :name => 'b_name', :index => 0)
i(:i_id, :id => 'i_id')
i(:i_class, :class => 'i_class')
i(:i_css, :css => '.i_class')
i(:i_name, :name => 'i_name')
i(:i_index, :index => 0)
i(:i_xpath, :xpath => '//i')
i(:i_class_index, :class => 'i_class', :index => 0)
i(:i_name_index, :name => 'i_name', :index => 0)
def before_callback(*args)
@before_callback_called = true
end
def after_callback(*args)
@after_callback_called = true
end
def before_callback?
val = @before_callback_called
@before_callback_called = nil
val
end
def after_callback?
val = @after_callback_called
@after_callback_called = true
val
end
end
|
Donavan/page-object
|
features/support/page.rb
|
Ruby
|
mit
| 16,387
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
本测试模块用于测试与 :class:`sqlite4dummy.schema.MetaData` 有关的方法
class, method, func, exception
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from sqlite4dummy import *
from sqlite4dummy.tests.basetest import *
from datetime import datetime, date
import unittest
class MetaDataUnittest(unittest.TestCase):
"""Unittest of :class:`sqlite4dummy.schema.MetaData`.
MetaData的方法的单元测试。
"""
def setUp(self):
self.engine = Sqlite3Engine(":memory:", autocommit=False)
self.metadata = MetaData()
self.int_ = 1
self.float_ = 3.14
self.str_ = r"""\/!@#$%^&*()_+-=~`|[]{}><,.'"?"""
self.bytes_ = "abc".encode("utf-8")
self.date_ = date(2000, 1, 1)
self.datetime_ = datetime(2015, 10, 1, 18, 30, 0, 123)
self.pickle_ = [1, 2, 3]
self.test = Table("test", self.metadata,
Column("_id", dtype.INTEGER, primary_key=True, nullable=False),
Column("_int_with_default", dtype.INTEGER, default=self.int_),
Column("_float_with_default", dtype.REAL, default=self.float_),
Column("_str_with_default", dtype.TEXT, default=self.str_),
Column("_bytes_with_default", dtype.BLOB, default=self.bytes_),
Column("_date_with_default", dtype.DATE, default=self.date_),
Column("_datetime_with_default", dtype.DATETIME, default=self.datetime_),
Column("_pickle_with_default", dtype.PICKLETYPE, default=self.pickle_),
Column("_int", dtype.INTEGER),
Column("_float", dtype.REAL),
Column("_str", dtype.TEXT),
Column("_bytes", dtype.BLOB),
Column("_date", dtype.DATE),
Column("_datetime", dtype.DATETIME),
Column("_pickle", dtype.PICKLETYPE),
)
self.metadata.create_all(self.engine)
self.index = Index("test_index", self.metadata,
[self.test.c._int,
self.test.c._float.desc(),
self.test.c._date,
desc(self.test.c._datetime)],
table_name=self.test,
unique=True,
skip_validate=False,
)
self.index.create(self.engine)
self.assertEqual(
len(self.engine.execute("PRAGMA table_info(test);").fetchall()),
15,
)
self.assertEqual(
len(self.engine.execute(
"SELECT * FROM sqlite_master "
"WHERE type = 'index' AND sql NOT NULL;").fetchall()),
1,
)
def tearDown(self):
self.engine.close()
def test_drop_all(self):
"""测试drop_all是否能drop所有的表。
"""
self.assertEqual(
len(self.engine.execute(
"SELECT * FROM sqlite_master WHERE type = 'table';").fetchall()),
1,
)
self.metadata.drop_all(self.engine)
self.assertEqual(
len(self.engine.execute(
"SELECT * FROM sqlite_master WHERE type = 'table';").fetchall()),
0,
)
self.assertEqual(len(self.metadata.t), 0) # 没有表了
def test_str_repr(self):
# print(self.metadata)
# print(repr(self.metadata))
pass
def test_get_table(self):
"""测试MetaData.get_table(table)方法是否能正确获得Table。
"""
self.assertEqual(self.metadata.get_table("test"), self.test)
self.assertRaises(KeyError,
self.metadata.get_table, "not_existing_table")
def test_get_index(self):
"""测试MetaData.get_index(index)方法是否能正确获得Index。
"""
self.assertEqual(self.metadata.get_index("test_index"), self.index)
self.assertRaises(KeyError,
self.metadata.get_index, "not_existing_index")
def test_reflect(self):
"""测试MetaData.reflect(engine)是否能正确解析出Table, Column, Index的
metadata, 并且解析出Column的default值。
"""
second_metadata = MetaData()
second_metadata.reflect(self.engine,
pickletype_columns=[
"test._pickle_with_default",
"test._pickle",
])
self.assertEqual(second_metadata.get_table("test").\
c._int_with_default.default, self.int_)
self.assertEqual(second_metadata.get_table("test").\
c._float_with_default.default, self.float_)
self.assertEqual(second_metadata.get_table("test").\
c._str_with_default.default, self.str_)
self.assertEqual(second_metadata.get_table("test").\
c._bytes_with_default.default, self.bytes_)
self.assertEqual(second_metadata.get_table("test").\
c._date_with_default.default, self.date_)
self.assertEqual(second_metadata.get_table("test").\
c._datetime_with_default.default, self.datetime_)
self.assertEqual(second_metadata.get_table("test").\
c._pickle_with_default.default, self.pickle_)
self.assertEqual(second_metadata.get_index("test_index").\
index_name, "test_index")
self.assertEqual(second_metadata.get_index("test_index").\
table_name, "test")
self.assertEqual(second_metadata.get_index("test_index").\
unique, True)
self.assertEqual(second_metadata.get_index("test_index").\
params, self.index.params)
if __name__ == "__main__":
unittest.main()
|
MacHu-GWU/sqlite4dummy-project
|
sqlite4dummy/tests/functionality/test_MetaData.py
|
Python
|
mit
| 5,883
|
package io.fundrequest.platform.tweb.profile;
import io.fundrequest.core.message.MessageService;
import io.fundrequest.core.message.dto.MessageDto;
import io.fundrequest.platform.keycloak.Provider;
import io.fundrequest.platform.profile.github.GithubBountyService;
import io.fundrequest.platform.profile.profile.ProfileService;
import io.fundrequest.platform.profile.profile.dto.GithubVerificationDto;
import io.fundrequest.platform.profile.ref.ReferralService;
import io.fundrequest.platform.profile.stackoverflow.StackOverflowBountyService;
import io.fundrequest.platform.profile.stackoverflow.dto.StackOverflowVerificationDto;
import org.apache.commons.lang3.StringUtils;
import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.Principal;
@Controller
public class ProfileController {
private ApplicationEventPublisher eventPublisher;
private ProfileService profileService;
private MessageService messageService;
private ReferralService referralService;
private GithubBountyService githubBountyService;
private StackOverflowBountyService stackOverflowBountyService;
private String arkaneEnvironment;
public ProfileController(final ApplicationEventPublisher eventPublisher,
final ProfileService profileService,
final MessageService messageService,
final ReferralService referralService,
final GithubBountyService githubBountyService,
final @Value("${network.arkane.environment}") String arkaneEnvironment,
final StackOverflowBountyService stackOverflowBountyService) {
this.eventPublisher = eventPublisher;
this.profileService = profileService;
this.messageService = messageService;
this.referralService = referralService;
this.githubBountyService = githubBountyService;
this.arkaneEnvironment = arkaneEnvironment;
this.stackOverflowBountyService = stackOverflowBountyService;
}
@GetMapping("/profile")
public ModelAndView showProfile(Principal principal) throws Exception {
final ModelAndView mav = new ModelAndView("pages/profile/index");
mav.addObject("isVerifiedGithub", isVerifiedGithub(principal));
mav.addObject("isVerifiedStackOverflow", isVerifiedStackOverflow(principal));
mav.addObject("refLink", getRefLink(principal, "web"));
mav.addObject("refShareTwitter", processRefLinkMessage(messageService.getMessageByKey("REFERRAL_SHARE.twitter"), getRefLink(principal, "twitter")));
mav.addObject("refShareLinkedin", processRefLinkMessage(messageService.getMessageByKey("REFERRAL_SHARE.linkedin"), getRefLink(principal, "linkedin")));
mav.addObject("refShareFacebook", processRefLinkMessage(messageService.getMessageByKey("REFERRAL_SHARE.facebook"), getRefLink(principal, "facebook")));
mav.addObject("arkaneWalletEndpoint", getArkaneWalletEndpoint());
return mav;
}
private MessageDto processRefLinkMessage(MessageDto message, String refLink) throws Exception {
String link = message.getLink();
String description = message.getDescription().replace("###REFLINK###", refLink);
link = link
.replace("###REFLINK###", URLEncoder.encode(refLink, "UTF-8"))
.replace("###TITLE###", URLEncoder.encode(message.getTitle(), "UTF-8"))
.replace("###DESCRIPTION###", URLEncoder.encode(description, "UTF-8"));
message.setDescription(description);
message.setLink(link);
return message;
}
private boolean isVerifiedStackOverflow(final Principal principal) {
final StackOverflowVerificationDto verification = stackOverflowBountyService.getVerification(principal);
return verification != null && verification.isApproved();
}
private boolean isVerifiedGithub(final Principal principal) {
final GithubVerificationDto verification = githubBountyService.getVerification(principal);
return verification != null && verification.isApproved();
}
@GetMapping("/profile/link/{provider}")
public ModelAndView linkProfile(@PathVariable String provider,
HttpServletRequest request,
Principal principal,
@RequestParam(value = "redirectUrl", required = false) String redirectUrl) {
if (StringUtils.isBlank(redirectUrl)) {
redirectUrl = request.getRequestURL().toString();
}
String link = profileService.createSignupLink(request, principal, Provider.fromString(provider.replaceAll("[^A-Za-z]", "")), redirectUrl);
return new ModelAndView(new RedirectView(link, false));
}
@GetMapping("/profile/managewallets")
public ModelAndView manageWallets(Principal principal, HttpServletRequest request) throws UnsupportedEncodingException {
String bearerToken = URLEncoder.encode(profileService.getArkaneAccessToken((KeycloakAuthenticationToken) principal), "UTF-8");
String redirectUri = request.getHeader("referer");
if (redirectUri == null) {
redirectUri = "/profile";
}
redirectUri = URLEncoder.encode(redirectUri, "UTF-8");
String url = getConnectEndpoint(bearerToken, redirectUri);
profileService.walletsManaged(principal);
return new ModelAndView(new RedirectView(url));
}
private String getConnectEndpoint(String bearerToken, String redirectUri) {
String endpoint = "https://connect.arkane.network";
if (StringUtils.isNotBlank(arkaneEnvironment)) {
endpoint = "https://connect-" + arkaneEnvironment + ".arkane.network";
}
return endpoint + "/wallets/manage?redirectUri=" + redirectUri + "&data=eyJjaGFpbiI6ICJldGhlcmV1bSJ9&bearerToken=" + bearerToken;
}
private String getArkaneWalletEndpoint() {
String endpoint = "https://app.arkane.network/chains/ethereum/wallets/";
if (StringUtils.isNotBlank(arkaneEnvironment)) {
endpoint = "https://" + arkaneEnvironment + ".arkane.network/chains/ethereum/wallets/";
}
return endpoint;
}
@PostMapping("/profile/headline")
public ModelAndView updateHeadline(Principal principal, @RequestParam("headline") String headline) {
profileService.updateHeadline(principal, headline);
return redirectToProfile();
}
private String getRefLink(final Principal principal, String source) {
return referralService.generateRefLink(principal.getName(), source);
}
@GetMapping("/profile/link/{provider}/redirect")
public ModelAndView redirectToHereAfterProfileLink(Principal principal,
@PathVariable("provider") String provider,
@RequestParam(value = "redirectUrl", required = false) String redirectUrl) {
profileService.userProviderIdentityLinked(principal, Provider.fromString(provider));
if (StringUtils.isNotBlank(redirectUrl) && !redirectUrl.toLowerCase().contains("/profile/link/")) {
return new ModelAndView(new RedirectView(redirectUrl));
}
return redirectToProfile();
}
private ModelAndView redirectToProfile() {
return new ModelAndView(new RedirectView("/profile"));
}
}
|
FundRequest/platform
|
tweb/src/main/java/io/fundrequest/platform/tweb/profile/ProfileController.java
|
Java
|
mit
| 8,165
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.connector;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.ServletOutputStream;
import javax.servlet.SessionTrackingMode;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.Context;
import org.apache.catalina.Globals;
import org.apache.catalina.Session;
import org.apache.catalina.Wrapper;
import org.apache.catalina.security.SecurityUtil;
import org.apache.catalina.util.RequestUtil;
import org.apache.catalina.util.SessionConfig;
import org.apache.coyote.ActionCode;
import org.apache.tomcat.util.buf.CharChunk;
import org.apache.tomcat.util.buf.UEncoder;
import org.apache.tomcat.util.buf.UEncoder.SafeCharsSet;
import org.apache.tomcat.util.http.FastHttpDateFormat;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.http.parser.MediaTypeCache;
import org.apache.tomcat.util.net.URL;
import org.apache.tomcat.util.res.StringManager;
/**
* Wrapper object for the Coyote response.
*
* @author Remy Maucherat
* @author Craig R. McClanahan
*/
public class Response
implements HttpServletResponse {
// ----------------------------------------------------------- Constructors
private static final MediaTypeCache MEDIA_TYPE_CACHE =
new MediaTypeCache(100);
/**
* Compliance with SRV.15.2.22.1. A call to Response.getWriter() if no
* character encoding has been specified will result in subsequent calls to
* Response.getCharacterEncoding() returning ISO-8859-1 and the Content-Type
* response header will include a charset=ISO-8859-1 component.
*/
private static final boolean ENFORCE_ENCODING_IN_GET_WRITER;
static {
// Ensure that URL is loaded for SM
URL.isSchemeChar('c');
ENFORCE_ENCODING_IN_GET_WRITER = Boolean.valueOf(
System.getProperty("org.apache.catalina.connector.Response.ENFORCE_ENCODING_IN_GET_WRITER",
"true")).booleanValue();
}
public Response() {
}
// ----------------------------------------------------- Class Variables
/**
* The string manager for this package.
*/
protected static final StringManager sm =
StringManager.getManager(Constants.Package);
// ----------------------------------------------------- Instance Variables
/**
* The date format we will use for creating date headers.
*/
protected SimpleDateFormat format = null;
// ------------------------------------------------------------- Properties
/**
* Set the Connector through which this Request was received.
*
* @param connector The new connector
*/
public void setConnector(Connector connector) {
if("AJP/1.3".equals(connector.getProtocol())) {
// default size to size of one ajp-packet
outputBuffer = new OutputBuffer(8184);
} else {
outputBuffer = new OutputBuffer();
}
outputStream = new CoyoteOutputStream(outputBuffer);
writer = new CoyoteWriter(outputBuffer);
}
/**
* Coyote response.
*/
protected org.apache.coyote.Response coyoteResponse;
/**
* Set the Coyote response.
*
* @param coyoteResponse The Coyote response
*/
public void setCoyoteResponse(org.apache.coyote.Response coyoteResponse) {
this.coyoteResponse = coyoteResponse;
outputBuffer.setResponse(coyoteResponse);
}
/**
* Get the Coyote response.
*/
public org.apache.coyote.Response getCoyoteResponse() {
return this.coyoteResponse;
}
/**
* Return the Context within which this Request is being processed.
*/
public Context getContext() {
return (request.getContext());
}
/**
* The associated output buffer.
*/
protected OutputBuffer outputBuffer;
/**
* The associated output stream.
*/
protected CoyoteOutputStream outputStream;
/**
* The associated writer.
*/
protected CoyoteWriter writer;
/**
* The application commit flag.
*/
protected boolean appCommitted = false;
/**
* The included flag.
*/
protected boolean included = false;
/**
* The characterEncoding flag
*/
private boolean isCharacterEncodingSet = false;
/**
* With the introduction of async processing and the possibility of
* non-container threads calling sendError() tracking the current error
* state and ensuring that the correct error page is called becomes more
* complicated. This state attribute helps by tracking the current error
* state and informing callers that attempt to change state if the change
* was successful or if another thread got there first.
*
* <pre>
* The state machine is very simple:
*
* 0 - NONE
* 1 - NOT_REPORTED
* 2 - REPORTED
*
*
* -->---->-- >NONE
* | | |
* | | | setError()
* ^ ^ |
* | | \|/
* | |-<-NOT_REPORTED
* | |
* ^ | report()
* | |
* | \|/
* |----<----REPORTED
* </pre>
*/
private final AtomicInteger errorState = new AtomicInteger(0);
/**
* Using output stream flag.
*/
protected boolean usingOutputStream = false;
/**
* Using writer flag.
*/
protected boolean usingWriter = false;
/**
* URL encoder.
*/
protected final UEncoder urlEncoder = new UEncoder(SafeCharsSet.WITH_SLASH);
/**
* Recyclable buffer to hold the redirect URL.
*/
protected final CharChunk redirectURLCC = new CharChunk();
// --------------------------------------------------------- Public Methods
/**
* Release all object references, and initialize instance variables, in
* preparation for reuse of this object.
*/
public void recycle() {
outputBuffer.recycle();
usingOutputStream = false;
usingWriter = false;
appCommitted = false;
included = false;
errorState.set(0);
isCharacterEncodingSet = false;
if (Globals.IS_SECURITY_ENABLED || Connector.RECYCLE_FACADES) {
if (facade != null) {
facade.clear();
facade = null;
}
if (outputStream != null) {
outputStream.clear();
outputStream = null;
}
if (writer != null) {
writer.clear();
writer = null;
}
} else {
writer.recycle();
}
}
/**
* Clear cached encoders (to save memory for Comet requests).
*/
public void clearEncoders() {
outputBuffer.clearEncoders();
}
// ------------------------------------------------------- Response Methods
/**
* Return the number of bytes the application has actually written to the
* output stream. This excludes chunking, compression, etc. as well as
* headers.
*/
public long getContentWritten() {
return outputBuffer.getContentWritten();
}
/**
* Return the number of bytes the actually written to the socket. This
* includes chunking, compression, etc. but excludes headers.
*/
public long getBytesWritten(boolean flush) {
if (flush) {
try {
outputBuffer.flush();
} catch (IOException ioe) {
// Ignore - the client has probably closed the connection
}
}
return getCoyoteResponse().getBytesWritten(flush);
}
/**
* Set the application commit flag.
*
* @param appCommitted The new application committed flag value
*/
public void setAppCommitted(boolean appCommitted) {
this.appCommitted = appCommitted;
}
/**
* Application commit flag accessor.
*/
public boolean isAppCommitted() {
return (this.appCommitted || isCommitted() || isSuspended()
|| ((getContentLength() > 0)
&& (getContentWritten() >= getContentLength())));
}
/**
* The request with which this response is associated.
*/
protected Request request = null;
/**
* Return the Request with which this Response is associated.
*/
public org.apache.catalina.connector.Request getRequest() {
return (this.request);
}
/**
* Set the Request with which this Response is associated.
*
* @param request The new associated request
*/
public void setRequest(org.apache.catalina.connector.Request request) {
this.request = request;
}
/**
* The facade associated with this response.
*/
protected ResponseFacade facade = null;
/**
* Return the <code>ServletResponse</code> for which this object
* is the facade.
*/
public HttpServletResponse getResponse() {
if (facade == null) {
facade = new ResponseFacade(this);
}
return (facade);
}
/**
* Set the suspended flag.
*
* @param suspended The new suspended flag value
*/
public void setSuspended(boolean suspended) {
outputBuffer.setSuspended(suspended);
}
/**
* Suspended flag accessor.
*/
public boolean isSuspended() {
return outputBuffer.isSuspended();
}
/**
* Closed flag accessor.
*/
public boolean isClosed() {
return outputBuffer.isClosed();
}
/**
* Set the error flag.
*/
public boolean setError() {
boolean result = errorState.compareAndSet(0, 1);
if (result) {
Wrapper wrapper = getRequest().getWrapper();
if (wrapper != null) {
wrapper.incrementErrorCount();
}
}
return result;
}
/**
* Error flag accessor.
*/
public boolean isError() {
return errorState.get() > 0;
}
public boolean isErrorReportRequired() {
return errorState.get() == 1;
}
public boolean setErrorReported() {
return errorState.compareAndSet(1, 2);
}
/**
* Perform whatever actions are required to flush and close the output
* stream or writer, in a single operation.
*
* @exception IOException if an input/output error occurs
*/
public void finishResponse() throws IOException {
// Writing leftover bytes
outputBuffer.close();
}
/**
* Return the content length that was set or calculated for this Response.
*/
public int getContentLength() {
return getCoyoteResponse().getContentLength();
}
/**
* Return the content type that was set or calculated for this response,
* or <code>null</code> if no content type was set.
*/
@Override
public String getContentType() {
return getCoyoteResponse().getContentType();
}
/**
* Return a PrintWriter that can be used to render error messages,
* regardless of whether a stream or writer has already been acquired.
*
* @return Writer which can be used for error reports. If the response is
* not an error report returned using sendError or triggered by an
* unexpected exception thrown during the servlet processing
* (and only in that case), null will be returned if the response stream
* has already been used.
*
* @exception IOException if an input/output error occurs
*/
public PrintWriter getReporter() throws IOException {
if (outputBuffer.isNew()) {
outputBuffer.checkConverter();
if (writer == null) {
writer = new CoyoteWriter(outputBuffer);
}
return writer;
} else {
return null;
}
}
// ------------------------------------------------ ServletResponse Methods
/**
* Flush the buffer and commit this response.
*
* @exception IOException if an input/output error occurs
*/
@Override
public void flushBuffer() throws IOException {
outputBuffer.flush();
}
/**
* Return the actual buffer size used for this Response.
*/
@Override
public int getBufferSize() {
return outputBuffer.getBufferSize();
}
/**
* Return the character encoding used for this Response.
*/
@Override
public String getCharacterEncoding() {
return (getCoyoteResponse().getCharacterEncoding());
}
/**
* Return the servlet output stream associated with this Response.
*
* @exception IllegalStateException if <code>getWriter</code> has
* already been called for this response
* @exception IOException if an input/output error occurs
*/
@Override
public ServletOutputStream getOutputStream()
throws IOException {
if (usingWriter) {
throw new IllegalStateException
(sm.getString("coyoteResponse.getOutputStream.ise"));
}
usingOutputStream = true;
if (outputStream == null) {
outputStream = new CoyoteOutputStream(outputBuffer);
}
return outputStream;
}
/**
* Return the Locale assigned to this response.
*/
@Override
public Locale getLocale() {
return (getCoyoteResponse().getLocale());
}
/**
* Return the writer associated with this Response.
*
* @exception IllegalStateException if <code>getOutputStream</code> has
* already been called for this response
* @exception IOException if an input/output error occurs
*/
@Override
public PrintWriter getWriter()
throws IOException {
if (usingOutputStream) {
throw new IllegalStateException
(sm.getString("coyoteResponse.getWriter.ise"));
}
if (ENFORCE_ENCODING_IN_GET_WRITER) {
/*
* If the response's character encoding has not been specified as
* described in <code>getCharacterEncoding</code> (i.e., the method
* just returns the default value <code>ISO-8859-1</code>),
* <code>getWriter</code> updates it to <code>ISO-8859-1</code>
* (with the effect that a subsequent call to getContentType() will
* include a charset=ISO-8859-1 component which will also be
* reflected in the Content-Type response header, thereby satisfying
* the Servlet spec requirement that containers must communicate the
* character encoding used for the servlet response's writer to the
* client).
*/
setCharacterEncoding(getCharacterEncoding());
}
usingWriter = true;
outputBuffer.checkConverter();
if (writer == null) {
writer = new CoyoteWriter(outputBuffer);
}
return writer;
}
/**
* Has the output of this response already been committed?
*/
@Override
public boolean isCommitted() {
return getCoyoteResponse().isCommitted();
}
/**
* Clear any content written to the buffer.
*
* @exception IllegalStateException if this response has already
* been committed
*/
@Override
public void reset() {
// Ignore any call from an included servlet
if (included) {
return;
}
getCoyoteResponse().reset();
outputBuffer.reset();
usingOutputStream = false;
usingWriter = false;
isCharacterEncodingSet = false;
}
/**
* Reset the data buffer but not any status or header information.
*
* @exception IllegalStateException if the response has already
* been committed
*/
@Override
public void resetBuffer() {
resetBuffer(false);
}
/**
* Reset the data buffer and the using Writer/Stream flags but not any
* status or header information.
*
* @param resetWriterStreamFlags <code>true</code> if the internal
* <code>usingWriter</code>, <code>usingOutputStream</code>,
* <code>isCharacterEncodingSet</code> flags should also be reset
*
* @exception IllegalStateException if the response has already
* been committed
*/
public void resetBuffer(boolean resetWriterStreamFlags) {
if (isCommitted()) {
throw new IllegalStateException
(sm.getString("coyoteResponse.resetBuffer.ise"));
}
outputBuffer.reset(resetWriterStreamFlags);
if(resetWriterStreamFlags) {
usingOutputStream = false;
usingWriter = false;
isCharacterEncodingSet = false;
}
}
/**
* Set the buffer size to be used for this Response.
*
* @param size The new buffer size
*
* @exception IllegalStateException if this method is called after
* output has been committed for this response
*/
@Override
public void setBufferSize(int size) {
if (isCommitted() || !outputBuffer.isNew()) {
throw new IllegalStateException
(sm.getString("coyoteResponse.setBufferSize.ise"));
}
outputBuffer.setBufferSize(size);
}
/**
* Set the content length (in bytes) for this Response.
*
* @param length The new content length
*/
@Override
public void setContentLength(int length) {
setContentLengthLong(length);
}
/**
* TODO SERVLET 3.1
*/
@Override
public void setContentLengthLong(long length) {
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
getCoyoteResponse().setContentLength(length);
}
/**
* Set the content type for this Response.
*
* @param type The new content type
*/
@Override
public void setContentType(String type) {
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
if (type == null) {
getCoyoteResponse().setContentType(null);
return;
}
String[] m = MEDIA_TYPE_CACHE.parse(type);
if (m == null) {
// Invalid - Assume no charset and just pass through whatever
// the user provided.
getCoyoteResponse().setContentTypeNoCharset(type);
return;
}
getCoyoteResponse().setContentTypeNoCharset(m[0]);
if (m[1] != null) {
// Ignore charset if getWriter() has already been called
if (!usingWriter) {
getCoyoteResponse().setCharacterEncoding(m[1]);
isCharacterEncodingSet = true;
}
}
}
/*
* Overrides the name of the character encoding used in the body
* of the request. This method must be called prior to reading
* request parameters or reading input using getReader().
*
* @param charset String containing the name of the character encoding.
*/
@Override
public void setCharacterEncoding(String charset) {
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
// Ignore any call made after the getWriter has been invoked
// The default should be used
if (usingWriter) {
return;
}
getCoyoteResponse().setCharacterEncoding(charset);
isCharacterEncodingSet = true;
}
/**
* Set the Locale that is appropriate for this response, including
* setting the appropriate character encoding.
*
* @param locale The new locale
*/
@Override
public void setLocale(Locale locale) {
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
getCoyoteResponse().setLocale(locale);
// Ignore any call made after the getWriter has been invoked.
// The default should be used
if (usingWriter) {
return;
}
if (isCharacterEncodingSet) {
return;
}
String charset = getContext().getCharset(locale);
if (charset != null) {
getCoyoteResponse().setCharacterEncoding(charset);
}
}
// --------------------------------------------------- HttpResponse Methods
@Override
public String getHeader(String name) {
return getCoyoteResponse().getMimeHeaders().getHeader(name);
}
@Override
public Collection<String> getHeaderNames() {
MimeHeaders headers = getCoyoteResponse().getMimeHeaders();
int n = headers.size();
List<String> result = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
result.add(headers.getName(i).toString());
}
return result;
}
@Override
public Collection<String> getHeaders(String name) {
Enumeration<String> enumeration =
getCoyoteResponse().getMimeHeaders().values(name);
Vector<String> result = new Vector<>();
while (enumeration.hasMoreElements()) {
result.addElement(enumeration.nextElement());
}
return result;
}
/**
* Return the error message that was set with <code>sendError()</code>
* for this Response.
*/
public String getMessage() {
return getCoyoteResponse().getMessage();
}
@Override
public int getStatus() {
return getCoyoteResponse().getStatus();
}
// -------------------------------------------- HttpServletResponse Methods
/**
* Add the specified Cookie to those that will be included with
* this Response.
*
* @param cookie Cookie to be added
*/
@Override
public void addCookie(final Cookie cookie) {
// Ignore any call from an included servlet
if (included || isCommitted()) {
return;
}
String header = generateCookieString(cookie);
//if we reached here, no exception, cookie is valid
// the header name is Set-Cookie for both "old" and v.1 ( RFC2109 )
// RFC2965 is not supported by browsers and the Servlet spec
// asks for 2109.
addHeader("Set-Cookie", header, getContext().getCookieProcessor().getCharset());
}
/**
* Special method for adding a session cookie as we should be overriding
* any previous.
*
* @param cookie The new session cookie to add the response
*/
public void addSessionCookieInternal(final Cookie cookie) {
if (isCommitted()) {
return;
}
String name = cookie.getName();
final String headername = "Set-Cookie";
final String startsWith = name + "=";
String header = generateCookieString(cookie);
boolean set = false;
MimeHeaders headers = getCoyoteResponse().getMimeHeaders();
int n = headers.size();
for (int i = 0; i < n; i++) {
if (headers.getName(i).toString().equals(headername)) {
if (headers.getValue(i).toString().startsWith(startsWith)) {
headers.getValue(i).setString(header);
set = true;
}
}
}
if (!set) {
addHeader(headername, header);
}
}
public String generateCookieString(final Cookie cookie) {
// Web application code can receive a IllegalArgumentException
// from the generateHeader() invocation
if (SecurityUtil.isPackageProtectionEnabled()) {
return AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run(){
return getContext().getCookieProcessor().generateHeader(cookie);
}
});
} else {
return getContext().getCookieProcessor().generateHeader(cookie);
}
}
/**
* Add the specified date header to the specified value.
*
* @param name Name of the header to set
* @param value Date value to be set
*/
@Override
public void addDateHeader(String name, long value) {
if (name == null || name.length() == 0) {
return;
}
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
if (format == null) {
format = new SimpleDateFormat(FastHttpDateFormat.RFC1123_DATE,
Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
}
addHeader(name, FastHttpDateFormat.formatDate(value, format));
}
/**
* Add the specified header to the specified value.
*
* @param name Name of the header to set
* @param value Value to be set
*/
@Override
public void addHeader(String name, String value) {
addHeader(name, value, null);
}
private void addHeader(String name, String value, Charset charset) {
if (name == null || name.length() == 0 || value == null) {
return;
}
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
char cc=name.charAt(0);
if (cc=='C' || cc=='c') {
if (checkSpecialHeader(name, value))
return;
}
getCoyoteResponse().addHeader(name, value, charset);
}
/**
* An extended version of this exists in {@link org.apache.coyote.Response}.
* This check is required here to ensure that the usingWriter check in
* {@link #setContentType(String)} is applied since usingWriter is not
* visible to {@link org.apache.coyote.Response}
*
* Called from set/addHeader.
* Return true if the header is special, no need to set the header.
*/
private boolean checkSpecialHeader(String name, String value) {
if (name.equalsIgnoreCase("Content-Type")) {
setContentType(value);
return true;
}
return false;
}
/**
* Add the specified integer header to the specified value.
*
* @param name Name of the header to set
* @param value Integer value to be set
*/
@Override
public void addIntHeader(String name, int value) {
if (name == null || name.length() == 0) {
return;
}
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
addHeader(name, "" + value);
}
/**
* Has the specified header been set already in this response?
*
* @param name Name of the header to check
*/
@Override
public boolean containsHeader(String name) {
// Need special handling for Content-Type and Content-Length due to
// special handling of these in coyoteResponse
char cc=name.charAt(0);
if(cc=='C' || cc=='c') {
if(name.equalsIgnoreCase("Content-Type")) {
// Will return null if this has not been set
return (getCoyoteResponse().getContentType() != null);
}
if(name.equalsIgnoreCase("Content-Length")) {
// -1 means not known and is not sent to client
return (getCoyoteResponse().getContentLengthLong() != -1);
}
}
return getCoyoteResponse().containsHeader(name);
}
/**
* Encode the session identifier associated with this response
* into the specified redirect URL, if necessary.
*
* @param url URL to be encoded
*/
@Override
public String encodeRedirectURL(String url) {
if (isEncodeable(toAbsolute(url))) {
return (toEncoded(url, request.getSessionInternal().getIdInternal()));
} else {
return (url);
}
}
/**
* Encode the session identifier associated with this response
* into the specified redirect URL, if necessary.
*
* @param url URL to be encoded
*
* @deprecated As of Version 2.1 of the Java Servlet API, use
* <code>encodeRedirectURL()</code> instead.
*/
@Override
@Deprecated
public String encodeRedirectUrl(String url) {
return (encodeRedirectURL(url));
}
/**
* Encode the session identifier associated with this response
* into the specified URL, if necessary.
*
* @param url URL to be encoded
*/
@Override
public String encodeURL(String url) {
String absolute;
try {
absolute = toAbsolute(url);
} catch (IllegalArgumentException iae) {
// Relative URL
return url;
}
if (isEncodeable(absolute)) {
// W3c spec clearly said
if (url.equalsIgnoreCase("")) {
url = absolute;
} else if (url.equals(absolute) && !hasPath(url)) {
url += '/';
}
return (toEncoded(url, request.getSessionInternal().getIdInternal()));
} else {
return (url);
}
}
/**
* Encode the session identifier associated with this response
* into the specified URL, if necessary.
*
* @param url URL to be encoded
*
* @deprecated As of Version 2.1 of the Java Servlet API, use
* <code>encodeURL()</code> instead.
*/
@Override
@Deprecated
public String encodeUrl(String url) {
return (encodeURL(url));
}
/**
* Send an acknowledgement of a request.
*
* @exception IOException if an input/output error occurs
*/
public void sendAcknowledgement()
throws IOException {
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
getCoyoteResponse().action(ActionCode.ACK, null);
}
/**
* Send an error response with the specified status and a
* default message.
*
* @param status HTTP status code to send
*
* @exception IllegalStateException if this response has
* already been committed
* @exception IOException if an input/output error occurs
*/
@Override
public void sendError(int status) throws IOException {
sendError(status, null);
}
/**
* Send an error response with the specified status and message.
*
* @param status HTTP status code to send
* @param message Corresponding message to send
*
* @exception IllegalStateException if this response has
* already been committed
* @exception IOException if an input/output error occurs
*/
@Override
public void sendError(int status, String message) throws IOException {
if (isCommitted()) {
throw new IllegalStateException
(sm.getString("coyoteResponse.sendError.ise"));
}
// Ignore any call from an included servlet
if (included) {
return;
}
setError();
getCoyoteResponse().setStatus(status);
getCoyoteResponse().setMessage(message);
// Clear any data content that has been buffered
resetBuffer();
// Cause the response to be finished (from the application perspective)
setSuspended(true);
}
/**
* Send a temporary redirect to the specified redirect location URL.
*
* @param location Location URL to redirect to
*
* @exception IllegalStateException if this response has
* already been committed
* @exception IOException if an input/output error occurs
*/
@Override
public void sendRedirect(String location) throws IOException {
sendRedirect(location, SC_FOUND);
}
/**
* Internal method that allows a redirect to be sent with a status other
* than {@link HttpServletResponse#SC_FOUND} (302). No attempt is made to
* validate the status code.
*/
public void sendRedirect(String location, int status) throws IOException {
if (isCommitted()) {
throw new IllegalStateException
(sm.getString("coyoteResponse.sendRedirect.ise"));
}
// Ignore any call from an included servlet
if (included) {
return;
}
// Clear any data content that has been buffered
resetBuffer(true);
// Generate a temporary redirect to the specified location
try {
String absolute = toAbsolute(location);
setStatus(status);
setHeader("Location", absolute);
if (getContext().getSendRedirectBody()) {
PrintWriter writer = getWriter();
writer.print(sm.getString("coyoteResponse.sendRedirect.note",
RequestUtil.filter(absolute)));
flushBuffer();
}
} catch (IllegalArgumentException e) {
setStatus(SC_NOT_FOUND);
}
// Cause the response to be finished (from the application perspective)
setSuspended(true);
}
/**
* Set the specified date header to the specified value.
*
* @param name Name of the header to set
* @param value Date value to be set
*/
@Override
public void setDateHeader(String name, long value) {
if (name == null || name.length() == 0) {
return;
}
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
if (format == null) {
format = new SimpleDateFormat(FastHttpDateFormat.RFC1123_DATE,
Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
}
setHeader(name, FastHttpDateFormat.formatDate(value, format));
}
/**
* Set the specified header to the specified value.
*
* @param name Name of the header to set
* @param value Value to be set
*/
@Override
public void setHeader(String name, String value) {
if (name == null || name.length() == 0 || value == null) {
return;
}
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
char cc=name.charAt(0);
if (cc=='C' || cc=='c') {
if (checkSpecialHeader(name, value))
return;
}
getCoyoteResponse().setHeader(name, value);
}
/**
* Set the specified integer header to the specified value.
*
* @param name Name of the header to set
* @param value Integer value to be set
*/
@Override
public void setIntHeader(String name, int value) {
if (name == null || name.length() == 0) {
return;
}
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
setHeader(name, "" + value);
}
/**
* Set the HTTP status to be returned with this response.
*
* @param status The new HTTP status
*/
@Override
public void setStatus(int status) {
setStatus(status, null);
}
/**
* Set the HTTP status and message to be returned with this response.
*
* @param status The new HTTP status
* @param message The associated text message
*
* @deprecated As of Version 2.1 of the Java Servlet API, this method
* has been deprecated due to the ambiguous meaning of the message
* parameter.
*/
@Override
@Deprecated
public void setStatus(int status, String message) {
if (isCommitted()) {
return;
}
// Ignore any call from an included servlet
if (included) {
return;
}
getCoyoteResponse().setStatus(status);
getCoyoteResponse().setMessage(message);
}
// ------------------------------------------------------ Protected Methods
/**
* Return <code>true</code> if the specified URL should be encoded with
* a session identifier. This will be true if all of the following
* conditions are met:
* <ul>
* <li>The request we are responding to asked for a valid session
* <li>The requested session ID was not received via a cookie
* <li>The specified URL points back to somewhere within the web
* application that is responding to this request
* </ul>
*
* @param location Absolute URL to be validated
*/
protected boolean isEncodeable(final String location) {
if (location == null) {
return (false);
}
// Is this an intra-document reference?
if (location.startsWith("#")) {
return (false);
}
// Are we in a valid session that is not using cookies?
final Request hreq = request;
final Session session = hreq.getSessionInternal(false);
if (session == null) {
return (false);
}
if (hreq.isRequestedSessionIdFromCookie()) {
return (false);
}
// Is URL encoding permitted
if (!hreq.getServletContext().getEffectiveSessionTrackingModes().
contains(SessionTrackingMode.URL)) {
return false;
}
if (SecurityUtil.isPackageProtectionEnabled()) {
return (
AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run(){
return Boolean.valueOf(doIsEncodeable(hreq, session, location));
}
})).booleanValue();
} else {
return doIsEncodeable(hreq, session, location);
}
}
private boolean doIsEncodeable(Request hreq, Session session,
String location) {
// Is this a valid absolute URL?
URL url = null;
try {
url = new URL(location);
} catch (MalformedURLException e) {
return (false);
}
// Does this URL match down to (and including) the context path?
if (!hreq.getScheme().equalsIgnoreCase(url.getProtocol())) {
return (false);
}
if (!hreq.getServerName().equalsIgnoreCase(url.getHost())) {
return (false);
}
int serverPort = hreq.getServerPort();
if (serverPort == -1) {
if ("https".equals(hreq.getScheme())) {
serverPort = 443;
} else {
serverPort = 80;
}
}
int urlPort = url.getPort();
if (urlPort == -1) {
if ("https".equals(url.getProtocol())) {
urlPort = 443;
} else {
urlPort = 80;
}
}
if (serverPort != urlPort) {
return (false);
}
String contextPath = getContext().getPath();
if (contextPath != null) {
String file = url.getFile();
if ((file == null) || !file.startsWith(contextPath)) {
return (false);
}
String tok = ";" +
SessionConfig.getSessionUriParamName(request.getContext()) +
"=" + session.getIdInternal();
if( file.indexOf(tok, contextPath.length()) >= 0 ) {
return (false);
}
}
// This URL belongs to our web application, so it is encodeable
return (true);
}
/**
* Convert (if necessary) and return the absolute URL that represents the
* resource referenced by this possibly relative URL. If this URL is
* already absolute, return it unchanged.
*
* @param location URL to be (possibly) converted and then returned
*
* @exception IllegalArgumentException if a MalformedURLException is
* thrown when converting the relative URL to an absolute one
*/
protected String toAbsolute(String location) {
if (location == null) {
return (location);
}
boolean leadingSlash = location.startsWith("/");
if (location.startsWith("//")) {
// Scheme relative
redirectURLCC.recycle();
// Add the scheme
String scheme = request.getScheme();
try {
redirectURLCC.append(scheme, 0, scheme.length());
redirectURLCC.append(':');
redirectURLCC.append(location, 0, location.length());
return redirectURLCC.toString();
} catch (IOException e) {
IllegalArgumentException iae =
new IllegalArgumentException(location);
iae.initCause(e);
throw iae;
}
} else if (leadingSlash || !hasScheme(location)) {
redirectURLCC.recycle();
String scheme = request.getScheme();
String name = request.getServerName();
int port = request.getServerPort();
try {
redirectURLCC.append(scheme, 0, scheme.length());
redirectURLCC.append("://", 0, 3);
redirectURLCC.append(name, 0, name.length());
if ((scheme.equals("http") && port != 80)
|| (scheme.equals("https") && port != 443)) {
redirectURLCC.append(':');
String portS = port + "";
redirectURLCC.append(portS, 0, portS.length());
}
if (!leadingSlash) {
String relativePath = request.getDecodedRequestURI();
int pos = relativePath.lastIndexOf('/');
CharChunk encodedURI = null;
final String frelativePath = relativePath;
final int fend = pos;
if (SecurityUtil.isPackageProtectionEnabled() ){
try{
encodedURI = AccessController.doPrivileged(
new PrivilegedExceptionAction<CharChunk>(){
@Override
public CharChunk run() throws IOException{
return urlEncoder.encodeURL(frelativePath, 0, fend);
}
});
} catch (PrivilegedActionException pae){
IllegalArgumentException iae =
new IllegalArgumentException(location);
iae.initCause(pae.getException());
throw iae;
}
} else {
encodedURI = urlEncoder.encodeURL(relativePath, 0, pos);
}
redirectURLCC.append(encodedURI);
encodedURI.recycle();
redirectURLCC.append('/');
}
redirectURLCC.append(location, 0, location.length());
normalize(redirectURLCC);
} catch (IOException e) {
IllegalArgumentException iae =
new IllegalArgumentException(location);
iae.initCause(e);
throw iae;
}
return redirectURLCC.toString();
} else {
return (location);
}
}
/*
* Removes /./ and /../ sequences from absolute URLs.
* Code borrowed heavily from CoyoteAdapter.normalize()
*/
private void normalize(CharChunk cc) {
// Strip query string and/or fragment first as doing it this way makes
// the normalization logic a lot simpler
int truncate = cc.indexOf('?');
if (truncate == -1) {
truncate = cc.indexOf('#');
}
char[] truncateCC = null;
if (truncate > -1) {
truncateCC = Arrays.copyOfRange(cc.getBuffer(),
cc.getStart() + truncate, cc.getEnd());
cc.setEnd(cc.getStart() + truncate);
}
if (cc.endsWith("/.") || cc.endsWith("/..")) {
try {
cc.append('/');
} catch (IOException e) {
throw new IllegalArgumentException(cc.toString(), e);
}
}
char[] c = cc.getChars();
int start = cc.getStart();
int end = cc.getEnd();
int index = 0;
int startIndex = 0;
// Advance past the first three / characters (should place index just
// scheme://host[:port]
for (int i = 0; i < 3; i++) {
startIndex = cc.indexOf('/', startIndex + 1);
}
// Remove /./
index = startIndex;
while (true) {
index = cc.indexOf("/./", 0, 3, index);
if (index < 0) {
break;
}
copyChars(c, start + index, start + index + 2,
end - start - index - 2);
end = end - 2;
cc.setEnd(end);
}
// Remove /../
index = startIndex;
int pos;
while (true) {
index = cc.indexOf("/../", 0, 4, index);
if (index < 0) {
break;
}
// Can't go above the server root
if (index == startIndex) {
throw new IllegalArgumentException();
}
int index2 = -1;
for (pos = start + index - 1; (pos >= 0) && (index2 < 0); pos --) {
if (c[pos] == (byte) '/') {
index2 = pos;
}
}
copyChars(c, start + index2, start + index + 3,
end - start - index - 3);
end = end + index2 - index - 3;
cc.setEnd(end);
index = index2;
}
// Add the query string and/or fragment (if present) back in
if (truncateCC != null) {
try {
cc.append(truncateCC, 0, truncateCC.length);
} catch (IOException ioe) {
throw new IllegalArgumentException(ioe);
}
}
}
private void copyChars(char[] c, int dest, int src, int len) {
for (int pos = 0; pos < len; pos++) {
c[pos + dest] = c[pos + src];
}
}
/**
* Determine if an absolute URL has a path component
*/
private boolean hasPath(String uri) {
int pos = uri.indexOf("://");
if (pos < 0) {
return false;
}
pos = uri.indexOf('/', pos + 3);
if (pos < 0) {
return false;
}
return true;
}
/**
* Determine if a URI string has a <code>scheme</code> component.
*/
private boolean hasScheme(String uri) {
int len = uri.length();
for(int i=0; i < len ; i++) {
char c = uri.charAt(i);
if(c == ':') {
return i > 0;
} else if(!URL.isSchemeChar(c)) {
return false;
}
}
return false;
}
/**
* Return the specified URL with the specified session identifier
* suitably encoded.
*
* @param url URL to be encoded with the session id
* @param sessionId Session id to be included in the encoded URL
*/
protected String toEncoded(String url, String sessionId) {
if ((url == null) || (sessionId == null)) {
return (url);
}
String path = url;
String query = "";
String anchor = "";
int question = url.indexOf('?');
if (question >= 0) {
path = url.substring(0, question);
query = url.substring(question);
}
int pound = path.indexOf('#');
if (pound >= 0) {
anchor = path.substring(pound);
path = path.substring(0, pound);
}
StringBuilder sb = new StringBuilder(path);
if( sb.length() > 0 ) { // jsessionid can't be first.
sb.append(";");
sb.append(SessionConfig.getSessionUriParamName(
request.getContext()));
sb.append("=");
sb.append(sessionId);
}
sb.append(anchor);
sb.append(query);
return (sb.toString());
}
}
|
plumer/codana
|
tomcat_files/8.0.22/Response (2).java
|
Java
|
mit
| 50,758
|
/*
* Copyright (c) 2015 XING AG (http://xing.com/)
*
* 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 com.xing.android.sdk.model.user.field;
import com.xing.android.sdk.json.Field;
/**
* Represents the photos of a user.
*
* @author david.gonzalez
*/
@SuppressWarnings("unused")
public class PhotoUrlsField extends Field {
public static final PhotoUrlsField LARGE = new PhotoUrlsField("large");
public static final PhotoUrlsField MAXI_THUMB = new PhotoUrlsField("maxi_thumb");
public static final PhotoUrlsField MEDIUM_THUMB = new PhotoUrlsField("medium_thumb");
public static final PhotoUrlsField MINI_THUMB = new PhotoUrlsField("mini_thumb");
public static final PhotoUrlsField THUMB = new PhotoUrlsField("thumb");
public static final PhotoUrlsField SIZE_32X32 = new PhotoUrlsField("size_32x32");
public static final PhotoUrlsField SIZE_48X48 = new PhotoUrlsField("size_48x48");
public static final PhotoUrlsField SIZE_64X64 = new PhotoUrlsField("size_64x64");
public static final PhotoUrlsField SIZE_96X96 = new PhotoUrlsField("size_96x96");
public static final PhotoUrlsField SIZE_128X128 = new PhotoUrlsField("size_128x128");
public static final PhotoUrlsField SIZE_192X192 = new PhotoUrlsField("size_192x192");
public static final PhotoUrlsField SIZE_256X256 = new PhotoUrlsField("size_256x256");
public static final PhotoUrlsField SIZE_1024X1024 = new PhotoUrlsField("size_1024x1024");
public static final PhotoUrlsField SIZE_ORIGINAL = new PhotoUrlsField("size_original");
private PhotoUrlsField(String name) {
super(name);
}
}
|
CiprianU/xing-android-sdk
|
sdk/src/main/java/com/xing/android/sdk/model/user/field/PhotoUrlsField.java
|
Java
|
mit
| 2,653
|
<?php
namespace Tests\BrainExe\Core\Util;
use BrainExe\Core\Util\Time;
use PHPUnit\Framework\TestCase;
/**
* @covers \BrainExe\Core\Util\Time
*/
class TimeTest extends TestCase
{
/**
* @var Time
*/
private $subject;
public function setUp()
{
$this->subject = new Time();
}
public function testNow()
{
$actual = $this->subject->now();
$this->assertEquals(time(), $actual, "current time", 1);
}
public function testDate()
{
$actual = $this->subject->date('y');
$expected = date('y');
$this->assertEquals($expected, $actual);
}
public function testMicrotime()
{
$actual = $this->subject->microtime();
$this->assertEquals(microtime(true), $actual, "microtime", 100);
}
public function testStrtotime()
{
$string = 'tomorrow';
$actual = $this->subject->strtotime($string);
$this->assertInternalType('integer', $actual);
}
}
|
brainexe/core
|
Tests/BrainExe/Core/Util/TimeTest.php
|
PHP
|
mit
| 1,000
|
using ControlePontos.Dominio.Model;
using ControlePontos.Dominio.Model.Configuracao;
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace ControlePontos.Control
{
internal class CheckBoxCell : DataGridViewCheckBoxCell, IDiaTrabalhoCell
{
public void AddedCell(ConfiguracaoApp appConfig, DiaTrabalho dia)
{
this.UpdateCell(appConfig, dia);
}
public void UpdateCell(ConfiguracaoApp appConfig, DiaTrabalho dia)
{
var config = this.Configuracao() ?? new DiaTrabalhoColumnConfiguracao();
var cor = appConfig.Cores.DiaNormal;
var @readonly = false;
if (dia.Falta)
cor = appConfig.Cores.Falta;
else if (!appConfig.DiasTrabalho.Contains(dia.Data.DayOfWeek))
{
cor = appConfig.Cores.NaoTrabalho;
@readonly = true;
}
else if (appConfig.Feriados.Feriados.Contains(dia.Data.Date))
{
cor = appConfig.Cores.Feriado;
@readonly = true;
}
else if (appConfig.Ferias.Contains(dia.Data.Date))
{
cor = appConfig.Cores.Ferias;
@readonly = true;
}
else if (DateTime.Now.Date == dia.Data.Date)
cor = appConfig.Cores.Hoje;
this.Style.BackColor = cor;
this.SetReadonly(@readonly);
}
private void SetReadonly(bool @readonly)
{
if (@readonly)
{
this.FlatStyle = FlatStyle.Flat;
this.Style.ForeColor = Color.DarkGray;
this.ReadOnly = true;
}
else
{
this.FlatStyle = FlatStyle.Standard;
this.Style.ForeColor = Color.Black;
this.ReadOnly = false;
}
}
private DiaTrabalhoColumnConfiguracao Configuracao()
{
var coluna = this.OwningColumn as CheckBoxColumn;
if (coluna == null)
throw new Exception("OwningColumn invalid!");
return coluna == null ? null : coluna.Configuracao;
}
}
internal class CheckBoxColumn : DataGridViewCheckBoxColumn
{
public DiaTrabalhoColumnConfiguracao Configuracao { get; set; }
public CheckBoxColumn(string nome, string cabecalho, DiaTrabalhoColumnConfiguracao config = null)
{
this.Name = nome;
this.HeaderText = cabecalho;
this.Configuracao = config;
this.CellTemplate = new CheckBoxCell();
if (config != null)
this.ValueType = config.Tipo;
}
}
}
|
cabralRodrigo/controle-pontos
|
ControlePontos.UI/Control/DiaTrabalhoCheckBoxControls.cs
|
C#
|
mit
| 2,788
|
html {
background-color: #e2e2e2;
margin: 0;
padding: 0;
}
body {
background-color: #fff;
border-top: solid 10px #000;
color: #333;
font-size: .85em;
font-family: "Segoe UI", Verdana, Helvetica, Sans-Serif;
margin: 0;
padding: 0;
}
a {
color: #333;
outline: none;
padding-left: 3px;
padding-right: 3px;
text-decoration: underline;
}
a:link, a:visited,
a:active, a:hover {
color: #333;
}
a:hover {
background-color: #c7d1d6;
}
header, footer, hgroup,
nav, section {
display: block;
}
mark {
background-color: #a6dbed;
padding-left: 5px;
padding-right: 5px;
}
.float-left {
float: left;
}
.float-right {
float: right;
}
.clear-fix:after {
content: ".";
clear: both;
display: block;
height: 0;
visibility: hidden;
}
h1, h2, h3,
h4, h5, h6 {
color: #000;
margin-bottom: 0;
padding-bottom: 0;
}
h1 {
font-size: 2em;
}
h2 {
font-size: 1.75em;
}
h3 {
font-size: 1.2em;
}
h4 {
font-size: 1.1em;
}
h5, h6 {
font-size: 1em;
}
h5 a:link, h5 a:visited, h5 a:active {
padding: 0;
text-decoration: none;
}
/* main layout
----------------------------------------------------------*/
.content-wrapper {
margin: 0 auto;
max-width: 960px;
}
#body {
background-color: #efeeef;
clear: both;
padding-bottom: 35px;
}
.main-content {
background: url("../Images/accent.png") no-repeat;
padding-left: 10px;
padding-top: 30px;
}
.featured + .main-content {
background: url("../Images/heroAccent.png") no-repeat;
}
header .content-wrapper {
padding-top: 20px;
}
footer {
clear: both;
background-color: #e2e2e2;
font-size: .8em;
height: 100px;
}
/* site title
----------------------------------------------------------*/
.site-title {
color: #c8c8c8;
font-family: Rockwell, Consolas, "Courier New", Courier, monospace;
font-size: 2.3em;
margin: 0;
}
.site-title a, .site-title a:hover, .site-title a:active {
background: none;
color: #c8c8c8;
outline: none;
text-decoration: none;
}
/* login
----------------------------------------------------------*/
#login {
display: block;
font-size: .85em;
margin: 0 0 10px;
text-align: right;
}
#login a {
background-color: #d3dce0;
margin-left: 10px;
margin-right: 3px;
padding: 2px 3px;
text-decoration: none;
}
#login a.username {
background: none;
margin: 0;
padding: 0;
text-decoration: underline;
}
#login ul {
margin: 0;
}
#login li {
display: inline;
list-style: none;
}
/* menu
----------------------------------------------------------*/
ul#menu {
font-size: 1.3em;
font-weight: 600;
margin: 0 0 5px;
padding: 0;
text-align: right;
}
ul#menu li {
display: inline;
list-style: none;
padding-left: 15px;
}
ul#menu li a {
background: none;
color: #999;
text-decoration: none;
}
ul#menu li a:hover {
color: #333;
text-decoration: none;
}
/* page elements
----------------------------------------------------------*/
/* featured */
.featured {
background-color: #fff;
}
.featured .content-wrapper {
background-color: #7ac0da;
background-image: -ms-linear-gradient(left, #7ac0da 0%, #a4d4e6 100%);
background-image: -o-linear-gradient(left, #7ac0da 0%, #a4d4e6 100%);
background-image: -webkit-gradient(linear, left top, right top, color-stop(0, #7ac0da), color-stop(1, #a4d4e6));
background-image: -webkit-linear-gradient(left, #7ac0da 0%, #a4d4e6 100%);
background-image: linear-gradient(left, #7ac0da 0%, #a4d4e6 100%);
color: #3e5667;
padding: 20px 40px 30px 40px;
}
.featured hgroup.title h1, .featured hgroup.title h2 {
color: #fff;
}
.featured p {
font-size: 1.1em;
}
/* page titles */
hgroup.title {
margin-bottom: 10px;
}
hgroup.title h1, hgroup.title h2 {
display: inline;
}
hgroup.title h2 {
font-weight: normal;
margin-left: 3px;
}
/* features */
section.feature {
width: 300px;
float: left;
padding: 10px;
}
/* ordered list */
ol.round {
list-style-type: none;
padding-left: 0;
}
ol.round li {
margin: 25px 0;
padding-left: 45px;
}
ol.round li.zero {
background: url("../Images/orderedList0.png") no-repeat;
}
ol.round li.one {
background: url("../Images/orderedList1.png") no-repeat;
}
ol.round li.two {
background: url("../Images/orderedList2.png") no-repeat;
}
ol.round li.three {
background: url("../Images/orderedList3.png") no-repeat;
}
ol.round li.four {
background: url("../Images/orderedList4.png") no-repeat;
}
ol.round li.five {
background: url("../Images/orderedList5.png") no-repeat;
}
ol.round li.six {
background: url("../Images/orderedList6.png") no-repeat;
}
ol.round li.seven {
background: url("../Images/orderedList7.png") no-repeat;
}
ol.round li.eight {
background: url("../Images/orderedList8.png") no-repeat;
}
ol.round li.nine {
background: url("../Images/orderedList9.png") no-repeat;
}
/* content */
article {
float: left;
width: 70%;
}
aside {
float: right;
width: 25%;
}
aside ul {
list-style: none;
padding: 0;
}
aside ul li {
background: url("../Images/bullet.png") no-repeat 0 50%;
padding: 2px 0 2px 20px;
}
.label {
font-weight: 700;
}
/* login page */
#loginForm {
border-right: solid 2px #c8c8c8;
float: left;
width: 55%;
}
#loginForm .validation-error {
display: block;
margin-left: 15px;
}
#loginForm .validation-summary-errors ul {
margin: 0;
padding: 0;
}
#loginForm .validation-summary-errors li {
display: inline;
list-style: none;
margin: 0;
}
#loginForm input {
width: 250px;
}
#loginForm input[type="checkbox"],
#loginForm input[type="submit"],
#loginForm input[type="button"],
#loginForm button {
width: auto;
}
#socialLoginForm {
margin-left: 40px;
float: left;
width: 40%;
}
#socialLoginForm h2 {
margin-bottom: 5px;
}
#socialLoginList button {
margin-bottom: 12px;
}
#logoutForm {
display: inline;
}
/* contact */
.contact h3 {
font-size: 1.2em;
}
.contact p {
margin: 5px 0 0 10px;
}
.contact iframe {
border: 1px solid #333;
margin: 5px 0 0 10px;
}
/* forms */
fieldset {
border: none;
margin: 0;
padding: 0;
}
fieldset legend {
display: none;
}
fieldset ol {
padding: 0;
list-style: none;
}
fieldset ol li {
padding-bottom: 5px;
}
label {
display: block;
font-size: 1.2em;
font-weight: 600;
}
label.checkbox {
display: inline;
}
input, textarea {
border: 1px solid #e2e2e2;
background: #fff;
color: #333;
font-size: 1.2em;
margin: 5px 0 6px 0;
padding: 5px;
width: 300px;
}
textarea {
font-family: inherit;
width: 500px;
}
input:focus, textarea:focus {
border: 1px solid #7ac0da;
}
input[type="checkbox"] {
background: transparent;
border: inherit;
width: auto;
}
input[type="submit"],
input[type="button"],
button {
background-color: #d3dce0;
border: 1px solid #787878;
cursor: pointer;
font-size: 1.2em;
font-weight: 600;
padding: 7px;
margin-right: 8px;
width: auto;
}
td input[type="submit"],
td input[type="button"],
td button {
font-size: 1em;
padding: 4px;
margin-right: 4px;
}
/* info and errors */
.message-info {
border: 1px solid;
clear: both;
padding: 10px 20px;
}
.message-error {
clear: both;
color: #e80c4d;
font-size: 1.1em;
font-weight: bold;
margin: 20px 0 10px 0;
}
.message-success {
color: #7ac0da;
font-size: 1.3em;
font-weight: bold;
margin: 20px 0 10px 0;
}
.error {
color: #e80c4d;
}
/* styles for validation helpers */
.field-validation-error {
color: #e80c4d;
font-weight: bold;
}
.field-validation-valid {
display: none;
}
input.input-validation-error {
border: 1px solid #e80c4d;
}
input[type="checkbox"].input-validation-error {
border: 0 none;
}
.validation-summary-errors {
color: #e80c4d;
font-weight: bold;
font-size: 1.1em;
}
.validation-summary-valid {
display: none;
}
/* tables
----------------------------------------------------------*/
table {
border-collapse: collapse;
border-spacing: 0;
margin-top: 0.75em;
border: 0 none;
}
th {
font-size: 1.2em;
text-align: left;
border: none 0px;
padding-left: 0;
}
th a {
display: block;
position: relative;
}
th a:link, th a:visited, th a:active, th a:hover {
color: #333;
font-weight: 600;
text-decoration: none;
padding: 0;
}
th a:hover {
color: #000;
}
th.asc a, th.desc a {
margin-right: .75em;
}
th.asc a:after, th.desc a:after {
display: block;
position: absolute;
right: 0em;
top: 0;
font-size: 0.75em;
}
th.asc a:after {
content: '▲';
}
th.desc a:after {
content: '▼';
}
td {
padding: 0.25em 2em 0.25em 0em;
border: 0 none;
}
tr.pager td {
padding: 0 0.25em 0 0;
}
/********************
* Mobile Styles *
********************/
@media only screen and (max-width: 850px) {
/* header
----------------------------------------------------------*/
header .float-left,
header .float-right {
float: none;
}
/* logo */
header .site-title {
margin: 10px;
text-align: center;
}
/* login */
#login {
font-size: .85em;
margin: 0 0 12px;
text-align: center;
}
#login ul {
margin: 5px 0;
padding: 0;
}
#login li {
display: inline;
list-style: none;
margin: 0;
padding: 0;
}
#login a {
background: none;
color: #999;
font-weight: 600;
margin: 2px;
padding: 0;
}
#login a:hover {
color: #333;
}
/* menu */
nav {
margin-bottom: 5px;
}
ul#menu {
margin: 0;
padding: 0;
text-align: center;
}
ul#menu li {
margin: 0;
padding: 0;
}
/* main layout
----------------------------------------------------------*/
.main-content,
.featured + .main-content {
background-position: 10px 0;
}
.content-wrapper {
padding-right: 10px;
padding-left: 10px;
}
.featured .content-wrapper {
padding: 10px;
}
/* page content */
article, aside {
float: none;
width: 100%;
}
/* ordered list */
ol.round {
list-style-type: none;
padding-left: 0;
}
ol.round li {
padding-left: 10px;
margin: 25px 0;
}
ol.round li.zero,
ol.round li.one,
ol.round li.two,
ol.round li.three,
ol.round li.four,
ol.round li.five,
ol.round li.six,
ol.round li.seven,
ol.round li.eight,
ol.round li.nine {
background: none;
}
/* features */
section.feature {
float: none;
padding: 10px;
width: auto;
}
section.feature img {
color: #999;
content: attr(alt);
font-size: 1.5em;
font-weight: 600;
}
/* forms */
input {
width: 90%;
}
/* login page */
#loginForm {
border-right: none;
float: none;
width: auto;
}
#loginForm .validation-error {
display: block;
margin-left: 15px;
}
#socialLoginForm {
margin-left: 0;
float: none;
width: auto;
}
/* footer
----------------------------------------------------------*/
footer .float-left,
footer .float-right {
float: none;
}
footer {
text-align: center;
height: auto;
padding: 10px 0;
}
footer p {
margin: 0;
}
}
figure#visualization {
margin-left: 0;
margin-top: 40px;
}
figure#visualization > figcaption{
float: none;
clear: both;
width: 100%;
}
div#graphs > div {
float: left;
width: 135px;
height: 100px;
border: solid 2px #ccc;
padding: 10px;
text-align: center;
}
div#graphs {
font-size: 1.3em;
}
div#graphs span{
font-size: 3em;
font-weight: bold;
display: block;
}
|
teelahti/TD2013JSBus
|
JSBus/Content/Site.css
|
CSS
|
mit
| 13,612
|
/*
The MIT License (MIT)
Copyright (c) 2014, Groupon, Inc.
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 com.groupon.jenkins.dynamic.buildconfiguration;
import hudson.matrix.Combination;
import java.util.Arrays;
import java.util.Collections;
import com.google.common.collect.Iterables;
import com.groupon.jenkins.dynamic.build.execution.BuildType;
import com.groupon.jenkins.dynamic.buildconfiguration.configvalue.ConfigValue;
public abstract class ConfigSection<T extends ConfigValue<?>> {
protected T configValue;
private final String name;
private final MergeStrategy mergeStrategy;
protected enum MergeStrategy {
REPLACE, APPEND
}
protected ConfigSection(String name, T configValue, MergeStrategy mergeStrategy) {
this.name = name;
this.mergeStrategy = mergeStrategy;
this.configValue = configValue;
}
public abstract ShellCommands toScript(Combination combination, BuildType buildType);
protected void merge(ConfigSection<T> otherConfigSection) {
if (!otherConfigSection.getConfigValue().isEmpty()) {
if (mergeStrategy.equals(MergeStrategy.REPLACE)) {
configValue.replace(otherConfigSection.configValue);
} else {
configValue.append(otherConfigSection.configValue);
}
}
}
protected T getConfigValue() {
return configValue;
}
protected void setConfigValue(T config) {
this.configValue = config;
}
protected String getName() {
return name;
}
public boolean isValid() {
return Iterables.isEmpty(getValidationErrors());
}
public Iterable<String> getValidationErrors() {
if (getConfigValue().isValid()) {
return Collections.emptyList();
} else {
return Arrays.asList(String.format("Invalid format for: %s", getName()));
}
}
protected Object getFinalConfigValue() {
return getConfigValue().getValue();
}
public boolean isSpecified() {
return !getConfigValue().isEmpty();
}
}
|
jenkinsci/DotCi
|
src/main/java/com/groupon/jenkins/dynamic/buildconfiguration/ConfigSection.java
|
Java
|
mit
| 2,858
|
FILE(REMOVE_RECURSE
"CMakeFiles/stable_norm_1.dir/stable_norm.cpp.o"
"stable_norm_1.pdb"
"stable_norm_1"
)
# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
INCLUDE(CMakeFiles/stable_norm_1.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)
|
cmeon/Simplex
|
lib/test/CMakeFiles/stable_norm_1.dir/cmake_clean.cmake
|
CMake
|
mit
| 277
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTasksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
// Create tables
$table->increments('id');
$table->string('name');
$table->text('description');
$table->string('status');
$table->integer('sprint_id')->unsigned()->nullable();
$table->integer('project_id')->unsigned()->nullable();
$table->integer('parent_id')->unsigned()->nullable();
$table->timestamps();
// Foreign key relationships
$table->foreign('sprint_id')->references('id')->on('sprints');
$table->foreign('project_id')->references('id')->on('projects');
$table->foreign('parent_id')->references('id')->on('tasks');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('tasks');
}
}
|
WebSpanner/track
|
database/migrations/2016_07_22_223427_create_tasks_table.php
|
PHP
|
mit
| 1,150
|
package tech.letscode.awsexplorer.domain.model;
import org.apache.commons.lang3.Validate;
import javax.annotation.Nonnull;
import java.util.List;
import java.util.function.Consumer;
/**
* @author Oleg Pavlov <oleg.pavlov@aol.com>
*/
public class Bucket
{
private String name;
private List<Directory> directories;
public Bucket(@Nonnull String name, List<Directory> directories)
{
Validate.notNull(name, "name is required");
this.name = name;
this.directories = directories;
}
@Nonnull
public String name()
{
return this.name;
}
public void visitDirectories(@Nonnull Consumer<Directory> consumer)
{
Validate.notNull(consumer, "consumer is required");
if (this.directories != null)
{
this.directories.forEach(consumer);
}
}
}
|
opavlov24/aws-s3-explorer
|
src/main/java/tech/letscode/awsexplorer/domain/model/Bucket.java
|
Java
|
mit
| 857
|
#!/usr/bin/env python
# https://www.codeeval.com/open_challenges/1/
import sys
def solve(X, Y, N):
r = []
for i in range(1, N + 1):
if i % X == 0 and i % Y == 0:
r.append('FB')
elif i % X == 0:
r.append('F')
elif i % Y == 0:
r.append('B')
else:
r.append(str(i))
print ' '.join(r)
def main():
for line in sys.stdin:
(X, Y, N) = line.strip().split(' ')
solve(int(X), int(Y), int(N))
if __name__ == '__main__':
main()
|
guozengxin/codeeval
|
easy/fizzBuzz.py
|
Python
|
mit
| 537
|
version https://git-lfs.github.com/spec/v1
oid sha256:7532f5b4891e60d75d6a1d91f80921a3ad8b96ba88a746f05948fc6c6f5a9772
size 137987
|
yogeshsaroya/new-cdnjs
|
ajax/libs/lodash.js/1.0.0-rc.2/lodash.js
|
JavaScript
|
mit
| 131
|
package sanitize
import(
"os"
"encoding/json"
)
// Load a new whitelist from a JSON file
func WhitelistFromFile(filepath string) (*Whitelist, error) {
bytes, err := readFileToBytes(filepath)
if err != nil {
return nil, err
}
whitelist, err := NewWhitelist(bytes)
return whitelist, nil
}
// helper function to read entirety of provided file into byte slice
func readFileToBytes(filepath string) ([]byte, error) {
f, err := os.Open(filepath)
if err != nil {
return nil, err
}
// prepare byte slice to read json file into
fileInfo, err := f.Stat()
bytes := make([]byte, fileInfo.Size())
_, err = f.Read(bytes)
return bytes, err
}
// Create a new whitelist from JSON configuration
func NewWhitelist(jsonData []byte) (*Whitelist, error) {
// unmarshal json file into contract-free interface
configuration := &Whitelist{}
err := json.Unmarshal(jsonData, configuration)
return configuration, err
}
|
maxwells/sanitize
|
whitelist_parser.go
|
GO
|
mit
| 921
|
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* 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.
*/
@org.spongepowered.api.util.annotation.NonnullByDefault package org.spongepowered.api.service.permission;
|
SpongeHistory/SpongeAPI-History
|
src/main/java/org/spongepowered/api/service/permission/package-info.java
|
Java
|
mit
| 1,358
|
#ifndef IMAPC_STORAGE_H
#define IMAPC_STORAGE_H
#include "index-storage.h"
#include "imapc-settings.h"
#define IMAPC_STORAGE_NAME "imapc"
#define IMAPC_LIST_ESCAPE_CHAR '%'
#define IMAPC_LIST_BROKEN_CHAR '~'
struct imap_arg;
struct imapc_untagged_reply;
struct imapc_command_reply;
struct imapc_mailbox;
struct imapc_storage_client;
typedef void imapc_storage_callback_t(const struct imapc_untagged_reply *reply,
struct imapc_storage_client *client);
typedef void imapc_mailbox_callback_t(const struct imapc_untagged_reply *reply,
struct imapc_mailbox *mbox);
struct imapc_storage_event_callback {
char *name;
imapc_storage_callback_t *callback;
};
struct imapc_mailbox_event_callback {
const char *name;
imapc_mailbox_callback_t *callback;
};
#define IMAPC_HAS_FEATURE(mstorage, feature) \
(((mstorage)->set->parsed_features & feature) != 0)
#define IMAPC_BOX_HAS_FEATURE(mbox, feature) \
(((mbox)->storage->set->parsed_features & feature) != 0)
struct imapc_namespace {
const char *prefix;
char separator;
enum mail_namespace_type type;
};
struct imapc_storage_client {
int refcount;
/* either one of these may not be available: */
struct imapc_storage *_storage;
struct imapc_mailbox_list *_list;
struct imapc_client *client;
ARRAY(struct imapc_storage_event_callback) untagged_callbacks;
unsigned int auth_failed:1;
unsigned int destroying:1;
};
struct imapc_storage {
struct mail_storage storage;
const struct imapc_settings *set;
struct ioloop *root_ioloop;
struct imapc_storage_client *client;
struct imapc_mailbox *cur_status_box;
struct mailbox_status *cur_status;
unsigned int reopen_count;
ARRAY(struct imapc_namespace) remote_namespaces;
unsigned int namespaces_requested:1;
};
struct imapc_mail_cache {
uint32_t uid;
/* either fd != -1 or buf != NULL */
int fd;
buffer_t *buf;
};
struct imapc_fetch_request {
ARRAY(struct imapc_mail *) mails;
};
struct imapc_mailbox {
struct mailbox box;
struct imapc_storage *storage;
struct imapc_client_mailbox *client_box;
struct mail_index_transaction *delayed_sync_trans;
struct mail_index_view *sync_view, *delayed_sync_view;
struct mail_cache_view *delayed_sync_cache_view;
struct mail_cache_transaction_ctx *delayed_sync_cache_trans;
struct timeout *to_idle_check, *to_idle_delay;
ARRAY(struct imapc_fetch_request *) fetch_requests;
/* if non-empty, contains the latest FETCH command we're going to be
sending soon (but still waiting to see if we can increase its
UID range) */
string_t *pending_fetch_cmd;
struct imapc_fetch_request *pending_fetch_request;
struct timeout *to_pending_fetch_send;
ARRAY(struct imapc_mailbox_event_callback) untagged_callbacks;
ARRAY(struct imapc_mailbox_event_callback) resp_text_callbacks;
enum mail_flags permanent_flags;
uint32_t highest_nonrecent_uid;
ARRAY_TYPE(uint32_t) delayed_expunged_uids;
uint32_t sync_uid_validity;
uint32_t sync_uid_next;
uint32_t sync_fetch_first_uid;
uint32_t sync_next_lseq;
uint32_t sync_next_rseq;
uint32_t exists_count;
uint32_t min_append_uid;
char *sync_gmail_pop3_search_tag;
/* keep the previous fetched message body cached,
mainly for partial IMAP fetches */
struct imapc_mail_cache prev_mail_cache;
uint32_t prev_skipped_rseq, prev_skipped_uid;
struct imapc_sync_context *sync_ctx;
const char *guid_fetch_field_name;
struct imapc_search_context *search_ctx;
unsigned int selecting:1;
unsigned int syncing:1;
unsigned int initial_sync_done:1;
unsigned int selected:1;
unsigned int exists_received:1;
};
struct imapc_simple_context {
struct imapc_storage_client *client;
int ret;
};
int imapc_storage_client_create(struct mail_namespace *ns,
const struct imapc_settings *imapc_set,
const struct mail_storage_settings *mail_set,
struct imapc_storage_client **client_r,
const char **error_r);
void imapc_storage_client_unref(struct imapc_storage_client **client);
struct mail_save_context *
imapc_save_alloc(struct mailbox_transaction_context *_t);
int imapc_save_begin(struct mail_save_context *ctx, struct istream *input);
int imapc_save_continue(struct mail_save_context *ctx);
int imapc_save_finish(struct mail_save_context *ctx);
void imapc_save_cancel(struct mail_save_context *ctx);
int imapc_copy(struct mail_save_context *ctx, struct mail *mail);
int imapc_transaction_save_commit_pre(struct mail_save_context *ctx);
void imapc_transaction_save_commit_post(struct mail_save_context *ctx,
struct mail_index_transaction_commit_result *result);
void imapc_transaction_save_rollback(struct mail_save_context *ctx);
void imapc_mailbox_run(struct imapc_mailbox *mbox);
void imapc_mailbox_run_nofetch(struct imapc_mailbox *mbox);
void imapc_mail_cache_free(struct imapc_mail_cache *cache);
int imapc_mailbox_select(struct imapc_mailbox *mbox);
bool imap_resp_text_code_parse(const char *str, enum mail_error *error_r);
void imapc_copy_error_from_reply(struct imapc_storage *storage,
enum mail_error default_error,
const struct imapc_command_reply *reply);
void imapc_simple_context_init(struct imapc_simple_context *sctx,
struct imapc_storage_client *client);
void imapc_simple_run(struct imapc_simple_context *sctx);
void imapc_simple_callback(const struct imapc_command_reply *reply,
void *context);
int imapc_mailbox_commit_delayed_trans(struct imapc_mailbox *mbox,
bool *changes_r);
void imapc_mailbox_noop(struct imapc_mailbox *mbox);
void imapc_mailbox_set_corrupted(struct imapc_mailbox *mbox,
const char *reason, ...) ATTR_FORMAT(2, 3);
void imapc_storage_client_register_untagged(struct imapc_storage_client *client,
const char *name,
imapc_storage_callback_t *callback);
void imapc_mailbox_register_untagged(struct imapc_mailbox *mbox,
const char *name,
imapc_mailbox_callback_t *callback);
void imapc_mailbox_register_resp_text(struct imapc_mailbox *mbox,
const char *key,
imapc_mailbox_callback_t *callback);
void imapc_mailbox_register_callbacks(struct imapc_mailbox *mbox);
#endif
|
dscho/dovecot
|
src/lib-storage/index/imapc/imapc-storage.h
|
C
|
mit
| 6,085
|
/**
* Albores, Allyssa
* Bedio, Aiden Justin
* Malaki, Earl Timothy
* Paler, Timothy River
* <p>
* BSCS - II | UP - Cebu
* CMSC22 - OOP
* Final Project
* <p>
* Done:
* - basic skeleton code for concrete monster
* <p>
* To Do:
* - add specific identity/behaviour (skills, capabilities, etc.)
* - do this to the remaining monsters
* <p>
* game.Note:
* <p>
* Done:
* - basic skeleton code for concrete monster
* <p>
* To Do:
* - add specific identity/behaviour (skills, capabilities, etc.)
* - do this to the remaining monsters
* <p>
* game.Note:
* <p>
* Done:
* - basic skeleton code for concrete monster
* <p>
* To Do:
* - add specific identity/behaviour (skills, capabilities, etc.)
* - do this to the remaining monsters
* <p>
* game.Note:
* <p>
* Done:
* - basic skeleton code for concrete monster
* <p>
* To Do:
* - add specific identity/behaviour (skills, capabilities, etc.)
* - do this to the remaining monsters
* <p>
* game.Note:
* <p>
* Done:
* - basic skeleton code for concrete monster
* <p>
* To Do:
* - add specific identity/behaviour (skills, capabilities, etc.)
* - do this to the remaining monsters
* <p>
* game.Note:
* <p>
* Done:
* - basic skeleton code for concrete monster
* <p>
* To Do:
* - add specific identity/behaviour (skills, capabilities, etc.)
* - do this to the remaining monsters
* <p>
* game.Note:
* <p>
* Done:
* - basic skeleton code for concrete monster
* <p>
* To Do:
* - add specific identity/behaviour (skills, capabilities, etc.)
* - do this to the remaining monsters
* <p>
* game.Note:
*/
/**
* Done:
* - basic skeleton code for concrete monster
*
* To Do:
* - add specific identity/behaviour (skills, capabilities, etc.)
* - do this to the remaining monsters
*
* game.Note:
*
*/
package game.monsters;
import game.SkillCost;
import org.newdawn.slick.Animation;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.SpriteSheet;
import org.newdawn.slick.openal.Audio;
import org.newdawn.slick.openal.AudioLoader;
import org.newdawn.slick.util.ResourceLoader;
import java.io.IOException;
public class Monster3 extends Monster {
private Animation animationIdle;
private Animation animationSkill1;
private Animation animationSkill2;
private Animation animationSkillUlt;
private Image[] skillIcons;
// TODO enter proper duration of skill animation when sprites are done
private Animation animationHumanIdle;
private final SkillCost costSkill1 = new SkillCost(3, 0, 0, 3);
private final SkillCost costSkill2 = new SkillCost(0, 7, 7, 0);
private final SkillCost costSkillUlt = new SkillCost(12, 12, 12, 12);
private SkillCost currResources;
// TODO enter proper duration of skill animation when sprites are done
private static final int skill1Duration = 2100;
private static final int skill2Duration = 3000;
private static final int skillUltDuration = 4050;
private Audio monsterSfx1;
private Audio monsterSfx2;
private Audio monsterSfx3;
private static final int skill1Cooldown = 5000;
private static final int skill2Cooldown = 7000;
private static final int skillUltCooldown = 15000;
private static final int frameDurationMonsterIdle = 260;
private static final int frameDurationHumanIdle = 300;
private static final int frameDurationSkill1 = 150;
private static final int frameDurationSkill2 = 250;
private static final int frameDurationSkillUlt = 150;
private static final int damageSkill1 = 15;
private static final int damageSkill2 = 25;
private static final int damageSkillUlt = 35;
private Image imageFaceHealthBar;
//fire
public Monster3(int playerNumber) throws SlickException {
super();
try {
monsterSfx1 = AudioLoader.getAudio("OGG", ResourceLoader.getResourceAsStream("Assets/Sound Effects/Flame/Breathe_Fire.ogg")); //DELAY
monsterSfx2 = AudioLoader.getAudio("OGG", ResourceLoader.getResourceAsStream("Assets/Sound Effects/Flame/Scorched_Earth.ogg")); //PWEDE
monsterSfx3 = AudioLoader.getAudio("OGG", ResourceLoader.getResourceAsStream("Assets/Sound Effects/Flame/Fireblast.ogg")); //NOPE
} catch (IOException e) {
e.printStackTrace();
}
skillIcons = new Image[]{
new Image("Assets/Graphics/Monster and Human Sprites/Flame/Fire fist.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/Firefly.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/X-Burner.png")
};
if (playerNumber == 1) {
animationIdle = new Animation(new SpriteSheet("Assets/Graphics/Monster and Human Sprites/Flame/Flame - Idle P1.png", 600, 300, 0), frameDurationMonsterIdle);
animationHumanIdle = new Animation(new SpriteSheet("Assets/Graphics/Monster and Human Sprites/Flame/Flame - Human P1.png", 150, 150, 0), frameDurationHumanIdle);
animationSkill1 = new Animation(new SpriteSheet("Assets/Graphics/Monster and Human Sprites/Flame/firefist p1.png", 600, 300, 0), frameDurationSkill1);
animationSkill2 = new Animation(new SpriteSheet("Assets/Graphics/Monster and Human Sprites/Flame/FireFlyAni.png", 600, 300, 0), frameDurationSkill2);
imageFaceHealthBar = new Image("Assets/Graphics/Monster and Human Sprites/Flame/Flame - Face Health Bar P1.png");
Image[] skillUlt = new Image[]{
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn00.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn01.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn02.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn03.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn04.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn05.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn06.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn07.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn08.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn09.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn10.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn11.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn12.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn13.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn14.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn15.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn16.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn17.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn18.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn19.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn20.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn21.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn22.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn23.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn24.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn25.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p1/xburn26.png"),
};
int[] duration = new int[]{
150,
150,
150,
150,
150,
150, //6
150,
150,
150,
150, //10
150,
150,
150,
150,
150,
150,
150,
150,
150,
150, //20
150,
150,
150,
150,
150,
150,
150
};
animationSkillUlt = new Animation(skillUlt, duration);
} else if (playerNumber == 2) {
animationIdle = new Animation(new SpriteSheet("Assets/Graphics/Monster and Human Sprites/Flame/Flame - Idle P2.png", 600, 300, 0), frameDurationMonsterIdle);
animationHumanIdle = new Animation(new SpriteSheet("Assets/Graphics/Monster and Human Sprites/Flame/Flame - Human P2.png", 150, 150, 0), frameDurationHumanIdle);
animationSkill1 = new Animation(new SpriteSheet("Assets/Graphics/Monster and Human Sprites/Flame/firefist p2.png", 600, 300, 0), frameDurationSkill1);
animationSkill2 = new Animation(new SpriteSheet("Assets/Graphics/Monster and Human Sprites/Flame/FireFlyAni.png", 600, 300, 0), frameDurationSkill2);
imageFaceHealthBar = new Image("Assets/Graphics/Monster and Human Sprites/Flame/Flame - Face Health Bar P2.png");
Image[] skillUlt = new Image[]{
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn00.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn01.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn02.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn03.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn04.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn05.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn06.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn07.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn08.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn09.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn10.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn11.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn12.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn13.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn14.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn15.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn16.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn17.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn18.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn19.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn20.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn21.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn22.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn23.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn24.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn25.png"),
new Image("Assets/Graphics/Monster and Human Sprites/Flame/p2/xburn26.png"),
};
int[] duration = new int[]{
150,
150,
150,
150,
150,
150, //6
150,
150,
150,
150, //10
150,
150,
150,
150,
150,
150,
150,
150,
150,
150, //20
150,
150,
150,
150,
150,
150,
150
};
animationSkillUlt = new Animation(skillUlt, duration);
}
}
@Override
public Image[] getSkillIcons() {
return skillIcons;
}
public void skill1() {
super.setDamage(damageSkill1);
super.doSkillCost(costSkill1);
getAnimationSkill1().restart();
monsterSfx1.playAsSoundEffect(1.0f, 1.0f, false);
}
public void skill2() {
super.setDamage(damageSkill2);
super.doSkillCost(costSkill2);
getAnimationSkill2().restart();
monsterSfx2.playAsSoundEffect(1.0f, 1.0f, false);
}
public void skillUlt() {
super.setDamage(damageSkillUlt);
super.doSkillCost(costSkillUlt);
getAnimationSkillUlt().restart();
monsterSfx3.playAsSoundEffect(1.0f, 1.0f, false);
}
public int getDurationSkill1() {
return skill1Duration;
}
@Override
public int getDurationSkill2() {
return skill2Duration;
}
@Override
public int getDurationSkillUlt() {
return skillUltDuration;
}
@Override
public int getCooldownSkill1() {
return skill1Cooldown;
}
@Override
public int getCooldownSkill2() {
return skill2Cooldown;
}
@Override
public int getCooldownSkillUlt() {
return skillUltCooldown;
}
@Override
public Animation getAnimationIdle() {
return animationIdle;
}
@Override
public Animation getAnimationHumanIdle() {
return animationHumanIdle;
}
@Override
public Animation getAnimationSkill1() {
return animationSkill1;
}
@Override
public Animation getAnimationSkill2() {
return animationSkill2;
}
@Override
public Animation getAnimationSkillUlt() {
return animationSkillUlt;
}
@Override
public SkillCost getCostSkill1() {
return costSkill1;
}
@Override
public SkillCost getCostSkill2() {
return costSkill2;
}
@Override
public SkillCost getCostSkillUlt() {
return costSkillUlt;
}
@Override
public Image getImageFaceHealthBar() {
return imageFaceHealthBar;
}
public static int getFrameDurationMonsterIdle() {
return frameDurationMonsterIdle;
}
public static int getFrameDurationHumanIdle() {
return frameDurationHumanIdle;
}
}
|
earlmalaki/BeatBitBeat
|
src/game/monsters/Monster3.java
|
Java
|
mit
| 15,628
|
package evergarden.fxchart.chart;
import java.util.Comparator;
import charlotte.tools.LongTools;
public class PriceData {
public static double DEF_PRICE = 120.0;
private long _sec;
private double _ask;
private double _bid;
public PriceData(long sec, double ask, double bid) {
_sec = sec;
_ask = ask;
_bid = bid;
}
public long getSec() {
return _sec;
}
public double getAsk() {
return _ask;
}
public double getBid() {
return _bid;
}
public double getMid() {
return (_ask + _bid) / 2.0;
}
public static Comparator<PriceData> comp = new Comparator<PriceData>() {
@Override
public int compare(PriceData p1, PriceData p2) {
return LongTools.comp.compare(p1._sec, p2._sec);
}
};
public static PriceData target(long sec) {
return new PriceData(sec, DEF_PRICE, DEF_PRICE);
}
public static PriceData createBetween(long sec, PriceData l, PriceData h) {
if(l == null && h == null) {
return new PriceData(sec, DEF_PRICE, DEF_PRICE);
}
if(l == null) {
return h;
}
if(h == null) {
return l;
}
return new PriceData(
sec,
getBetween(sec, l._sec, h._sec, l._ask, h._ask),
getBetween(sec, l._sec, h._sec, l._bid, h._bid)
);
}
private static double getBetween(long sec, long lSec, long hSec, double lVal, double hVal) {
long numer = sec - lSec;
long denom = hSec - lSec;
double rate = (double)numer / denom;
return lVal + rate * (hVal - lVal);
}
}
|
stackprobe/Java3
|
evergarden/fxchart/chart/PriceData.java
|
Java
|
mit
| 1,436
|
---
layout: post
title: svn冲突处理
categories: svn
---
冲突处理
大多数情况下svn会自动merge, 这时文件会有G的标志, 当自动merge失败时会有提示, 并生成3个文件, 分别是
f.mine 本地修改的版本
f.rOLDREV 本地修改所基于的版本
f.rNEWREV 其它人修改后提交的版本
直接查看f文件, 可以发起其中有类似如下标志的行
<<<<<< .mine
xx
=======
将这些冲突的地方修改后, 手动将f.mine f.rOLDREV f.rNEWREV文件删除即可
或者用svn resolved命令来删除这些文件
编辑文件时发生冲突
$ svn up Conflict discovered in 'Makefile'. Select: (p) postpone, (df) diff-full, (e) edit, (mc) mine-conflict, (tc) theirs-conflict, (s) show all options: p C Makefile Updated to revision 5. Summary of conflicts: Text conflicts: 1
($ svn up 在 “Makefile” 中发现冲突。 选择: (p) 推迟,(df) 显示全部差异,(e) 编辑, (mc) 我的版本, (tc) 他人的版本, (s) 显示全部选项: p C Makefile 更新到版本 5。 冲突概要: 正文冲突:1 )
多人同时编辑同一个文件时,可能会遇到冲突。别人先于我提交,则当我提交时要先更新。更新可能遇到不能自动解决的冲突
使用工具进行冲突解决
|
icoolworld/icoolworld.github.io
|
_posts/svn/2016-09-27-svn冲突处理.md
|
Markdown
|
mit
| 1,300
|
import ConfigParser
import sys, traceback
from slackclient import SlackClient
from chatterbot import ChatBot
import os
from os import listdir
from os.path import isfile, join
from chatterbot.trainers import ChatterBotCorpusTrainer
config = ConfigParser.SafeConfigParser({"host": "searchhub.lucidworks.com", "port":80})
config.read('config.cfg')
token = config.get("Slack", "token") # found at https://api.slack.com/web#authentication
channel_str = config.get("Slack", "channels")
channel_names = []
if channel_str:
#print (channel_str)
channels = channel_str.split(",")
for channel in channels:
#print channel
channel_names.append(channel)
storage = config.get("Chatterbot", "storage_dir")
if not os.path.exists(storage):
os.makedirs(storage)
bot_name = config.get("Slack", "bot_name")
print "Starting Slack"
sc = SlackClient(token)
print "Starting Chatterbot"
chatbot = ChatBot(bot_name, storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter",
logic_adapters=[
"chatterbot.adapters.logic.MathematicalEvaluation",
"chatterbot.adapters.logic.TimeLogicAdapter",
"chatterbot.adapters.logic.ClosestMeaningAdapter",
"adapters.SearchHubLogicAdapter"
],
searchhub_host=config.get("SearchHub", "host"),
searchhub_port=config.get("SearchHub", "port"),
input_adapter="adapters.SlackPythonInputAdapter",
output_adapter="adapters.SlackPythonOutputAdapter",
database=storage + "/database.json",
slack_client=sc,
slack_channels=channel_names,
slack_output_channel=config.get("Slack", "output_channel"),
slack_bot_name=bot_name
)
chatbot.set_trainer(ChatterBotCorpusTrainer)
training_dir = "training"
files = [f for f in listdir(training_dir) if isfile(join(training_dir, f)) and f.endswith(".json") and f.find("example.json") == -1]
for file in files:
print "Training on " + file
chatbot.train("training." + file.replace(".json", ""))
# Train based on english greetings corpus
chatbot.train("chatterbot.corpus.english")
# Train based on the english conversations corpus
#chatbot.train("chatterbot.corpus.english.conversations")
print "Starting Chatbot"
while True:
try:
bot_input = chatbot.get_response(None)
except(Exception):
print "Exception"
traceback.print_exc(Exception)
|
gsingers/rtfmbot
|
src/python/run.py
|
Python
|
mit
| 2,559
|
#
# Unified2
#
module Unified2
#
# Signature
#
class Signature
attr_accessor :id, :generator, :revision, :name,
:blank, :references
#
# Initialize signature object
#
# @param [Hash] signature Signature hash attributes
#
# @option signature [Integer] :signature_id Signature id
# @option signature [Integer] :generator_id Generator id
# @option signature [Integer] :revision Signature revision
# @option signature [Integer] :name Signature name
# @option signature [true, false] :blank Signature exists
#
def initialize(signature={})
@id = signature[:signature_id] || 0
@generator = signature[:generator_id]
@references = signature[:references]
@revision = signature[:revision]
@name = signature[:name].strip
@blank = signature[:blank] || false
end
def to_h
hash = {
:id => id,
:generator_id => generator,
:revision => revision,
:name => name,
:blank => blank,
:references => references
}
end
#
# to_string
#
# @return [String] Signature name
#
def to_s
@name
end
#
# Blank?
#
# @return [true, false]
# Return true if signature exists
#
def blank?
@blank
end
#
# References
#
# @return [Array<String,String>] Signature references
#
def references
@references
end
end
end
|
mephux/unified2
|
lib/unified2/signature.rb
|
Ruby
|
mit
| 1,474
|
package pl.grzeslowski.jsupla.protocoljava.impl.serializers.sc;
import org.junit.Test;
import org.mockito.BDDMockito;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import pl.grzeslowski.jsupla.protocol.api.structs.sc.SuplaChannelValue;
import pl.grzeslowski.jsupla.protocol.api.structs.sc.SuplaChannelValuePack;
import pl.grzeslowski.jsupla.protocoljava.api.entities.sc.ChannelValuePack;
import pl.grzeslowski.jsupla.protocoljava.api.serializers.Serializer;
import pl.grzeslowski.jsupla.protocoljava.api.serializers.sc.ChannelValueSerializer;
import pl.grzeslowski.jsupla.protocoljava.impl.serializers.SerializerTest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
import static pl.grzeslowski.jsupla.protocol.common.RandomSupla.RANDOM_SUPLA;
public class ChannelValuePackSerializerImplTest extends SerializerTest<ChannelValuePack, SuplaChannelValuePack> {
@InjectMocks
ChannelValuePackSerializerImpl serializer;
@Mock
ChannelValueSerializer channelValueSerializer;
@Override
protected ChannelValuePack given() {
BDDMockito.given(channelValueSerializer.serialize(any()))
.willReturn(RANDOM_SUPLA.nextObject(SuplaChannelValue.class));
return super.given();
}
@Override
protected void then(ChannelValuePack entity, SuplaChannelValuePack proto) {
assertThat(proto.count).isEqualTo(entity.getItems().size());
assertThat(proto.totalLeft).isEqualTo(entity.getTotalLeft());
entity.getItems().forEach(item -> verify(channelValueSerializer).serialize(item));
}
@Override
protected Serializer<ChannelValuePack, SuplaChannelValuePack> serializer() {
return serializer;
}
@Override
protected Class<ChannelValuePack> entityClass() {
return ChannelValuePack.class;
}
@Test(expected = NullPointerException.class)
public void shouldThrowNullPointerExceptionWhenChannelValueSerializerIsNull() {
new ChannelValuePackSerializerImpl(null);
}
}
|
magx2/jSupla
|
protocol-java/src/test/java/pl/grzeslowski/jsupla/protocoljava/impl/serializers/sc/ChannelValuePackSerializerImplTest.java
|
Java
|
mit
| 2,093
|
let spec = {
"swagger": "2.0",
"info": {
"description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.",
"version": "1.0.0",
"title": "Swagger Petstore",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"email": "apiteam@swagger.io"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
}
},
"host": "petstore.swagger.io",
"basePath": "/v2",
"tags": [
{
"name": "pet",
"description": "Everything about your Pets",
"externalDocs": {
"description": "Find out more",
"url": "http://swagger.io"
}
},
{
"name": "store",
"description": "Access to Petstore orders"
},
{
"name": "user",
"description": "Operations about user",
"externalDocs": {
"description": "Find out more about our store",
"url": "http://swagger.io"
}
}
],
"schemes": [
"http"
],
"paths": {
"/pet": {
"post": {
"tags": [
"pet"
],
"summary": "Add a new pet to the store",
"description": "",
"operationId": "addPet",
"consumes": [
"application/json",
"application/xml"
],
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "Pet object that needs to be added to the store",
"required": true,
"schema": {
"$ref": "#/definitions/Pet"
}
}
],
"responses": {
"405": {
"description": "Invalid input"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
},
"put": {
"tags": [
"pet"
],
"summary": "Update an existing pet",
"description": "",
"operationId": "updatePet",
"consumes": [
"application/json",
"application/xml"
],
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "Pet object that needs to be added to the store",
"required": true,
"schema": {
"$ref": "#/definitions/Pet"
}
}
],
"responses": {
"400": {
"description": "Invalid ID supplied"
},
"404": {
"description": "Pet not found"
},
"405": {
"description": "Validation exception"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
},
"/pet/findByStatus": {
"get": {
"tags": [
"pet"
],
"summary": "Finds Pets by status",
"description": "Multiple status values can be provided with comma seperated strings",
"operationId": "findPetsByStatus",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "status",
"in": "query",
"description": "Status values that need to be considered for filter",
"required": true,
"type": "array",
"items": {
"type": "string",
"enum": [
"available",
"pending",
"sold"
],
"default": "available"
},
"collectionFormat": "csv"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Pet"
}
}
},
"400": {
"description": "Invalid status value"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
},
"/pet/findByTags": {
"get": {
"tags": [
"pet"
],
"summary": "Finds Pets by tags",
"description": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.",
"operationId": "findPetsByTags",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "tags",
"in": "query",
"description": "Tags to filter by",
"required": true,
"type": "array",
"items": {
"type": "string"
},
"collectionFormat": "csv"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Pet"
}
}
},
"400": {
"description": "Invalid tag value"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
},
"/pet/{petId}": {
"get": {
"tags": [
"pet"
],
"summary": "Find pet by ID",
"description": "Returns a single pet",
"operationId": "getPetById",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "petId",
"in": "path",
"description": "ID of pet to return",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"$ref": "#/definitions/Pet"
}
},
"400": {
"description": "Invalid ID supplied"
},
"404": {
"description": "Pet not found"
}
},
"security": [
{
"api_key": []
}
]
},
"post": {
"tags": [
"pet"
],
"summary": "Updates a pet in the store with form data",
"description": "",
"operationId": "updatePetWithForm",
"consumes": [
"application/x-www-form-urlencoded"
],
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "petId",
"in": "path",
"description": "ID of pet that needs to be updated",
"required": true,
"type": "integer",
"format": "int64"
},
{
"name": "name",
"in": "formData",
"description": "Updated name of the pet",
"required": false,
"type": "string"
},
{
"name": "status",
"in": "formData",
"description": "Updated status of the pet",
"required": false,
"type": "string"
}
],
"responses": {
"405": {
"description": "Invalid input"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
},
"delete": {
"tags": [
"pet"
],
"summary": "Deletes a pet",
"description": "",
"operationId": "deletePet",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "api_key",
"in": "header",
"required": false,
"type": "string"
},
{
"name": "petId",
"in": "path",
"description": "Pet id to delete",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"400": {
"description": "Invalid pet value"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
},
"/pet/{petId}/uploadImage": {
"post": {
"tags": [
"pet"
],
"summary": "uploads an image",
"description": "",
"operationId": "uploadFile",
"consumes": [
"multipart/form-data"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "petId",
"in": "path",
"description": "ID of pet to update",
"required": true,
"type": "integer",
"format": "int64"
},
{
"name": "additionalMetadata",
"in": "formData",
"description": "Additional data to pass to server",
"required": false,
"type": "string"
},
{
"name": "file",
"in": "formData",
"description": "file to upload",
"required": false,
"type": "file"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"$ref": "#/definitions/ApiResponse"
}
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
},
"/store/inventory": {
"get": {
"tags": [
"store"
],
"summary": "Returns pet inventories by status",
"description": "Returns a map of status codes to quantities",
"operationId": "getInventory",
"produces": [
"application/json"
],
"parameters": [],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "object",
"additionalProperties": {
"type": "integer",
"format": "int32"
}
}
}
},
"security": [
{
"api_key": []
}
]
}
},
"/store/order": {
"post": {
"tags": [
"store"
],
"summary": "Place an order for a pet",
"description": "",
"operationId": "placeOrder",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "order placed for purchasing the pet",
"required": true,
"schema": {
"$ref": "#/definitions/Order"
}
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"$ref": "#/definitions/Order"
}
},
"400": {
"description": "Invalid Order"
}
}
}
},
"/store/order/{orderId}": {
"get": {
"tags": [
"store"
],
"summary": "Find purchase order by ID",
"description": "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
"operationId": "getOrderById",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "orderId",
"in": "path",
"description": "ID of pet that needs to be fetched",
"required": true,
"type": "integer",
"maximum": 5.0,
"minimum": 1.0,
"format": "int64"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"$ref": "#/definitions/Order"
}
},
"400": {
"description": "Invalid ID supplied"
},
"404": {
"description": "Order not found"
}
}
},
"delete": {
"tags": [
"store"
],
"summary": "Delete purchase order by ID",
"description": "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors",
"operationId": "deleteOrder",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "orderId",
"in": "path",
"description": "ID of the order that needs to be deleted",
"required": true,
"type": "string",
"minimum": 1.0
}
],
"responses": {
"400": {
"description": "Invalid ID supplied"
},
"404": {
"description": "Order not found"
}
}
}
},
"/user": {
"post": {
"tags": [
"user"
],
"summary": "Create user",
"description": "This can only be done by the logged in user.",
"operationId": "createUser",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "Created user object",
"required": true,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"default": {
"description": "successful operation"
}
}
}
},
"/user/createWithArray": {
"post": {
"tags": [
"user"
],
"summary": "Creates list of users with given input array",
"description": "",
"operationId": "createUsersWithArrayInput",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "List of user object",
"required": true,
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/User"
}
}
}
],
"responses": {
"default": {
"description": "successful operation"
}
}
}
},
"/user/createWithList": {
"post": {
"tags": [
"user"
],
"summary": "Creates list of users with given input array",
"description": "",
"operationId": "createUsersWithListInput",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "List of user object",
"required": true,
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/User"
}
}
}
],
"responses": {
"default": {
"description": "successful operation"
}
}
}
},
"/user/login": {
"get": {
"tags": [
"user"
],
"summary": "Logs user into the system",
"description": "",
"operationId": "loginUser",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "username",
"in": "query",
"description": "The user name for login",
"required": true,
"type": "string"
},
{
"name": "password",
"in": "query",
"description": "The password for login in clear text",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "string"
},
"headers": {
"X-Rate-Limit": {
"type": "integer",
"format": "int32",
"description": "calls per hour allowed by the user"
},
"X-Expires-After": {
"type": "string",
"format": "date-time",
"description": "date in UTC when toekn expires"
}
}
},
"400": {
"description": "Invalid username/password supplied"
}
}
}
},
"/user/logout": {
"get": {
"tags": [
"user"
],
"summary": "Logs out current logged in user session",
"description": "",
"operationId": "logoutUser",
"produces": [
"application/xml",
"application/json"
],
"parameters": [],
"responses": {
"default": {
"description": "successful operation"
}
}
}
},
"/user/{username}": {
"get": {
"tags": [
"user"
],
"summary": "Get user by user name",
"description": "",
"operationId": "getUserByName",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "username",
"in": "path",
"description": "The name that needs to be fetched. Use user1 for testing. ",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"$ref": "#/definitions/User"
}
},
"400": {
"description": "Invalid username supplied"
},
"404": {
"description": "User not found"
}
}
},
"put": {
"tags": [
"user"
],
"summary": "Updated user",
"description": "This can only be done by the logged in user.",
"operationId": "updateUser",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "username",
"in": "path",
"description": "name that need to be deleted",
"required": true,
"type": "string"
},
{
"in": "body",
"name": "body",
"description": "Updated user object",
"required": true,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"400": {
"description": "Invalid user supplied"
},
"404": {
"description": "User not found"
}
}
},
"delete": {
"tags": [
"user"
],
"summary": "Delete user",
"description": "This can only be done by the logged in user.",
"operationId": "deleteUser",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "username",
"in": "path",
"description": "The name that needs to be deleted",
"required": true,
"type": "string"
}
],
"responses": {
"400": {
"description": "Invalid username supplied"
},
"404": {
"description": "User not found"
}
}
}
}
},
"securityDefinitions": {
"petstore_auth": {
"type": "oauth2",
"authorizationUrl": "http://petstore.swagger.io/api/oauth/dialog",
"flow": "implicit",
"scopes": {
"write:pets": "modify pets in your account",
"read:pets": "read your pets"
}
},
"api_key": {
"type": "apiKey",
"name": "api_key",
"in": "header"
}
},
"definitions": {
"Order": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"petId": {
"type": "integer",
"format": "int64"
},
"quantity": {
"type": "integer",
"format": "int32"
},
"shipDate": {
"type": "string",
"format": "date-time"
},
"status": {
"type": "string",
"description": "Order Status",
"enum": [
"placed",
"approved",
"delivered"
]
},
"complete": {
"type": "boolean",
"default": false
}
},
"xml": {
"name": "Order"
}
},
"User": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"username": {
"type": "string"
},
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"email": {
"type": "string"
},
"password": {
"type": "string"
},
"phone": {
"type": "string"
},
"userStatus": {
"type": "integer",
"format": "int32",
"description": "User Status"
}
},
"xml": {
"name": "User"
}
},
"Category": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
}
},
"xml": {
"name": "Category"
}
},
"Tag": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
}
},
"xml": {
"name": "Tag"
}
},
"Pet": {
"type": "object",
"required": [
"name",
"photoUrls"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"category": {
"$ref": "#/definitions/Category"
},
"name": {
"type": "string",
"example": "doggie"
},
"photoUrls": {
"type": "array",
"xml": {
"name": "photoUrl",
"wrapped": true
},
"items": {
"type": "string"
}
},
"tags": {
"type": "array",
"xml": {
"name": "tag",
"wrapped": true
},
"items": {
"$ref": "#/definitions/Tag"
}
},
"status": {
"type": "string",
"description": "pet status in the store",
"enum": [
"available",
"pending",
"sold"
]
}
},
"xml": {
"name": "Pet"
}
},
"ApiResponse": {
"type": "object",
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"type": {
"type": "string"
},
"message": {
"type": "string"
}
}
}
},
"externalDocs": {
"description": "Find out more about Swagger",
"url": "http://swagger.io"
}
};
export default spec;
|
rynam0/ember-swagger-ui
|
tests/integration/components/petstore.js
|
JavaScript
|
mit
| 24,794
|
package net.mrlatte.feeds.feeding;
public interface TaskListener {
public Object getData();
public void setData(Object data);
public void onPreExecute();
public void onPostExecute();
}
|
jongha/android-feeds
|
src/src/net/mrlatte/feeds/feeding/TaskListener.java
|
Java
|
mit
| 193
|
#ifndef MONGOMANAGER_H
#define MONGOMANAGER_H
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <bsoncxx/exception/exception.hpp>
#include <mongocxx/exception/bulk_write_exception.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <iostream>
#include <chrono>
#include "databasemanager.h"
#include "utils.hpp"
namespace rclog {
// TODO: somehow restrict creating other instances of the class!
class MongoManager : public DatabaseManager
{
public:
MongoManager(const std::string &node_id);
int addDocument(const std::string &document, const std::string &producerName) override;
private:
mongocxx::instance mongoInstance; // NOTE: A unique instance of the Mongocxx driver MUST be kept around
mongocxx::client client;
};
}
#endif // MONGOMANAGER_H
|
blaecwen/rc_logging
|
rclogd/mongomanager.h
|
C
|
mit
| 835
|
import style from './style';
const s = Object.create(style);
s.root = {
fontFamily: 'helvetica, sans-serif',
fontWeight: '300',
fontSize: '16px',
letterSpacing: '0.025em',
padding: '3vh 0 12vh 0',
width: '500px',
// use responsive max-width to simulate padding/margin to allow
// space for vertical scroll bar without creating horizontal scroll bar
// (if there is padding, the window will scroll horizontally to show the padding)
maxWidth: 'calc(100vw - 40px)',
// center based on vw to prevent content jump when vertical scroll bar show/hide
// note: vw/vh include the width of scroll bars. Note that centering using margin auto
// or % (which doesn't include scroll bars, so changes when scroll bars shown) causes a page jump
position: 'relative',
left: '50vw',
WebkitTransform: 'translate(-50%, 0)',
MozTransform: 'translate(-50%, 0)',
msTransform: 'translate(-50%, 0)',
OTransform: 'translate(-50%, 0)',
transform: 'translate(-50%, 0)',
WebkitTextSizeAdjust: 'none',
MozTextSizeAdjust: 'none',
msTextSizeAdjust: 'none',
textSizeAdjust: 'none',
};
s.title = {
fontSize: '20px',
marginBottom: '0.5vh',
};
s.repoLink = {
fontSize: '14px',
};
s.breadcrumbs = {
margin: '3vh 0',
};
s.creditLine = {
color: '#A0A0A0',
fontSize: '14px',
marginTop: '50px',
};
s.App = {
textAlign: 'center',
backgroundColor: '#F7F0F0',
};
s.Appheader = {
backgroundColor: '#18A999',
height: 'auto',
padding: '20px',
color: '#484349',
};
s.button = {
backgroundColor: '#18a999',
borderRadius: '10px',
color: '#F7F0F0',
display: 'inline-block',
marginBottom: '5px',
padding: '10px 10px',
textDecoration: 'none',
};
s.Links = {
paddingTop: '20px',
};
s.Icons = {
paddingLeft: '5px',
paddingRight: '5px',
color: '#484349',
};
export default s;
|
AKBarcenas/akbarcenas.github.io
|
src/styles/app.style.js
|
JavaScript
|
mit
| 1,830
|
package com.decSports.measureme;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class DotDrawView extends View {
public static final String TAG = "DotDrawView";
public static final float dotRadius = 5;
private PointF mCurrentPoint;
private ArrayList<PointF> mPoints = new ArrayList<PointF>();
private Paint mPointPaint;
public DotDrawView(Context context) {
this(context, null);
}
public DotDrawView(Context context, AttributeSet attrs) {
super(context, attrs);
mPointPaint = new Paint();
mPointPaint.setColor(0xffff6347);
}
public PointF getCurrentPoint() {
return mCurrentPoint;
}
public void setCurrentPoint(PointF newPoint) {
mCurrentPoint = newPoint;
invalidate();
}
public void setPoints(ArrayList<PointF> points) {
mPoints = points;
}
public ArrayList<PointF> getPoints() {
return mPoints;
}
public boolean onTouchEvent(MotionEvent event) {
PointF curr = new PointF(event.getX(), event.getY());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i(TAG, "Touched Screen");
mCurrentPoint = curr;
break;
case MotionEvent.ACTION_MOVE:
if (mCurrentPoint != null) {
mCurrentPoint = curr;
invalidate();
}
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_CANCEL:
break;
}
return true;
}
@Override
protected void onDraw(Canvas canvas) {
if (mCurrentPoint != null) {
float canvasHeight = canvas.getHeight();
float canvasWidth = canvas.getWidth();
float xPos = mCurrentPoint.x;
float yPos = mCurrentPoint.y;
canvas.drawLine(xPos, 0, xPos, canvasHeight, mPointPaint);
canvas.drawLine(0, yPos, canvasWidth, yPos, mPointPaint);
for (PointF point : mPoints) {
xPos = point.x;
yPos = point.y;
canvas.drawCircle(xPos, yPos, dotRadius, mPointPaint);
}
}
}
}
|
tylernickr/MeasureMe
|
app/src/main/java/com/decSports/measureme/DotDrawView.java
|
Java
|
mit
| 2,106
|
<?php $this->load->view('themes/dppm/header'); ?>
<?php $this->load->view('themes/dppm/sidebar'); ?>
<div class="page animsition">
<div class="page-header">
<h1 class="page-title">Dashboard </h1>
<ol class="breadcrumb">
<li><a href="#">Menu Umum</a></li>
<li class="active">Dashboard</li>
</ol>
</div>
<div class="page-content">
<div class="row">
<div class="col-sm-6 txt-dc-none">
<!-- Widget -->
<a style="text-decoration: none;" href="<?php echo site_url('buku-ajar')?>">
<div class="widget">
<div class="widget-content padding-30 bg-primary">
<div class="widget-watermark darker font-size-60 margin-15"><i class="icon wb-book" aria-hidden="true"></i></div>
<div class="counter counter-md counter-inverse text-left">
<div class="counter-number-group">
<span class="counter-number-related text-capitalize">Buku Ajar</span>
</div>
<div class="counter-label text-capitalize">Menu Kelola / Buku Ajar</div>
</div>
</div>
</div>
</a>
<!-- End Widget -->
</div>
<div class="col-sm-6 txt-dc-none">
<!-- Widget -->
<a style="text-decoration: none;" href="<?php echo site_url('penelitian-internal')?>">
<div class="widget">
<div class="widget-content padding-30 bg-warning">
<div class="widget-watermark darker font-size-60 margin-15"><i class="icon wb-arrow-shrink" aria-hidden="true"></i></div>
<div class="counter counter-md counter-inverse text-left">
<div class="counter-number-group">
<span class="counter-number-related text-capitalize">Penelitian Internal</span>
</div>
<div class="counter-label text-capitalize">Menu Kelola / Penelitian Internal</div>
</div>
</div>
</div>
</a>
<!-- End Widget -->
</div>
<div class="col-sm-6 txt-dc-none">
<!-- Widget -->
<a style="text-decoration: none;" href="<?php echo site_url('penelitian-eksternal')?>">
<div class="widget">
<div class="widget-content padding-30 bg-danger">
<div class="widget-watermark darker font-size-60 margin-15"><i class="icon wb-arrow-expand" aria-hidden="true"></i></div>
<div class="counter counter-md counter-inverse text-left">
<div class="counter-number-group">
<span class="counter-number-related text-capitalize">Penelitian Eksternal</span>
</div>
<div class="counter-label text-capitalize">Menu Kelola / Penelitian Eksternal</div>
</div>
</div>
</div>
</a>
<!-- End Widget -->
</div>
<div class="col-sm-6 txt-dc-none">
<!-- Widget -->
<a style="text-decoration: none;" href="<?php echo site_url('luaran-lain')?>">
<div class="widget">
<div class="widget-content padding-30 bg-info">
<div class="widget-watermark darker font-size-60 margin-15"><i class="icon fa fa-line-chart" aria-hidden="true"></i></div>
<div class="counter counter-md counter-inverse text-left">
<div class="counter-number-group">
<span class="counter-number-related text-capitalize">Luaran Lain</span>
</div>
<div class="counter-label text-capitalize">Menu Kelola / Luaran Lain</div>
</div>
</div>
</div>
</a>
<!-- End Widget -->
</div>
<div class="col-sm-6 txt-dc-none">
<!-- Widget -->
<a style="text-decoration: none;" href="<?php echo site_url('forum-ilmiah') ?>">
<div class="widget">
<div class="widget-content padding-30 bg-grey-600">
<div class="widget-watermark darker font-size-60 margin-15"><i class="icon wb-user" aria-hidden="true"></i></div>
<div class="counter counter-md counter-inverse text-left">
<div class="counter-number-group">
<span class="counter-number-related text-capitalize">Pemakalah Forum</span>
</div>
<div class="counter-label text-capitalize">Menu Kelola / Pemakalah Forum Ilmiah</div>
</div>
</div>
</div>
</a>
<!-- End Widget -->
</div>
<div class="col-sm-6 txt-dc-none">
<!-- Widget -->
<a style="text-decoration: none;" href="<?php echo site_url('penunjang-penelitian')?>">
<div class="widget">
<div class="widget-content padding-30 bg-success">
<div class="widget-watermark darker font-size-60 margin-15"><i class="icon fa fa-eyedropper" aria-hidden="true"></i></div>
<div class="counter counter-md counter-inverse text-left">
<div class="counter-number-group">
<span class="counter-number-related text-capitalize">Penelitian Internal</span>
</div>
<div class="counter-label text-capitalize">Menu Kelola / Penelitian Internal</div>
</div>
</div>
</div>
</a>
<!-- End Widget -->
</div>
</div>
</div>
</div>
<?php $this->load->view('themes/footer'); ?>
<?php $this->load->view('themes/footer-script'); ?>
|
Lective/newdospres
|
application/modules/lv_dashboard/views/view_dashboard_dppm.php
|
PHP
|
mit
| 5,835
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>flexile.js Tests Runner using Jasmine v2.5.2</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.5.2/jasmine.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.5.2/jasmine.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.5.2/jasmine-html.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.5.2/boot.min.js"></script>
<script src="../flexile.js"></script>
<script src="flexile-theme-tests.js"></script>
<script src="flexile-transition-tests.js"></script>
<script src="flexile-aspect-tests.js"></script>
<script src="flexile-key-tests.js"></script>
<script src="flexile-errors-tests.js"></script>
</head>
<body>
</body>
</html>
|
timbrock/flexile.js
|
src/js/tests/flexile-tests-runner.html
|
HTML
|
mit
| 855
|
<LINK REL="stylesheet" HREF="../static/styles.css">
<HTML>
<HEAD>
<TITLE>FMOD_DSP_GETPARAM_FLOAT_CALLBACK</TITLE>
</HEAD>
<BODY TOPMARGIN="0" class="api_reference">
<p class="header">Firelight Technologies FMOD Studio API</p>
<H1>FMOD_DSP_GETPARAM_FLOAT_CALLBACK</H1>
<P>
<p>This callback is called when the user wants to get an indexed float parameter from a DSP unit.</p>
</P>
<h3>C/C++ Syntax</h3>
<PRE class=syntax><CODE>FMOD_RESULT F_CALLBACK FMOD_DSP_GETPARAM_FLOAT_CALLBACK(
FMOD_DSP_STATE *<I>dsp_state</I>,
int <I>index</I>,
float *<I>value</I>,
char *<I>valuestr</I>
);
</CODE></PRE>
<h2>Parameters</h2>
<P class=dt><I>dsp_state</I></P>
<P class=indent>Pointer to the plugin state. The user can use this variable to access runtime plugin specific variables and plugin writer user data. Do not cast this to FMOD_DSP! The handle to the user created DSP handle is stored within the <A HREF="FMOD_DSP_STATE.html">FMOD_DSP_STATE</A> structure.</P>
<P class=dt><I>index</I></P>
<P class=indent>The index into the parameter list for the parameter the user wants to get.</P>
<P class=dt><I>value</I></P>
<P class=indent>Pointer to a float variable to receive the selected parameter value.</P>
<P class=dt><I>valuestr</I></P>
<P class=indent>A pointer to a string to receive the value of the selected parameter, but in text form. This might be useful to display words instead of numbers. For example "ON" or "OFF" instead of 1.0 and 0.0. The length of the buffer being passed in is always 16 bytes, so do not exceed this. <strong>Note:</strong> This pointer will be 0 / NULL if a string is not required.</P>
<h2>Return Values</h2><P>
If the function succeeds then the return value is <A HREF="FMOD_RESULT.html">FMOD_OK</A>.<BR>
If the function fails then the return value will be one of the values defined in the <A HREF="FMOD_RESULT.html">FMOD_RESULT</A> enumeration.<BR>
</P>
<h2>Remarks</h2><P>
<p>Functions that the user would have to call for this callback to be called.</p>
<ul>
<li><A HREF="FMOD_DSP_GetParameterFloat.html">DSP::getParameterFloat</A>.</li>
<li><A HREF="FMOD_DSP_GETPARAM_FLOAT_CALLBACK.html">FMOD_DSP_GETPARAM_FLOAT_CALLBACK</A>.</li>
</ul>
<p>Remember to return <A HREF="FMOD_RESULT.html">FMOD_OK</A> at the bottom of the function, or an appropriate error code from <A HREF="FMOD_RESULT.html">FMOD_RESULT</A>.</p>
</P>
<h2>See Also</h2>
<UL type=disc>
<LI><A HREF="FMOD_DSP_STATE.html">FMOD_DSP_STATE</A></LI>
<LI><A HREF="FMOD_DSP_GetParameterFloat.html">DSP::getParameterFloat</A></LI>
<LI><A HREF="FMOD_DSP_DESCRIPTION.html">FMOD_DSP_DESCRIPTION</A></LI>
<LI><A HREF="FMOD_DSP_SETPARAM_FLOAT_CALLBACK.html">FMOD_DSP_SETPARAM_FLOAT_CALLBACK</A></LI>
</UL>
<BR><BR><BR>
<P align=center><font size=-2>Version 1.08.02 Built on Apr 14, 2016</font></P>
<BR>
</HTML>
|
Silveryard/Car_System
|
Old/3rdParty/fmodstudioapi10802linux/doc/FMOD Studio Programmers API for Linux/content/generated/FMOD_DSP_GETPARAM_FLOAT_CALLBACK.html
|
HTML
|
mit
| 2,804
|
"""
filename: controllers.py
description: Controllers for committee notes.
created by: Chris Lemelin (cxl8826@rit.edu)
created on: 04/20/18
"""
from flask_socketio import emit
from app.decorators import ensure_dict
from app import socketio, db
from app.committee_notes.models import *
from app.committees.models import *
from app.users.models import Users
from app.committee_notes.committee_notes_response import Response
##
## @brief Creates a committee note. (Must be admin user or committe head)
##
## @param user_data The user data required to create a committee note
##
## All the following fields are required:
## committee - id of the committee
## description - Description of new committee note
##
@socketio.on('create_committee_note')
@ensure_dict
def create_note(user_data):
user = Users.verify_auth(user_data.get("token", ""))
committe_id = user_data.get('committee', '')
committee = Committees.query.filter_by(id=committe_id).first()
if committee is not None:
if(user is not None and (user.is_admin or committee.head == user.id)):
committee_note = CommitteeNotes()
committee_note.committee = committee.id
committee_note.description = user_data.get('description',"")
committee_note.author = user.id
committee_note.hidden = False
db.session.add(committee_note)
try:
db.session.commit()
emit('create_committee_note', Response.AddSuccess)
get_notes(action.id, broadcast = True)
except Exception as e:
db.session.rollback()
db.session.flush()
emit("create_committee_note", Response.AddError)
else:
emit("create_committee_note", Response.UsrNotAuth)
else:
emit("create_committee_note", Response.CommitteeDoesntExist)
##
## @brief Gets committee notes from a committee
##
## @param committee_id - id of the committee
##
@socketio.on('get_committee_notes')
def get_notes(committee_id, broadcast = False):
notes = CommitteeNotes.query.filter_by(committee= committee_id).all()
note_ser = [
{
"id": c.id,
"author": c.author,
"committee": c.committee,
"description": c.description,
"created_at": c.created_at,
"hidden": c.hidden
}
for c in notes
]
emit("get_committee_notes", note_ser, broadcast = broadcast)
##
## @brief Gets a committee note
##
## @param id - id of committee note.
##
@socketio.on('get_committee_note')
def get_note(id, broadcast = False):
note = CommitteeNotes.query.filter_by(id= id).first()
if note is not None:
note_data = {
"id": note.id,
"author": note.author,
"committee": note.committee,
"description": note.description,
"created_at": note.created_at,
"hidden": note.hidden
}
emit('get_committee_note', note_data, broadcast = broadcast)
else:
emit("get_committee_note", {}, broadcast = broadcast)
##
## @brief Edits a committee note (Must be admin user or committe head to hide,
## only the author can edit the description)
##
## @param user_data The user data to edit a note, must
## contain a token, an id and any of the following
## fields:
## - description
## - hidden
##
## Any other field will be ignored.
##
## @emit Emits a success mesage if edited, errors otherwise.
##
@socketio.on('modify_committee_note')
@ensure_dict
def modify_note(user_data):
user = Users.verify_auth(user_data.get("token",""))
if(user is None):
emit('modify_note', Response.UsrDoesntExist)
return
committee_note_id = user_data.get("id","")
committee_note = CommitteeNotes.query.filter_by(id=committee_note_id).first()
if(committee_note is None):
emit('modify_note', Response.CommitteeNoteDoesntExist)
return
committee = Committees.query.filter_by(id= committee_note.committee).first()
if(user.id == committee_note.author):
if "description" in user_data:
committee_note.description = user_data['description']
if(user.id == committee.head or user.is_admin or user.id == committee_note.author):
if "hidden" in user_data:
committee_note.hidden = user_data['hidden']
db.session.add(committee_note)
try:
db.session.commit()
emit('modify_committee_note', Response.ModifySuccess)
#get_note(committee_note.id, broadcast = True)
except Exception as e:
db.session.rollback()
db.session.flush()
emit("modify_committee_note", Response.ModifyError)
else:
emit("modify_committee_note", Response.UsrNotAuth)
|
ritstudentgovernment/chargeflask
|
app/committee_notes/controllers.py
|
Python
|
mit
| 5,203
|
package com.github.piasy.fancytransitiondemo;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
import com.facebook.rebound.BaseSpringSystem;
import com.facebook.rebound.SimpleSpringListener;
import com.facebook.rebound.Spring;
import com.facebook.rebound.SpringConfig;
import com.facebook.rebound.SpringSystem;
import com.facebook.rebound.SpringUtil;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
public class CountdownAnimationTextView extends TextView {
private int mStartCount;
private int mStopCount;
private int mCurrentCount;
private final CountdownSpringListener mSpringListener = new CountdownSpringListener(this);
private final Spring mCountdownSpring;
private Subscription mCountdownSubscription;
private CountdownCallback mCountdownCallback;
public CountdownAnimationTextView(Context context) {
this(context, null);
}
public CountdownAnimationTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CountdownAnimationTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
BaseSpringSystem springSystem = SpringSystem.create();
mCountdownSpring = springSystem.createSpring();
mCountdownSpring.setSpringConfig(SpringConfig.fromOrigamiTensionAndFriction(600, 9));
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mCountdownSubscription != null && !mCountdownSubscription.isUnsubscribed()) {
mCountdownSubscription.unsubscribe();
}
mCountdownSpring.removeAllListeners();
}
public void setCountdown(int startCount, int stopCount) {
mStartCount = startCount;
mStopCount = stopCount;
}
public void startCountdown() {
mCountdownSpring.addListener(mSpringListener);
mCurrentCount = mStartCount;
play(mCurrentCount);
if (mCountdownCallback != null) {
mCountdownCallback.onStart();
}
mCountdownSubscription = Observable.interval(100, TimeUnit.MILLISECONDS)
.take((mStartCount - mStopCount + 1) * 10)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Long>() {
@Override
public void onCompleted() {
countdown();
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Long count) {
if (count > 0 && count % 10 == 0) {
countdown();
} else if (count % 10 == 8) {
hide();
}
}
});
}
private void countdown() {
if (mCurrentCount <= mStopCount) {
mCountdownSpring.removeAllListeners();
if (mCountdownCallback != null) {
mCountdownCallback.onComplete();
}
} else {
mCurrentCount--;
play(mCurrentCount);
if (mCountdownCallback != null) {
mCountdownCallback.onCountdown();
}
}
}
private void play(int count) {
setText(String.valueOf(count));
mCountdownSpring.setCurrentValue(0.01);
mCountdownSpring.setEndValue(1);
show();
}
private void show() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
animate().alpha(1).setDuration(100).withLayer().start();
} else {
animate().alpha(1).setDuration(100).start();
}
}
private void hide() {
animate().alpha(0).setDuration(100).start();
}
public void setCountdownCallback(CountdownCallback countdownCallback) {
mCountdownCallback = countdownCallback;
}
private static class CountdownSpringListener extends SimpleSpringListener {
public static final double TO_HIGH = 1.5;
private final View mView;
private CountdownSpringListener(View view) {
mView = view;
}
@Override
public void onSpringUpdate(Spring spring) {
if (mView != null) {
float mappedValue =
(float) SpringUtil.mapValueFromRangeToRange(spring.getCurrentValue(), 0, 1,
1, TO_HIGH);
mView.setScaleX(mappedValue);
mView.setScaleY(mappedValue);
}
}
}
public interface CountdownCallback {
void onStart();
void onCountdown();
void onComplete();
}
public abstract static class LazyCountdownCallback implements CountdownCallback {
@Override
public void onStart() {
}
@Override
public void onCountdown() {
}
@Override
public void onComplete() {
}
}
}
|
Piasy/AndroidPlayground
|
effect/FancyTransitionDemo/src/main/java/com/github/piasy/fancytransitiondemo/CountdownAnimationTextView.java
|
Java
|
mit
| 5,277
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_calcButton_clicked();
void on_clearButton_clicked();
void on_calcEdit_returnPressed();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
|
dannagle/BarcampCalculator
|
mainwindow.h
|
C
|
mit
| 417
|
/**Copyright (C) 2013 Rory Burks
*
* 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.
* */
// ExportComposite.cs
//
// A wrapper for the method to export projects to file.
// !!! TODO !!! : exporting the chunk data could be made general rather than
// duplicated for each resource by creating an exportFromMemort(stream)
// prototype in RSContentContainer, and then implementing it in each
// data type.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rockslide_Content_Pipeline.Data_Types;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace Rockslide_Content_Pipeline.IO
{
public static class ExportComposite
{
/// <summary>
/// Exports the composite project file to the given file.
/// </summary>
/// <returns>true if export was successful</returns>
public static bool exportCompositeFile(string file_name, RSComposite composite)
{
BinaryWriter writer = null;
// Lists which keep track of the data's position and size so they
// can be filled in the Resource Table on a second pass
List<uint> seek_locations = new List<uint>();
List<int> chunk_sizes = new List<int>();
UInt32[] resource_count = new UInt32[RSComposite.CONTENT_NUM];
try
{
writer = new BinaryWriter(File.Open(file_name, FileMode.Create));
// Write Magic Number
byte[] magic_number = Encoding.ASCII.GetBytes("RSCD_002");
writer.Write(magic_number, 0, 8);
for (int i = 0; i < RSComposite.CONTENT_NUM; ++i)
{
resource_count[i] = 0;
writer.Write((UInt32)(0)); // Placeholder for resource counts
}
// Write the Resource Table (with room for the seeks to be filled later)
for (int i = 0; i < RSComposite.CONTENT_NUM; ++i)
{
foreach (TreeNode node in composite.roots[i].Nodes)
{
_rec_writeResourceHeader( node, composite, writer,
ref resource_count[i], i);
}
}
// Write each individual data chunk
foreach (TreeNode node in composite.roots[(int)RSComposite.ContentType.Model].Nodes)
{
_rec_writeModelData(node, composite, writer, seek_locations, chunk_sizes);
}
foreach (TreeNode node in composite.roots[(int)RSComposite.ContentType.Texture].Nodes)
{
_rec_writeTextureData(node, composite, writer, seek_locations, chunk_sizes);
}
// Go back and fill the seek locations
writer.Seek(8, SeekOrigin.Begin);
for (int i = 0; i < RSComposite.CONTENT_NUM; ++i)
writer.Write(resource_count[i]);
for (int i = 0; i < RSComposite.CONTENT_NUM; ++i)
{
foreach (TreeNode node in composite.roots[i].Nodes)
_rec_fillHeader(node, composite, writer, seek_locations, chunk_sizes, i);
}
writer.Close();
}
catch (Exception e)
{
MessageBox.Show("Exception in Exporting Composite: " + e.Message);
return false;
}
finally
{
if( writer != null)
writer.Close();
}
return true;
}
/// <summary>
/// Writes the entry data for the given node, then recursively goes
/// through all its children, writing their data in depth-first tree
/// form.
/// </summary>
/// <param name="working_root">The entry node.</param>
/// <param name="composite">The file containing all the resources.</param>
/// <param name="writer">The data stream to write to.</param>
/// <param name="resource_count">Working count of how many resources have been written so far.</param>
/// <param name="type">The type of resource we're currently working with (in int form).</param>
private static void _rec_writeResourceHeader( TreeNode working_root,
RSComposite composite,
BinaryWriter writer,
ref uint resource_count,
int type)
{
if (working_root.Name == composite.file_identifier[type])
{
writer.Write((byte)1); // Type - Resource
resource_count++;
Debug.Assert(((RSContentContainer)working_root.Tag).id == working_root.Text);
byte[] name = Encoding.ASCII.GetBytes(working_root.Text);
writer.Write(name); // Identifier
writer.Write((byte)0); // Null-termination
writer.Write((UInt32)0); // Placeholder for seek location
writer.Write((UInt32)0); // Placeholder for chunk size
Debug.Assert(working_root.Nodes.Count == 0);
return;
}
else
{
Debug.Assert(working_root.Name == composite.folder_identifier[type]);
writer.Write((byte)0); // Type - Folder
byte[] name = Encoding.ASCII.GetBytes(working_root.Text);
writer.Write(name);
writer.Write((byte)0); // Null-termination
foreach (TreeNode node in working_root.Nodes)
_rec_writeResourceHeader(node, composite, writer, ref resource_count, type);
writer.Write((byte)255); // Type - End of Folder
resource_count += 2;
}
}
/// <summary>
/// Recursively writes each texture file to the stream, writing it
/// from the appropriate place where it exists.
/// </summary>
/// <param name="seek_locations">
/// An array to store the seek locations so that they can be written in the second pass.
/// </param>
/// <param name="chunk_sizes">
/// An array to store the chunk sizes so that they can be written in the second pass.
/// </param>
private static void _rec_writeTextureData( TreeNode working_root,
RSComposite composite,
BinaryWriter writer,
List<uint> seek_locations,
List<int> chunk_sizes)
{
if (working_root.Name == composite.file_identifier[(int)RSComposite.ContentType.Texture])
{
RSTexture tex = (RSTexture)working_root.Tag;
seek_locations.Add((uint)writer.BaseStream.Position);
if( tex.data_location == RSContentContainer.DataLocation.File &&
tex.filename != "" && File.Exists( tex.filename))
{
// File : Read the file into a data buffer, then write
// that buffer to the stream
byte[] data = File.ReadAllBytes(tex.filename);
writer.Write(data);
}
else if (tex.data_location == RSContentContainer.DataLocation.Memory &&
tex.image != null)
{
// Memory : Because image.Save can only write from the 0 offset,
// we must save to a temporary file then copy that file into the
// composite.
string temp_file = Path.GetTempFileName();
tex.image.Save( temp_file, tex.image.RawFormat);
byte[] data = File.ReadAllBytes(temp_file);
writer.Write(data);
File.Delete(temp_file);
}
else if (tex.data_location == RSContentContainer.DataLocation.CompositeFile &&
tex.filename != "" && File.Exists(tex.filename) )
{
// Composite : open the composite file, seek to the correct
// position, then read the described amount of chunks.
BinaryReader reader = new BinaryReader(File.OpenRead(tex.filename));
// Verify that file is big enough to contain the chunk described
if (reader.BaseStream.Length <= (Int64)tex.seek_location + (Int64)tex.chunk_size)
{
reader.BaseStream.Seek(tex.seek_location, SeekOrigin.Begin);
byte[] data = reader.ReadBytes(tex.chunk_size);
}
else Debug.Write("Bad composite.");
reader.Close();
}
// Verify that the file has not exceeded 4GB (otherwise our
// uint32 seek positions will corrupt).
if (writer.BaseStream.Position > uint.MaxValue)
{
writer.Seek(0, SeekOrigin.Begin);
writer.Write((UInt64)0); // Clear Magic number to signify that the file is corrupt/incomplete
throw new Exception(ControlStrings.ErrorFileTooBig);
}
// Calculate the chunk size based on the present and previous positions.
chunk_sizes.Add( (int)(writer.BaseStream.Position - seek_locations.Last()));
return;
}
else
{
foreach (TreeNode node in working_root.Nodes)
_rec_writeTextureData(node, composite, writer, seek_locations, chunk_sizes);
}
}
/// <summary>
/// Recursively writes each model file to the stream, writing it
/// from the appropriate place where it exists.
/// </summary>
/// <param name="seek_locations">
/// An array to store the seek locations so that they can be written in the second pass.
/// </param>
/// <param name="chunk_sizes">
/// An array to store the chunk sizes so that they can be written in the second pass.
/// </param>
private static void _rec_writeModelData( TreeNode working_root,
RSComposite composite,
BinaryWriter writer,
List<uint> seek_locations,
List<int> chunk_sizes)
{
if (working_root.Name == composite.file_identifier[(int)RSComposite.ContentType.Model])
{
RSModel model = (RSModel)working_root.Tag;
seek_locations.Add((uint)writer.BaseStream.Position);
if (model.data_location == RSContentContainer.DataLocation.File &&
model.filename != "" && File.Exists(model.filename))
{
// File : Read the file into a data buffer, then write
// that buffer to the stream
byte[] data = File.ReadAllBytes(model.filename);
writer.Write(data);
}
else if (model.data_location == RSContentContainer.DataLocation.Memory &&
model.data != null)
{
// Export Model
ExportModel.exportModel(writer.BaseStream, model);
}
else if (model.data_location == RSContentContainer.DataLocation.CompositeFile &&
model.filename != "" && File.Exists(model.filename))
{
// Composite : open the composite file, seek to the correct
// position, then read the described amount of chunks.
BinaryReader reader = new BinaryReader(File.OpenRead(model.filename));
// Verify that file is big enough to contain the chunk described
if (reader.BaseStream.Length <= (Int64)model.seek_location + (Int64)model.chunk_size)
{
reader.BaseStream.Seek(model.seek_location, SeekOrigin.Begin);
byte[] data = reader.ReadBytes(model.chunk_size);
}
else Debug.Write("Bad composite.");
reader.Close();
}
// Verify that the file has not exceeded 4GB (otherwise our
// uint32 seek positions will corrupt).
if (writer.BaseStream.Position > uint.MaxValue)
{
writer.Seek(0, SeekOrigin.Begin);
writer.Write((UInt64)0); // Clear Magic number to signify that the file is corrupt/incomplete
throw new Exception(ControlStrings.ErrorFileTooBig);
}
// Calculate the chunk size based on the present and previous positions.
chunk_sizes.Add((int)(writer.BaseStream.Position - seek_locations.Last()));
return;
}
else
{
foreach (TreeNode node in working_root.Nodes)
_rec_writeModelData(node, composite, writer, seek_locations, chunk_sizes);
}
}
/// <summary>
/// Go back and fill the Resource Table with the provided seek locations
/// and chunk sizes (called once for each resource type).
/// </summary>
private static void _rec_fillHeader( TreeNode working_root,
RSComposite composite,
BinaryWriter writer,
List<uint> seek_locations,
List<int> chunk_sizes,
int type)
{
if (working_root.Name == composite.file_identifier[type])
{
writer.Seek(1, SeekOrigin.Current);
while (writer.BaseStream.ReadByte() != 0) ;
writer.Write(seek_locations[0]);
writer.Write(chunk_sizes[0]);
seek_locations.RemoveAt(0); // More of a queue than a list, but w/e
chunk_sizes.RemoveAt(0);
return;
}
else
{
writer.Seek(1, SeekOrigin.Current);
while (writer.BaseStream.ReadByte() != 0) ;
foreach (TreeNode node in working_root.Nodes)
_rec_fillHeader(node, composite, writer, seek_locations, chunk_sizes, type);
}
}
}
}
|
roryburks/rock-pipe
|
src/Rockslide Content Pipeline/IO/ExportComposite.cs
|
C#
|
mit
| 15,181
|
using FlatRedBall.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TMXGlueLib
{
/// <summary>
/// Contains utility methods specific to tools - these should not be needed at runtime (in games)
/// </summary>
public static class TiledMapSaveToolsUtilities
{
/// <summary>
/// Sets all Image width/height values inside all Tilesets according to actual
/// texture sizes. The reason this is needed is because the user could have chnaged
/// the size of the images (like resized a PNG) and not opened/resaved the file in Tiled.
/// Therefore, the image size may be incorrect in the TMX.
/// </summary>
/// <param name="directory">The directory of the TMX, which is used to load images which typically use relative paths.</param>
public static void CorrectImageSizes(this TiledMapSave tiledMapSave, string directory)
{
foreach (var tileset in tiledMapSave.Tilesets)
{
foreach (var image in tileset.Images)
{
string absolutePath = image.Source;
if (FileManager.IsRelative(absolutePath))
{
absolutePath = directory + absolutePath;
}
if (System.IO.File.Exists(absolutePath))
{
var dimensions = ImageHeader.GetDimensions(absolutePath);
image.width = dimensions.Width;
image.height = dimensions.Height;
}
}
}
}
}
}
|
vchelaru/FlatRedBall
|
Tiled/TMXGlueLib/TiledMapSaveToolsUtilities.cs
|
C#
|
mit
| 1,689
|
export class Ruleset {
constructor(private movesPerTurn: number) {}
public getMovesPerTurn = (): number => this.movesPerTurn;
}
|
HolyMeekrob/i-shove-you-so-much
|
src/model/ruleset.ts
|
TypeScript
|
mit
| 131
|
/*******************************************************************************
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
package net.sourceforge.jsocks.socks;
import net.sourceforge.jsocks.socks.server.ServerAuthenticator;
//import java.util.Random;
import java.io.*;
//import org.apache.commons.lang.RandomStringUtils;
//import org.apache.log4j.Logger;
import java.net.*;
/**
* SOCKS4 and SOCKS5 proxy, handles both protocols simultaniously. Implements
* all SOCKS commands, including UDP relaying.
* <p>
* In order to use it you will need to implement ServerAuthenticator interface.
* There is an implementation of this interface which does no authentication
* ServerAuthenticatorNone, but it is very dangerous to use, as it will give
* access to your local network to anybody in the world. One should never use
* this authentication scheme unless one have pretty good reason to do so. There
* is a couple of other authentication schemes in socks.server package.
*
* @see socks.server.ServerAuthenticator
*/
public class ProxyServer implements Runnable {
ServerAuthenticator auth;
ProxyMessage msg = null;
Socket sock = null, remote_sock = null;
ServerSocket ss = null;
UDPRelayServer relayServer = null;
InputStream in, remote_in;
OutputStream out, remote_out;
int mode;
static final int START_MODE = 0;
static final int ACCEPT_MODE = 1;
static final int PIPE_MODE = 2;
static final int ABORT_MODE = 3;
static final int DEFAULT_BUF_SIZE = 8192;
Thread pipe_thread1, pipe_thread2;
long lastReadTime;
static int idleTimeout = 60000; // 60 seconds
static int acceptTimeout = 60000; // 60 seconds
// private static final Logger LOG = Logger.getLogger(ProxyServer.class);
static Proxy proxy;
private int BUF_SIZE = DEFAULT_BUF_SIZE;
// private String connectionId;
// Public Constructors
/////////////////////
/**
* Creates a proxy server with given Authentication scheme.
*
* @param auth
* Authentication scheme to be used.
*/
public ProxyServer(ServerAuthenticator auth) {
this.auth = auth;
// this.connectionId = newConnectionId();
}
// Other constructors
////////////////////
public ProxyServer(ServerAuthenticator auth, Socket s) {
this.auth = auth;
this.sock = s;
// this.connectionId = connectionId;
mode = START_MODE;
}
// Public methods
/////////////////
public void setPipeBufferSize(int bufSize) {
BUF_SIZE = bufSize;
}
/**
* Set proxy.
* <p>
* Allows Proxy chaining so that one Proxy server is connected to another and so
* on. If proxy supports SOCKSv4, then only some SOCKSv5 requests can be
* handled, UDP would not work, however CONNECT and BIND will be translated.
*
* @param p
* Proxy which should be used to handle user requests.
*/
public static void setProxy(Proxy p) {
proxy = p;
UDPRelayServer.proxy = proxy;
}
/**
* Get proxy.
*
* @return Proxy wich is used to handle user requests.
*/
public static Proxy getProxy() {
return proxy;
}
/**
* Sets the timeout for connections, how long shoud server wait for data to
* arrive before dropping the connection.<br>
* Zero timeout implies infinity.<br>
* Default timeout is 3 minutes.
*/
public static void setIdleTimeout(int timeout) {
idleTimeout = timeout;
}
/**
* Sets the timeout for BIND command, how long the server should wait for the
* incoming connection.<br>
* Zero timeout implies infinity.<br>
* Default timeout is 3 minutes.
*/
public static void setAcceptTimeout(int timeout) {
acceptTimeout = timeout;
}
/**
* Sets the timeout for UDPRelay server.<br>
* Zero timeout implies infinity.<br>
* Default timeout is 3 minutes.
*/
public static void setUDPTimeout(int timeout) {
UDPRelayServer.setTimeout(timeout);
}
/**
* Sets the size of the datagrams used in the UDPRelayServer.<br>
* Default size is 64K, a bit more than maximum possible size of the datagram.
*/
public static void setDatagramSize(int size) {
UDPRelayServer.setDatagramSize(size);
}
/**
* Start the Proxy server at given port.<br>
* This methods blocks.
*/
public void start(int port) {
start(port, 5, null);
}
/**
* Create a server with the specified port, listen backlog, and local IP address
* to bind to. The localIP argument can be used on a multi-homed host for a
* ServerSocket that will only accept connect requests to one of its addresses.
* If localIP is null, it will default accepting connections on any/all local
* addresses. The port must be between 0 and 65535, inclusive. <br>
* This methods blocks.
*/
public void start(int port, int backlog, InetAddress localIP) {
try {
ss = new ServerSocket(port, backlog, localIP);
//ss = new ServerSocket();
//ss.setReuseAddress(true);
//ss.bind(new InetSocketAddress(localIP, port), backlog);
//ss.bind(new InetSocketAddress(port));
// LOG.info("Starting SOCKS Proxy on:" +
// ss.getInetAddress().getHostAddress() + ":" + ss.getLocalPort());
//ss.setReceiveBufferSize(VT.VT_NETWORK_PACKET_BUFFER_SIZE - 1);
while (true) {
Socket s = ss.accept();
//s.setSendBufferSize(VT.VT_NETWORK_PACKET_BUFFER_SIZE - 1);
s.setTcpNoDelay(true);
s.setKeepAlive(true);
//s.setSoTimeout(60000);
//s.setSoLinger(true, 0);
// String connectionId = newConnectionId();
// LOG.info(connectionId + " Accepted from:" +
// s.getInetAddress().getHostName() + ":" +s.getPort());
ProxyServer ps = new ProxyServer(auth, s);
(new Thread(ps)).start();
}
} catch (IOException ioe) {
// ioe.printStackTrace();
}
}
/**
* Creates new unique ID for this connection.
*
* @return a random-enough ID.
*/
// private String newConnectionId() {
// return "[" + RandomStringUtils.randomAlphanumeric(4) + "]";
// }
/**
* Stop server operation.It would be wise to interrupt thread running the server
* afterwards.
*/
public void stop() {
try {
if (ss != null)
ss.close();
} catch (IOException ioe) {
}
}
// Runnable interface
////////////////////
public void run() {
switch (mode) {
case START_MODE:
try {
startSession();
} catch (IOException ioe) {
handleException(ioe);
// ioe.printStackTrace();
} finally {
abort();
if (auth != null)
auth.endSession();
// LOG.debug(connectionId + " Main thread(client->remote)stopped.");
}
break;
case ACCEPT_MODE:
try {
doAccept();
mode = PIPE_MODE;
pipe_thread1.interrupt(); // Tell other thread that connection have
// been accepted.
pipe(remote_in, out);
} catch (IOException ioe) {
// log("Accept exception:"+ioe);
handleException(ioe);
} finally {
abort();
// LOG.debug(connectionId + " Accept thread(remote->client) stopped");
}
break;
case PIPE_MODE:
try {
pipe(remote_in, out);
} catch (IOException ioe) {
} finally {
abort();
// LOG.debug(connectionId + " Support thread(remote->client) stopped");
}
break;
case ABORT_MODE:
break;
default:
// LOG.info(connectionId + " Unexpected MODE " + mode);
}
}
// Private methods
/////////////////
private void startSession() throws IOException {
sock.setSoTimeout(idleTimeout);
try {
auth = auth.startSession(sock);
} catch (IOException ioe) {
// LOG.info(connectionId + " Auth exception", ioe);
auth = null;
return;
}
if (auth == null) { // Authentication failed
// LOG.warn(connectionId + " Authentication failed");
return;
}
in = auth.getInputStream();
out = auth.getOutputStream();
msg = readMsg(in);
// Set the connection ID in the message.
// msg.setConnectionId(connectionId);
handleRequest(msg);
}
private void handleRequest(ProxyMessage msg) throws IOException {
if (!auth.checkRequest(msg)) {
ProxyMessage response = new Socks5Message(Proxy.SOCKS_NOT_ALLOWED_BY_RULESET);
response.write(out);
abort();
throw new SocksException(Proxy.SOCKS_NOT_ALLOWED_BY_RULESET);
}
if (msg.ip == null) {
if (msg instanceof Socks5Message) {
msg.ip = InetAddress.getByName(msg.host);
} else
throw new SocksException(Proxy.SOCKS_FAILURE);
}
// LOG.debug(connectionId + " " + msg);
switch (msg.command) {
case Proxy.SOCKS_CMD_CONNECT:
onConnect(msg);
break;
case Proxy.SOCKS_CMD_BIND:
onBind(msg);
break;
case Proxy.SOCKS_CMD_UDP_ASSOCIATE:
onUDP(msg);
break;
default:
throw new SocksException(Proxy.SOCKS_CMD_NOT_SUPPORTED);
}
}
private void handleException(IOException ioe) {
// If we couldn't read the request, return;
if (msg == null)
return;
// If have been aborted by other thread
if (mode == ABORT_MODE)
return;
// If the request was successfully completed, but exception happened later
if (mode == PIPE_MODE)
return;
int error_code = Proxy.SOCKS_FAILURE;
if (ioe instanceof SocksException)
error_code = ((SocksException) ioe).errCode;
else if (ioe instanceof NoRouteToHostException)
error_code = Proxy.SOCKS_HOST_UNREACHABLE;
else if (ioe instanceof ConnectException)
error_code = Proxy.SOCKS_CONNECTION_REFUSED;
else if (ioe instanceof InterruptedIOException)
error_code = Proxy.SOCKS_TTL_EXPIRE;
if (error_code > Proxy.SOCKS_ADDR_NOT_SUPPORTED || error_code < 0) {
error_code = Proxy.SOCKS_FAILURE;
}
sendErrorMessage(error_code);
}
private void onConnect(ProxyMessage msg) throws IOException {
Socket s;
ProxyMessage response = null;
if (proxy == null) {
s = new Socket();
//s.setReceiveBufferSize(VT.VT_NETWORK_PACKET_BUFFER_SIZE - 1);
//s.setSendBufferSize(VT.VT_NETWORK_PACKET_BUFFER_SIZE - 1);
//s.setReuseAddress(true);
s.connect(new InetSocketAddress(msg.ip, msg.port));
//s = new Socket(msg.ip, msg.port);
s.setTcpNoDelay(true);
s.setKeepAlive(true);
//s.setSoTimeout(60000);
//s.setSoLinger(true, 0);
} else {
s = new SocksSocket(proxy, msg.ip, msg.port);
s.setTcpNoDelay(true);
s.setKeepAlive(true);
//s.setSoTimeout(60000);
//s.setSoLinger(true, 0);
}
// LOG.info(connectionId + " Connected to " + s.getInetAddress() + ":" +
// s.getPort());
if (msg instanceof Socks5Message) {
response = new Socks5Message(Proxy.SOCKS_SUCCESS, s.getLocalAddress(), s.getLocalPort());
} else {
response = new Socks4Message(Socks4Message.REPLY_OK, s.getLocalAddress(), s.getLocalPort());
}
response.write(out);
startPipe(s);
}
private void onBind(ProxyMessage msg) throws IOException {
ProxyMessage response = null;
if (proxy == null) {
ss = new ServerSocket(0);
// ss = new ServerSocket(msg.port);
} else {
ss = new SocksServerSocket(proxy, msg.ip, msg.port);
}
ss.setSoTimeout(acceptTimeout);
// LOG.info(connectionId + " Trying accept on " + ss.getInetAddress() + ":" +
// ss.getLocalPort());
if (msg.version == 5)
response = new Socks5Message(Proxy.SOCKS_SUCCESS, ss.getInetAddress(), ss.getLocalPort());
else
response = new Socks4Message(Socks4Message.REPLY_OK, ss.getInetAddress(), ss.getLocalPort());
response.write(out);
mode = ACCEPT_MODE;
pipe_thread1 = Thread.currentThread();
pipe_thread2 = new Thread(this);
pipe_thread2.start();
// Make timeout infinit.
sock.setSoTimeout(0);
int eof = 0;
try {
while ((eof = in.read()) >= 0) {
if (mode != ACCEPT_MODE) {
if (mode != PIPE_MODE)
return;// Accept failed
remote_out.write(eof);
remote_out.flush();
break;
}
}
} catch (EOFException eofe) {
// System.out.println("EOF exception");
return;// Connection closed while we were trying to accept.
} catch (InterruptedIOException iioe) {
// Accept thread interrupted us.
// System.out.println("Interrupted");
if (mode != PIPE_MODE)
return;// If accept thread was not successfull return.
} finally {
// System.out.println("Finnaly!");
}
if (eof < 0)// Connection closed while we were trying to accept;
return;
// Do not restore timeout, instead timeout is set on the
// remote socket. It does not make any difference.
pipe(in, remote_out);
}
private void onUDP(ProxyMessage msg) throws IOException {
if (msg.ip.getHostAddress().equals("0.0.0.0") || msg.ip.getHostAddress().equals("::")
|| msg.ip.getHostAddress().equals("::0") || msg.ip.getHostAddress().equals("0:0:0:0:0:0:0:0")
|| msg.ip.getHostAddress().equals("00:00:00:00:00:00:00:00")
|| msg.ip.getHostAddress().equals("0000:0000:0000:0000:0000:0000:0000:0000"))
msg.ip = sock.getInetAddress();
// LOG.info(connectionId + " Creating UDP relay server for " + msg.ip +
// ":" + msg.port);
relayServer = new UDPRelayServer(msg.ip, msg.port, Thread.currentThread(), sock, auth);
ProxyMessage response;
response = new Socks5Message(Proxy.SOCKS_SUCCESS, relayServer.relayIP, relayServer.relayPort);
response.write(out);
relayServer.start();
// Make timeout infinit.
sock.setSoTimeout(0);
try {
while (in.read() >= 0)
/* do nothing */;
} catch (EOFException eofe) {
}
}
// Private methods
//////////////////
private void doAccept() throws IOException {
Socket s;
long startTime = System.currentTimeMillis();
// System.out.println("ProxyServer doAccept()");
// System.out.println("ProxyServer port: " + ss.getLocalPort());
while (true) {
//ss.setReuseAddress(true);
//ss.setReceiveBufferSize(VT.VT_NETWORK_PACKET_BUFFER_SIZE - 1);
s = ss.accept();
//s.setSendBufferSize(VT.VT_NETWORK_PACKET_BUFFER_SIZE - 1);
s.setTcpNoDelay(true);
s.setKeepAlive(true);
//s.setSoTimeout(60000);
//s.setSoLinger(true, 0);
// if(s.getInetAddress().equals(msg.ip)){
if (s != null) {
// got the connection from the right host
// Close listenning socket.
ss.close();
break;
} else if (ss instanceof SocksServerSocket) {
// We can't accept more then one connection
if (s != null) {
s.close();
}
ss.close();
throw new SocksException(Proxy.SOCKS_FAILURE);
} else {
if (acceptTimeout != 0) { // If timeout is not infinit
int newTimeout = acceptTimeout - (int) (System.currentTimeMillis() - startTime);
if (newTimeout <= 0)
throw new InterruptedIOException("In doAccept()");
ss.setSoTimeout(newTimeout);
}
if (s != null) {
s.close(); // Drop all connections from other hosts
}
}
}
// Accepted connection
remote_sock = s;
remote_in = s.getInputStream();
remote_out = s.getOutputStream();
// Set timeout
remote_sock.setSoTimeout(idleTimeout);
// LOG.info(connectionId + " Accepted from "+ s.getInetAddress() + ":" +
// s.getPort());
ProxyMessage response;
if (msg.version == 5)
response = new Socks5Message(Proxy.SOCKS_SUCCESS, s.getInetAddress(), s.getPort());
else
response = new Socks4Message(Socks4Message.REPLY_OK, s.getInetAddress(), s.getPort());
response.write(out);
}
private ProxyMessage readMsg(InputStream in) throws IOException {
PushbackInputStream push_in;
if (in instanceof PushbackInputStream)
push_in = (PushbackInputStream) in;
else
push_in = new PushbackInputStream(in);
int version = push_in.read();
push_in.unread(version);
ProxyMessage msg;
if (version == 5) {
msg = new Socks5Message(push_in, false);
} else if (version == 4) {
msg = new Socks4Message(push_in, false);
} else {
throw new SocksException(Proxy.SOCKS_FAILURE);
}
return msg;
}
private void startPipe(Socket s) {
mode = PIPE_MODE;
remote_sock = s;
try {
remote_in = s.getInputStream();
remote_out = s.getOutputStream();
pipe_thread1 = Thread.currentThread();
pipe_thread2 = new Thread(this);
pipe_thread2.start();
pipe(in, remote_out);
} catch (IOException ioe) {
}
}
private void sendErrorMessage(int error_code) {
ProxyMessage err_msg;
if (msg instanceof Socks4Message)
err_msg = new Socks4Message(Socks4Message.REPLY_REJECTED);
else
err_msg = new Socks5Message(error_code);
try {
err_msg.write(out);
} catch (IOException ioe) {
}
}
private synchronized void abort() {
if (mode == ABORT_MODE)
return;
mode = ABORT_MODE;
try {
// LOG.info(connectionId + " Closing connection.");
if (remote_sock != null)
remote_sock.close();
if (sock != null)
sock.close();
if (relayServer != null)
relayServer.stop();
if (ss != null)
ss.close();
if (pipe_thread1 != null)
pipe_thread1.interrupt();
if (pipe_thread2 != null)
pipe_thread2.interrupt();
} catch (IOException ioe) {
}
}
private void pipe(InputStream in, OutputStream out) throws IOException {
lastReadTime = System.currentTimeMillis();
byte[] buf = new byte[BUF_SIZE];
int len = 0;
while (len >= 0) {
try {
if (len != 0) {
out.write(buf, 0, len);
out.flush();
}
len = in.read(buf);
lastReadTime = System.currentTimeMillis();
} catch (InterruptedIOException iioe) {
if (idleTimeout == 0)
return;// Other thread interrupted us.
long timeSinceRead = System.currentTimeMillis() - lastReadTime;
if (timeSinceRead >= idleTimeout - 1000) // -1s for adjustment.
return;
len = 0;
}
}
}
static final String command_names[] = { "CONNECT", "BIND", "UDP_ASSOCIATE" };
static final String command2String(int cmd) {
if (cmd > 0 && cmd < 4)
return command_names[cmd - 1];
else
return "Unknown Command " + cmd;
}
}
|
wknishio/variable-terminal
|
src/jsocks/net/sourceforge/jsocks/socks/ProxyServer.java
|
Java
|
mit
| 18,739
|
#include <iostream>
#include <sstream>
#include "../swissarmyknife/enums/smart_enum.hpp"
namespace myapp {
SMART_ENUM(State,
enum State {
RUNNING,
SLEEPING,
FAULT,
UNKNOWN,
CO_545OL
})
/*struct State : public swissarmyknife::enums::SmartEnum<State::Nice> {
enum Nice { RUNNING, SLEEPING, FAULT, UNKNOWN, CO_545OL };
State(const State::Nice& value) : SmartEnum<State::Nice>(value) { }
State(const std::string value) : SmartEnum<State::Nice>(value) { }
protected:
virtual const std::string enumDeclaration() {
return std::string("enum State { RUNNING, SLEEPING, FAULT, UNKNOWN, CO_545OL }");
}
};*/
}
int main(int argc, char** argv) {
using namespace myapp;
std::stringstream ss;
ss << State::FAULT;
std::string myEnumStr = ss.str();
std::cout << State::RUNNING << " stringified : " << myEnumStr << std::endl;
std::cout << State::SLEEPING << " stringified : " << myapp::State::to_string(State::SLEEPING) << std::endl;
std::cout << State::FAULT << " stringified : " << State::FAULT << std::endl;
std::cout << State::UNKNOWN << " stringified : " << State::UNKNOWN << std::endl;
std::cout << State::CO_545OL<< " stringified : " << State::CO_545OL << std::endl;
State::State cool = State::from_string("FAULT");
std::cout << State::FAULT << " from string : " << static_cast<size_t>(cool) << std::endl;
return 0;
}
|
daminetreg/lib-cpp-swissarmyknife
|
test/enums.cpp
|
C++
|
mit
| 1,563
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>edit permison</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.5 -->
<link rel="stylesheet" href="../../bootstrap/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="../../dist/css/AdminLTE.min.css">
<!-- http://localhost/ease/. Choose a skin from the css/skins
folder instead of downloading all of them to reduce the load. -->
<link rel="stylesheet" href="../../dist/css/skins/_all-skins.min.css">
<!-- iCheck -->
<link rel="stylesheet" href="plugins/iCheck/flat/blue.css">
<!-- Date Picker -->
<link rel="stylesheet" href="../../plugins/datepicker/datepicker3.css">
<!-- Daterange picker -->
<link rel="stylesheet" href="../../plugins/daterangepicker/daterangepicker-bs3.css">
<!-- fullCalendar 2.2.5-->
<link rel="stylesheet" href="plugins/fullcalendar/fullcalendar.min.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<header class="main-header">
<!-- Logo -->
<a href="index2.html" class="logo">
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class="logo-mini"><b>I</b>EE</span>
<!-- logo for regular state and mobile devices -->
<span class="logo-lg">
<!--img src="../../dist/img/logo.png" class="img-circle" alt="Logo Image"-->
<span style="color:#fff"><b>IEE</b> SYSTEM</span>
</span>
</a>
<!-- Header Navbar: style can be found in header.less -->
<nav class="navbar navbar-static-top" role="navigation">
<!-- Sidebar toggle button-->
<a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
<span class="sr-only">Toggle navigation</span>
</a>
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<!-- Messages: style can be found in dropdown.less-->
<li class="dropdown messages-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-envelope-o"></i>
<span class="label label-success">4</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 4 messages</li>
<li>
<!-- inner menu: contains the actual data -->
<ul class="menu">
<li><!-- start message -->
<a href="#">
<div class="pull-left">
<img src="../../dist/img/user2-160x160.jpg" class="img-circle" alt="User Image">
</div>
<h4>
Support Team
<small><i class="fa fa-clock-o"></i> 5 mins</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li><!-- end message -->
<li>
<a href="#">
<div class="pull-left">
<img src="../../dist/img/user3-128x128.jpg" class="img-circle" alt="User Image">
</div>
<h4>
Admin Design Team
<small><i class="fa fa-clock-o"></i> 2 hours</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<li>
<a href="#">
<div class="pull-left">
<img src="../../dist/img/user4-128x128.jpg" class="img-circle" alt="User Image">
</div>
<h4>
Developers
<small><i class="fa fa-clock-o"></i> Today</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<li>
<a href="#">
<div class="pull-left">
<img src="../../dist/img/user3-128x128.jpg" class="img-circle" alt="User Image">
</div>
<h4>
Sales Department
<small><i class="fa fa-clock-o"></i> Yesterday</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<li>
<a href="#">
<div class="pull-left">
<img src="../../dist/img/user4-128x128.jpg" class="img-circle" alt="User Image">
</div>
<h4>
Reviewers
<small><i class="fa fa-clock-o"></i> 2 days</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
</ul>
</li>
<li class="footer"><a href="#">See All Messages</a></li>
</ul>
</li>
<!-- Notifications: style can be found in dropdown.less -->
<li class="dropdown notifications-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-bell-o"></i>
<span class="label label-warning">10</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 10 notifications</li>
<li>
<!-- inner menu: contains the actual data -->
<ul class="menu">
<li>
<a href="#">
<i class="fa fa-users text-aqua"></i> 5 new members joined today
</a>
</li>
<li>
<a href="#">
<i class="fa fa-warning text-yellow"></i> Very long description here that may not fit into the page and may cause design problems
</a>
</li>
<li>
<a href="#">
<i class="fa fa-users text-red"></i> 5 new members joined
</a>
</li>
<li>
<a href="#">
<i class="fa fa-shopping-cart text-green"></i> 25 sales made
</a>
</li>
<li>
<a href="#">
<i class="fa fa-user text-red"></i> You changed your username
</a>
</li>
</ul>
</li>
<li class="footer"><a href="#">View all</a></li>
</ul>
</li>
<!-- Tasks: style can be found in dropdown.less -->
<li class="dropdown tasks-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-flag-o"></i>
<span class="label label-danger">9</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 9 tasks</li>
<li>
<!-- inner menu: contains the actual data -->
<ul class="menu">
<li><!-- Task item -->
<a href="#">
<h3>
Design some buttons
<small class="pull-right">20%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-aqua" style="width: 20%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">20% Complete</span>
</div>
</div>
</a>
</li><!-- end task item -->
<li><!-- Task item -->
<a href="#">
<h3>
Create a nice theme
<small class="pull-right">40%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-green" style="width: 40%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">40% Complete</span>
</div>
</div>
</a>
</li><!-- end task item -->
<li><!-- Task item -->
<a href="#">
<h3>
Some task I need to do
<small class="pull-right">60%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-red" style="width: 60%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">60% Complete</span>
</div>
</div>
</a>
</li><!-- end task item -->
<li><!-- Task item -->
<a href="#">
<h3>
Make beautiful transitions
<small class="pull-right">80%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-yellow" style="width: 80%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">80% Complete</span>
</div>
</div>
</a>
</li><!-- end task item -->
</ul>
</li>
<li class="footer">
<a href="#">View all tasks</a>
</li>
</ul>
</li>
<!-- User Account: style can be found in dropdown.less -->
<li class="dropdown user user-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<img src="../../dist/img/user4-128x128.jpg" class="user-image" alt="User Image">
<span class="hidden-xs">Hà Hằng</span>
</a>
<ul class="dropdown-menu">
<!-- User image -->
<li class="user-header">
<img src="../../dist/img/user2-160x160.jpg" class="img-circle" alt="User Image">
<p>
Alexander Pierce - Web Developer
<small>Member since Nov. 2012</small>
</p>
</li>
<!-- Menu Footer-->
<li class="user-footer">
<div class="pull-left">
<a href="#" class="btn btn-default btn-flat">My Profile</a>
</div>
<div class="pull-right">
<a href="#" class="btn btn-danger">Sign out</a>
</div>
</li>
</ul>
</li>
</ul>
</div>
</nav>
</header>
<!-- Left side column. contains the logo and sidebar -->
<aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- sidebar menu: : style can be found in sidebar.less -->
<ul class="sidebar-menu">
<li class="active treeview">
<a href="#">
<i class="fa fa-graduation-cap"></i> <span>Quản lý lớp học</span> <i class="fa fa-angle-left pull-right"></i>
</a>
<ul class="treeview-menu">
<li><a href=""><i class="fa fa-plus"></i> Thêm mới</a></li>
<li><a href=""><i class="fa fa-trash"></i> Cập nhật</a></li>
<li><a href=""><i class="fa fa-list"></i> Danh sách lớp học</a></li>
</ul>
</li>
<li class=" treeview">
<a href="#">
<i class="fa fa-users"></i>
<span>Quản lý học sinh</span>
<span class="fa fa-angle-down pull-right"></span>
</a>
<ul class="treeview-menu">
<li><a href=""><i class="fa fa-plus"></i> Them Hoc Vien</a></li>
<li><a href=""><i class="fa fa-trash"></i> Xoa Hoc Vien</a></li>
<li><a href=""><i class="fa fa-list"></i> Danh Sach hoc vien</a></li>
</ul>
</li>
<li class=" treeview">
<a href="#">
<i class="fa fa-calendar-check-o"></i> <span>Quản lý thời khóa biểu</span> <i class="fa fa-angle-left pull-right"></i>
</a>
<ul class="treeview-menu">
<li><a href=""><i class="fa fa-plus"></i> Them thoi khoa bieu</a></li>
<li><a href=""><i class="fa fa-trash"></i> Xoa thoi khoa bieu</a></li>
<li><a href=""><i class="fa fa-list"></i> Danh thoi khoa bieu vien</a></li>
</ul>
</li>
<li class=" treeview">
<a href="#">
<i class="fa fa-cogs"></i> <span>Quản trị hệ thống</span> <i class="fa fa-angle-left pull-right"></i>
</a>
</li>
</ul>
</section>
<!-- /.sidebar -->
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Dashboard
<small>User</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active">edit-permission</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<section class=" content-addnew box box-solid ">
<div class=" box-body">
<div class="box-header with-border">
<h3 class="box-title"> Nhóm: Admin</h3>
</div>
<br/>
<form class="form-horizontal">
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
Nhóm danh mục: Giới thiệu
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body">
<div class="group-checkbox">
<div class="checkbox"><label><input type="checkbox" checked="">Read</label></div>
<div class="checkbox"><label><input type="checkbox">Quản trị hệ thống</label></div>
<div class="checkbox"><label><input type="checkbox">-- Trang chủ</label></div>
<div class="checkbox"><label><input type="checkbox"> -- Cấu hình</label></div>
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingTwo">
<h4 class="panel-title">
<a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
Nhóm danh mục: Dịch vụ tại phòng khám
</a>
</h4>
</div>
<div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
<div class="panel-body">
<div class="group-checkbox">
<div class="checkbox"><label><input type="checkbox" checked="">Read</label></div>
<div class="checkbox"><label><input type="checkbox">Quản trị hệ thống</label></div>
<div class="checkbox"><label><input type="checkbox">-- Trang chủ</label></div>
<div class="checkbox"><label><input type="checkbox"> -- Cấu hình</label></div>
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingThree">
<h4 class="panel-title">
<a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
Nhóm danh mục: Tra cứu
</a>
</h4>
</div>
<div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">
<div class="panel-body">
<div class="group-checkbox">
<div class="checkbox"><label><input type="checkbox" checked="">Read</label></div>
<div class="checkbox"><label><input type="checkbox">Quản trị hệ thống</label></div>
<div class="checkbox"><label><input type="checkbox">-- Trang chủ</label></div>
<div class="checkbox"><label><input type="checkbox"> -- Cấu hình</label></div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="box-footer center">
<button class="btn btn-info " type="submit">Save</button>
<button class="btn btn-default" type="submit">Cancel</button>
</div><!-- /.box-footer -->
</section>
</section><!-- /.content -->
</div><!-- /.content-wrapper -->
<footer class="main-footer">
<div class="pull-right hidden-xs">
<b>Version</b> 1.0
</div>
<strong>Copyright © 2016 <a href="">Trung Nguyen Thanh</a>.</strong> All rights reserved.
</footer>
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class="control-sidebar-bg"></div>
</div><!-- ./wrapper -->
<!-- jQuery 2.1.4 -->
<script src="../../plugins/jQuery/jQuery-2.1.4.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>
$.widget.bridge('uibutton', $.ui.button);
</script>
<!-- Bootstrap 3.3.5 -->
<script src="../../bootstrap/js/bootstrap.min.js"></script>
<!-- Morris.js charts -->
<!-- script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script-->
<!--script src="plugins/morris/morris.min.js"></script-->
<!-- Sparkline -->
<!--script src="plugins/sparkline/jquery.sparkline.min.js"></script>
<!-- jvectormap -->
<!--script src="plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<!-- jQuery Knob Chart -->
<!-- script src="plugins/knob/jquery.knob.js"></script>
<!-- daterangepicker -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>
<script src="../../plugins/daterangepicker/daterangepicker.js"></script>
<!-- datepicker -->
<script src="../../plugins/datepicker/bootstrap-datepicker.js"></script>
<!-- Bootstrap WYSIHTML5 -->
<script src="../../plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
<!-- Slimscroll -->
<!-- Admin App -->
<script src="../../dist/js/app.min.js"></script>
<!-- Admin dashboard demo (This is only for demo purposes) -->
<script src="../../dist/js/pages/dashboard.js"></script>
</body>
</html>
|
trungjc/quanlyhocsinh
|
pages/user/edit-permission.html
|
HTML
|
mit
| 22,040
|
<?php
/* Security check */
if (!defined('RESTExample')) {
die("Direct access not permitted\n");
}
/** Contact collection */
class ContactCollection extends SimpleREST\Legacy\Database\DatabaseCollection {
/** */
public function __construct() {
parent::setTableName('contact');
}
}
|
sendanor/php-rest
|
examples/v1/src/ContactCollection.class.php
|
PHP
|
mit
| 290
|
'use strict';
module.exports = {
SET_COUNTRY: function(state, value) {
state.countryCode = value;
},
SET_PERIOD: function(state, value) {
state.period = value;
}
};
|
openspending/subsidystories.eu
|
app/scripts/application/store/mutations.js
|
JavaScript
|
mit
| 182
|
/*------------------------------------*\
# base.container
\*------------------------------------*/
.container {
margin: 0 auto;
}
@media all and (--from-xlarge) {
.container {
}
}
.container__fixed {
height: 100%;
}
.container__main {
min-height: 100%;
}
@media all and (--from-xlarge) {
.container__main {
width: 1280px;
}
}
|
Baasic/baasic-starterkit-angularjs-blog
|
src/themes/gastro-thumbnail/src/base.container.css
|
CSS
|
mit
| 366
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>18 --> 19</title>
<link href="./../../assets/style.css" rel="stylesheet">
</head>
<body>
<h2>You have to be fast</h2>
<a href="./0df314d3d7dda98f5118cf2136a08fb1125a7b0939296685e112ceb243a8494d.html">Teleport</a>
<hr>
<a href="./../../about.md">About</a> (Spoilers! )
<script src="./../../assets/md5.js"></script>
<script>
window.currentLevel = 7;
</script>
<script src="./../../assets/script.js"></script>
</body>
</html>
|
simonmysun/praxis
|
TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/b49ac23dc9df07614076ab4802fb1df030cf3304d54486fe355c95263f2c5f62.html
|
HTML
|
mit
| 550
|
# GimiqsVM
Virtual Machine with 128bit Lisp-like CONS CELLs(Briqs) for Programming Language
## Briq?
Briq is 128bit Lisp-like 'CONS CELL'.
We call formar pointer 'P', and latter 'Q'.
```
+-----+-----+
| P | Q |
+-----+-----+
```
Briq has bit patterns below.
```
0 2 4 6 8 10 12 14 16(byte)
+-----+-----+-----+-----+-----+-----+-----+-----+
|Type1|Type2|BcktP|BcktQ| DntrP | DntrQ |
+-----+-----+-----+-----+-----+-----+-----+-----+
```
- Type1...main type of briq (2byte)
- Type2...sub type of briq (2byte)
- BcktP...bucket index of P (2byte)
- BcktQ...bucket index of Q (2byte)
- DntrP...denoter index of P (4byte)
- DntrQ...denoter index of Q (4byte)
## Internal of VM
GimiqsVM has 65536 buckets, and each bucket can have 4294967295 briqs.
|
cohyou/GimiqsVM
|
README.md
|
Markdown
|
mit
| 793
|
#pragma once
#include <vector>
#include <unordered_map>
#include <memory>
#include "Utils/StringId.h"
#include "Utils/Types.h"
#include "Math/Matrix.h"
#include "ObjectComponent.h"
namespace oakvr
{
class Object;
using ObjectSharedPointer = sp < Object > ;
using ObjectUniquePointer = up < Object > ;
using ObjectVector = std::vector < ObjectSharedPointer >;
using ObjectMap = std::unordered_map < oakvr::StringId, ObjectSharedPointer > ;
class Object: public std::enable_shared_from_this<Object>
{
public:
Object();
Object(const StringId &name);
virtual ~Object();
auto GetId() const -> const StringId &;
auto AddChild(ObjectSharedPointer pObj) -> void;
auto RemoveChild(ObjectSharedPointer pObj) -> void;
auto GetChildren() -> const ObjectVector &;
auto GetParent()->ObjectSharedPointer;
auto SetParent(ObjectSharedPointer pParent) -> void;
template <typename ComponentType>
auto AddComponent() -> std::shared_ptr<ComponentType>;
template <typename ComponentType>
auto GetComponent() -> std::shared_ptr<ComponentType>;
public:
ObjectSharedPointer m_pParent;
ObjectVector m_vecChildren;
StringId m_objID;
std::unordered_map<std::string, ObjectComponentSharedPointer> m_componentMap;
};
inline auto Object::GetId() const -> const StringId &
{
return m_objID;
}
inline auto Object::GetChildren() -> const ObjectVector &
{
return m_vecChildren;
}
inline auto Object::GetParent() -> ObjectSharedPointer
{
return m_pParent;
}
inline auto Object::SetParent(ObjectSharedPointer pParent) -> void
{
m_pParent = pParent;
}
template <typename ComponentType>
auto Object::AddComponent() -> std::shared_ptr<ComponentType>
{
auto pObjComp = std::make_shared<ComponentType>(shared_from_this());
auto componentTypeName = ComponentType::GetComponentClassTypeAsString();
m_componentMap[componentTypeName] = std::static_pointer_cast<ObjectComponent>(pObjComp);
return pObjComp;
}
template <typename ComponentType>
auto Object::GetComponent() -> std::shared_ptr<ComponentType>
{
auto componentTypeName = ComponentType::GetComponentClassTypeAsString();
auto it = m_componentMap.find(componentTypeName);
if (it != m_componentMap.end())
return std::dynamic_pointer_cast<ComponentType>(it->second);
else
return nullptr;
}
} // namespace oakvr
|
bluespeck/OakVR
|
src/Core/OakVR/Object.h
|
C
|
mit
| 2,350
|
var app = angular.module('Zespol', []);
//Filtr umożliwiający wstawienie scope jako link url
app.filter('trustAsResourceUrl', ['$sce', function($sce) {
return function(val) {
return $sce.trustAsResourceUrl(val);
};
}]);
app.controller('MusicCtrl', function($scope, $http){
$http.get("http://tolmax.type.pl/assets/php/music.php")
.then(function (response) {$scope.names = response.data.records;});
$scope.mysrctest = "http://tolmax.type.pl/uploads/music/01.Rehab.mp3";
$scope.myCategory = {
"Id rosnąco" : {wartosc : "id"},
"Id malejąco" : {wartosc : "-id"},
"Tytuł rosnąco" : {wartosc : "title"},
"Tytuł malejąco" : {wartosc : "-title"}
}
});
//Filtr zamieniajacy podłogi na spacje dla bezpieczenstwa bazy danych mtitle przechowuje nazwy z podłogami
app.filter('myFormat', function() {
return function(x) {
var i, c, txt = "";
for (i = 0; i < x.length; i++) {
c = x[i].replace(/_/g, " ");
txt += c;
}
return txt;
};
});
/////////
app.controller('VideoCtrl', function($scope, $http){
$http.get("http://tolmax.type.pl/assets/php/video.php")
.then(function (response) {$scope.names = response.data.records;});
$scope.myCategory = {
"Id rosnąco" : {wartosc : "id"},
"Id malejąco" : {wartosc : "-id"},
"Tytuł rosnąco" : {wartosc : "title"},
"Tytuł malejąco" : {wartosc : "-title"}
}
});
app.controller('PhotosCtrl', function($scope, $http){
$http.get("http://tolmax.type.pl/assets/php/photos.php")
.then(function (response) {$scope.names = response.data.records;});
$scope.myCategory = {
"Id rosnąco" : {wartosc : "id"},
"Id malejąco" : {wartosc : "-id"},
"Tytuł rosnąco" : {wartosc : "title"},
"Tytuł malejąco" : {wartosc : "-title"}
}
});
|
PiotrKulpa/spa
|
assets/js/my-app.js
|
JavaScript
|
mit
| 1,909
|
//------------------------------------------------------------------------------
// <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 Z.Lab.NamingIssue.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Z.Lab.NamingIssue.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
|
tamasflamich/effort
|
Main/Source/lab/Z.Lab.NamingIssue/Properties/Resources.Designer.cs
|
C#
|
mit
| 2,793
|
<!DOCTYPE html>
<html class="no-js" lang="ko">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="p5.js a JS client-side library for creating graphic and interactive experiences, based on the core principles of Processing.">
<title tabindex="1">showcase | p5.js</title>
<link rel="stylesheet" href="/assets/css/all.css?v=db3be6">
<link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inconsolata&display=swap" rel="stylesheet">
<link rel="shortcut icon" href="/../../assets/img/favicon.ico">
<link rel="icon" href="/../../assets/img/favicon.ico">
<script src="/../../assets/js/vendor/jquery-1.12.4.min.js"></script>
<script src="/../../assets/js/vendor/ace-nc/ace.js"></script>
<script src="/../../assets/js/vendor/ace-nc/mode-javascript.js"></script>
<script src="/../../assets/js/vendor/prism.js"></script>
<script src="/assets/js/init.js?v=af215d"></script>
</head>
<body>
<a href="#content" class="sr-only">건너뛰기</a>
<!-- p5*js language buttons -->
<div id="i18n-btn">
<h2 id="i18n-settings" class="sr-only">언어 설정</h2>
<ul id="i18n-buttons" aria-labelledby="i18n-settings">
<li><a href='#' lang='en' data-lang='en'>English</a></li>
<li><a href='#' lang='es' data-lang='es'>Español</a></li>
<li><a href='#' lang='zh-Hans' data-lang='zh-Hans'>简体中文</a></li>
<li><a href='#' lang='ko' data-lang='ko'>한국어</a></li>
</ul>
</div> <!-- .container -->
<div class="container">
<!-- logo -->
<header id="lockup">
<a href="/ko/">
<img src="/../../assets/img/p5js.svg" alt="p5 homepage" id="logo_image" class="logo" />
<div id="p5_logo"></div>
</a>
</header>
<!-- close logo -->
<div id="showcase-page">
<!-- site navigation -->
<div class="column-span">
<nav class="sidebar-menu-nav-element">
<h2 id="menu-title" class="sr-only">사이트 둘러보기</h2>
<input class="sidebar-menu-btn" type="checkbox" id="sidebar-menu-btn" />
<label class="sidebar-menu-icon" for="sidebar-menu-btn"><span class="sidebar-nav-icon"></span></label>
<ul id="menu" class="sidebar-menu" aria-labelledby="menu-title">
<li><a href="/ko/">홈</a></li>
<li><a href="https://editor.p5js.org">에디터</a></li>
<li><a href="/ko/download/">다운로드</a></li>
<li><a href="/ko/download/support.html">후원하기</a></li>
<li><a href="/ko/get-started/">시작하기</a></li>
<li><a href="/ko/reference/">레퍼런스</a></li>
<li><a href="/ko/libraries/">라이브러리</a></li>
<li><a href="/ko/learn/">배우기</a></li>
<li><a href="/ko/examples/">예제</a></li>
<li><a href="/ko/books/">출판물</a></li>
<li><a href="/ko/community/">커뮤니티</a></li>
<li><a href="https://showcase.p5js.org">쇼케이스</a></li>
<li><a href="https://discourse.processing.org/c/p5js" target=_blank class="other-link">포럼</a></li>
<li><a href="http://github.com/processing/p5.js" target=_blank class="other-link">GitHub</a></li>
<li><a href="http://twitter.com/p5xjs" target=_blank class="other-link">Twitter</a></li>
</ul>
</nav>
</div>
<main id="content" class="column-span">
<section class="showcase-intro">
<h1>쇼케이스</h1>
<p>쇼케이스는 2019년 강예은 <a href="https://ashleykang.dev" target="_blank">Ashley Kang</a>
이 제작, 기획하였으며, 2020년에는 코니 리우 <a href="https://connieliu0.github.io" target="_blank">Connie Liu</a>.
가 새로운 기획을 선보입니다. 쇼케이스는 p5.js를 보다 흥미진진하고 포용적으로 만든 창작물, 학습물, 오픈 소스 사례들을 기쁘게 소개합니다. 이렇게 우리는 함께 커뮤니티를 만들어 나가는게 아닐까요?:) 2019년 여름, 우리는 p5.js 기반의 다양한 프로젝트들을 소개한 바 있습니다.</p>
<p>현재 2020년 여름 쇼케이스를 모집중입니다. 아래의 버튼을 눌러 자신 또는 타인의 p5.js 작업을 추천해주세요!</p>
<span id="nominate" class="nominate"><a href="https://forms.gle/G8yqhVr4iEFAJnWa9" target="_blank">프로젝트 추천하기</a></span>
</section>
<section class="showcase-featured">
<h2 class="featuring">선정 프로젝트</h2>
<div class="left-column">
<div>
<h3 class="title"><a href="./featuring/roni-cantor.html">각도기 드로잉 프로그램(Programmed Plotter Drawings)</a></h3>
<p class="credit">Roni Cantor</p>
<a href="./featuring/roni-cantor.html" class="no-arrow-link">
<img src="../../assets/img/showcase/roni-cantor/roni-cantor_plotter-white.jpg"
alt="A drawing of a sine wave lerp plotted on black paper using an AxiDraw V3 and a white gel pen.">
</a>
<p class="description">p5.js로 제작한 사인파(Sine wave)와 선형 보간(lerp)으로, 실물 각도기와 펜과 연결되어 드로잉하고, SVG 파일로 내보내기 가능.</p>
<ul class="project-tags">
<li><a class="tag" href="https://p5js.org/reference/#/p5/lerp">lerp()</a></li>
</ul>
</div>
<div>
<h3 class="title"><a href="./featuring/daein-chung.html">Chillin'</a></h3>
<p class="credit">정대인(Dae In Chung)</p>
<a href="./featuring/daein-chung.html" class="no-arrow-link">
<img src="../../assets/img/showcase/daein-chung/daein-chung_chillin.png"
alt="A screenshot of a poster with red and yellow circles of letters from the word chillin against a blue tile background that changes perspective on a mobile device.
At the top, there is a text input box to enter a message and download your own poster">
</a>
<p class="description">모바일 기기의 모션 센서와 p5.js를 활용한 인터랙티브 타이포그래픽 포스터</p>
<ul class="project-tags">
<li><a class="tag" href="https://brm.io/matter-js/">matter.js</a></li>
<li><a class="tag" href="https://github.com/processing/p5.js/wiki/Getting-started-with-WebGL-in-p5">p5 WebGL</a></li>
<li><a class="tag" href="https://p5js.org/reference/#/p5.Camera">p5.Camera</a></li>
</ul>
</div>
<div>
<h3 class="title"><a href="./featuring/casey-louise.html">p5.js 셰이더(Shaders)</a></h3>
<p class="credit">캐시 콘치나(Casey Conchinha), 루이스 레셀(Louise Lessél)</p>
<a href="./featuring/casey-louise.html" class="no-arrow-link">
<img src="../../assets/img/showcase/casey-louise/casey-louise_p5js-shaders.png"
alt="A screenshot of the Introduction page of the p5.js Shaders guide website">
</a>
<p class="description">셰이더(Shaders)란 무엇이고, 이를 p5.js에서 왜, 그리고 어떻게 사용하는지 배울 수 있는 자료.</p>
<ul class="project-tags">
</ul>
</div>
</div>
<div class="right-column">
<div>
<h3 class="title"><a href="./featuring/phuong-ngo.html">날아라 아이리(Airi Flies)</a></h3>
<p class="credit">Phuong Ngo</p>
<a href="./featuring/phuong-ngo.html" class="no-arrow-link">
<img src="../../assets/img/showcase/phuong-ngo/phuong-ngo_airi-flies.png"
alt="A screenshot of the instructions and scoreboard for the online game Airi Flies">
</a>
<p class="description">p5.play로 제작된 게임으로, PEW라고 말해 아이리(Airi)가 날 수 있도록 돕는다. 사용자들이 자신의 안전 지대를 벗어난 곳에서도 행동, 외모, 발언에 상관없이 자신감을 갖게하고자 하는 취지에서 제작.</p>
<ul class="project-tags">
<li><a class="tag" href="http://molleindustria.github.io/p5.play/">p5.play</a></li>
<li><a class="tag" href="https://ml5js.org/">ml5.js</a></li>
</ul>
</div>
<div>
<h3 class="title"><a href="./featuring/qianqian-ye.html">Qtv</a></h3>
<p class="credit">치안치안 예(Qianqian Ye)</p>
<a href="./featuring/qianqian-ye.html" class="no-arrow-link">
<img src="../../assets/img/showcase/qianqian-ye/qianqian-ye_qtv.png"
alt="A screenshot of a Qtv video (Guest Talk #1) featuring Chinese womxn designers and artists Kaikai and Cheng Xu">
</a>
<p class="description">입문자를 위한 p5.js 튜토리얼을 포함하여, 코딩, 예술, 그리고 기술에 대해 다루는 1분 길이의 중국어 영상 채널들. 유투브, 인스타그램, 비리비리(Bilibili), 틱톡(TikTok)에서 확인 가능.</p>
<ul class="project-tags">
</ul>
</div>
<div>
<h3 class="title"><a href="./featuring/moon-xin.html">움직이는 반응형 포스터(Moving Responsive Posters)</a></h3>
<p class="credit">장문(Moon Jang), 씬 씬(Xin Xin), 그리고 학생들</p>
<a href="./featuring/moon-xin.html" class="no-arrow-link">
<img src="../../assets/img/showcase/moon-xin/moon-xin_poster-carlee.png"
alt="A screenshot of student Carlee Wooddell's poster that interprets the word zigzag using letters that bounce left and right">
</a>
<p class="description">브라우저 기반의 움직이는 포스터로, 그래픽 시스템과 변형 메소드, 그리고 p5.js를 사용하여 8자 미만 단어가 내포하는 바를 표현. 조지아 대학교(University of Georgia)의 그래픽 디자인 과정인 'Visual Narrative Systems'의 수강생들이 디자인.</p>
<ul class="project-tags">
<li><a class="tag" href="https://p5js.org/reference/#/p5/rect">rect()</a></li>
<li><a class="tag" href="https://p5js.org/reference/#/p5/translate">translate()</a></li>
</ul>
</div>
</div>
</section>
<footer>
<h2 class="sr-only">스케치 크레딧</h2>
<p> p5.js는 현재 모이라 터너 <a href='https://github.com/mcturner1995' target="_blank">Moira
Turner</a> 가 리드하며, 로렌 맥카시 <a href='http://lauren-mccarthy.com' target="_blank">Lauren
McCarthy</a> 가 창안하고 협력자 커뮤니티와 함께 개발하였습니다. 지원: 프로세싱 재단 <a href="http://processing.org/foundation/" target="_blank">Processing
Foundation</a> 과
<a href="http://itp.nyu.edu/itp/" target="_blank">NYU ITP</a>. 아이덴티티 및 그래픽 디자인: <a
href="http://jereljohnson.com/" target="_blank">Jerel Johnson</a>. <a href="/ko/copyright.html">©
Info.</a></p>
</footer>
</main>
<!-- outside of column for footer to go across both -->
<p class="clearfix"> </p>
<object type="image/svg+xml" data="../../assets/img/thick-asterisk-alone.svg" id="asterisk-design-element" aria-hidden="true">
</object>
</div>
</div> <!-- close class='container'-->
<nav id="family" aria-labelledby="processing-sites-heading">
<h2 id="processing-sites-heading" class="sr-only">Processing Sister Sites</h2>
<ul id="processing-sites" aria-labelledby="processing-sites-heading">
<li><a href="http://processing.org">Processing</a></li>
<li><a class="here" href="/ko/">p5.js</a></li>
<li><a href="http://py.processing.org/">Processing.py</a></li>
<li><a href="http://android.processing.org/">Processing for Android</a></li>
<li><a href="http://pi.processing.org/">Processing for Pi</a></li>
<li><a href="https://processingfoundation.org/">Processing Foundation</a></li>
</ul>
<a tabindex="1" href="#content" id="skip-to-content">Skip to main content</a>
<!-- <a id="promo-link" href="https://donorbox.org/supportpf2019-fundraising-campaign" target="_blank"><div id="promo">This season, we need your help! Click here to #SupportP5!</div></a> -->
</nav> <script>
var langs = ["en","es","ko","zh-Hans"];
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-53383000-1', 'auto');
ga('send', 'pageview');
$(window).ready(function() {
if (window.location.pathname !== '/' && window.location.pathname !== '/index.html') {
$('#top').remove();
} else {
$('#top').show();
}
});
</script>
</body>
</html>
|
mayaman/p5js-website
|
ko/showcase/index.html
|
HTML
|
mit
| 13,199
|
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% if page.title %}{{ page.title }} |{% endif %} {{ site.theme_settings.title }}</title>
<meta name="description" content="{% if page.excerpt %}{{ page.excerpt | strip_html | strip_newlines | truncate: 160 }}{% else %}{{ site.theme_settings.description }}{% endif %}">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- <meta http-equiv="X-Frame-Options" content="sameorigin"> -->
<!-- CSS -->
<link rel="stylesheet" href="{{ "/css/main.css" | prepend: site.baseurl }}">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
<!--Favicon-->
<link rel="shortcut icon" href="{{ "/favicon.ico" | prepend: site.baseurl }}" type="image/x-icon">
<!-- Canonical -->
<link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
<!-- RSS -->
<link rel="alternate" type="application/atom+xml" title="{{ site.theme_settings.title }}" href="{{ "/feed.xml" | prepend: site.baseurl | prepend: site.url }}" />
<!-- Font Awesome -->
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
<!-- Google Fonts -->
{% if site.theme_settings.google_fonts %}
<link href="//fonts.googleapis.com/css?family={{ site.theme_settings.google_fonts }}" rel="stylesheet" type="text/css">
{% endif %}
<!-- KaTeX -->
{% if site.theme_settings.katex %}
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min.css">
<script async src="//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min.js"></script>
{% endif %}
<script defer src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<!-- Google Analytics -->
{% if site.theme_settings.google_analytics %}
<script async>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '{{ site.theme_settings.google_analytics }}', 'auto');
ga('send', 'pageview');
</script>
{% endif %}
</head>
|
mcheang20/mcheang20.github.io
|
_includes/head.html
|
HTML
|
mit
| 2,426
|
module PloggyHelper
@log_items = []
@use_project_time = false
def self.log_items
@log_items
end
def self.log_time
total_time_s = 0
@log_items.each{ |item|
start_time = DateTime.parse(item[:start_time])
end_time = (item[:end_time] == nil) ? start_time : DateTime.parse(item[:end_time])
spent_diff = end_time - start_time
total_time_s += spent_diff * 24 * 60 * 60
}
total_time_s
end
def self.sort_log_items
@log_items.sort! {|x, y| DateTime.parse(x[:start_time]) <=> DateTime.parse(y[:start_time])}
end
def self.sup_fix(num)
if num == 1
'st'
elsif num == 2
'nd'
elsif num == 3
'rd'
else
'th'
end
end
def self.time_to_s(time)
time = time.to_i
time_names = ['week', 'day', 'hour', 'minute', 'second']
time_values = [1.week, 1.day, 1.hour, 1.minute, 1.second]
time_split = [0, 0, 0, 0, 0]
# build an array with different time formats
while time > 0
time_split.length.times do |i|
if time >= time_values[i]
time -= time_values[i]
time_split[i] += 1
break
end
end
end
# build string out of array
time_a = []
time_split.length.times do |i|
if time_split[i] > 0
time_s = time_split[i].to_s + ' ' + time_names[i]
if time_split[i] != 1
time_s += 's'
end
time_a.push(time_s)
end
end
if time_a.length == 0
''
elsif time_a.length == 1
time_a[0]
else
time_a[0..-2].join(', ') + ' and ' + time_a[-1]
end
end
def self.use_project_time!(upt = true)
@use_project_time = upt
end
def self.use_project_time?
@use_project_time
end
def self.work_time(start_date, end_date)
start_date.step(end_date).select{|d| !d.saturday? && !d.sunday?}.size
end
end
# extend Fixnum
class Fixnum
def seconds
self
end
alias :second :seconds
def minutes
self * 60.seconds
end
alias :minute :minutes
def hours
self * 60.minutes
end
alias :hour :hours
def days
self * (PloggyHelper.use_project_time? ? PloggyConfigHelper.project_hours_per_day : 24.hours)
end
alias :day :days
def weeks
self * (PloggyHelper.use_project_time? ? PloggyConfigHelper.project_days_per_week : 7.days)
end
alias :week :weeks
end
|
Caster/Ploggy
|
lib/helpers/ploggy.rb
|
Ruby
|
mit
| 2,741
|
// Copyright 2016, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// AUTO-GENERATED CODE. DO NOT EDIT.
package pubsub
import (
"fmt"
"math"
"runtime"
"time"
"cloud.google.com/go/iam"
gax "github.com/googleapis/gax-go"
"golang.org/x/net/context"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"google.golang.org/api/transport"
pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
)
var (
subscriberProjectPathTemplate = gax.MustCompilePathTemplate("projects/{project}")
subscriberSubscriptionPathTemplate = gax.MustCompilePathTemplate("projects/{project}/subscriptions/{subscription}")
subscriberTopicPathTemplate = gax.MustCompilePathTemplate("projects/{project}/topics/{topic}")
)
// SubscriberCallOptions contains the retry settings for each method of SubscriberClient.
type SubscriberCallOptions struct {
CreateSubscription []gax.CallOption
GetSubscription []gax.CallOption
ListSubscriptions []gax.CallOption
DeleteSubscription []gax.CallOption
ModifyAckDeadline []gax.CallOption
Acknowledge []gax.CallOption
Pull []gax.CallOption
ModifyPushConfig []gax.CallOption
}
func defaultSubscriberClientOptions() []option.ClientOption {
return []option.ClientOption{
option.WithEndpoint("pubsub.googleapis.com:443"),
option.WithScopes(
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/pubsub",
),
}
}
func defaultSubscriberCallOptions() *SubscriberCallOptions {
retry := map[[2]string][]gax.CallOption{
{"default", "idempotent"}: {
gax.WithRetry(func() gax.Retryer {
return gax.OnCodes([]codes.Code{
codes.DeadlineExceeded,
codes.Unavailable,
}, gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.3,
})
}),
},
}
return &SubscriberCallOptions{
CreateSubscription: retry[[2]string{"default", "idempotent"}],
GetSubscription: retry[[2]string{"default", "idempotent"}],
ListSubscriptions: retry[[2]string{"default", "idempotent"}],
DeleteSubscription: retry[[2]string{"default", "idempotent"}],
ModifyAckDeadline: retry[[2]string{"default", "non_idempotent"}],
Acknowledge: retry[[2]string{"messaging", "non_idempotent"}],
Pull: retry[[2]string{"messaging", "non_idempotent"}],
ModifyPushConfig: retry[[2]string{"default", "non_idempotent"}],
}
}
// SubscriberClient is a client for interacting with Google Cloud Pub/Sub API.
type SubscriberClient struct {
// The connection to the service.
conn *grpc.ClientConn
// The gRPC API client.
subscriberClient pubsubpb.SubscriberClient
// The call options for this service.
CallOptions *SubscriberCallOptions
// The metadata to be sent with each request.
metadata metadata.MD
}
// NewSubscriberClient creates a new subscriber client.
//
// The service that an application uses to manipulate subscriptions and to
// consume messages from a subscription via the `Pull` method.
func NewSubscriberClient(ctx context.Context, opts ...option.ClientOption) (*SubscriberClient, error) {
conn, err := transport.DialGRPC(ctx, append(defaultSubscriberClientOptions(), opts...)...)
if err != nil {
return nil, err
}
c := &SubscriberClient{
conn: conn,
CallOptions: defaultSubscriberCallOptions(),
subscriberClient: pubsubpb.NewSubscriberClient(conn),
}
c.SetGoogleClientInfo("gax", gax.Version)
return c, nil
}
// Connection returns the client's connection to the API service.
func (c *SubscriberClient) Connection() *grpc.ClientConn {
return c.conn
}
// Close closes the connection to the API service. The user should invoke this when
// the client is no longer required.
func (c *SubscriberClient) Close() error {
return c.conn.Close()
}
// SetGoogleClientInfo sets the name and version of the application in
// the `x-goog-api-client` header passed on each request. Intended for
// use by Google-written clients.
func (c *SubscriberClient) SetGoogleClientInfo(name, version string) {
v := fmt.Sprintf("%s/%s %s gax/%s go/%s", name, version, gapicNameVersion, gax.Version, runtime.Version())
c.metadata = metadata.Pairs("x-goog-api-client", v)
}
// SubscriberProjectPath returns the path for the project resource.
func SubscriberProjectPath(project string) string {
path, err := subscriberProjectPathTemplate.Render(map[string]string{
"project": project,
})
if err != nil {
panic(err)
}
return path
}
// SubscriberSubscriptionPath returns the path for the subscription resource.
func SubscriberSubscriptionPath(project, subscription string) string {
path, err := subscriberSubscriptionPathTemplate.Render(map[string]string{
"project": project,
"subscription": subscription,
})
if err != nil {
panic(err)
}
return path
}
// SubscriberTopicPath returns the path for the topic resource.
func SubscriberTopicPath(project, topic string) string {
path, err := subscriberTopicPathTemplate.Render(map[string]string{
"project": project,
"topic": topic,
})
if err != nil {
panic(err)
}
return path
}
func (c *SubscriberClient) SubscriptionIAM(subscription *pubsubpb.Subscription) *iam.Handle {
return iam.InternalNewHandle(c.Connection(), subscription.Name)
}
func (c *SubscriberClient) TopicIAM(topic *pubsubpb.Topic) *iam.Handle {
return iam.InternalNewHandle(c.Connection(), topic.Name)
}
// CreateSubscription creates a subscription to a given topic.
// If the subscription already exists, returns `ALREADY_EXISTS`.
// If the corresponding topic doesn't exist, returns `NOT_FOUND`.
//
// If the name is not provided in the request, the server will assign a random
// name for this subscription on the same project as the topic. Note that
// for REST API requests, you must specify a name.
func (c *SubscriberClient) CreateSubscription(ctx context.Context, req *pubsubpb.Subscription) (*pubsubpb.Subscription, error) {
md, _ := metadata.FromContext(ctx)
ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
var resp *pubsubpb.Subscription
err := gax.Invoke(ctx, func(ctx context.Context) error {
var err error
resp, err = c.subscriberClient.CreateSubscription(ctx, req)
return err
}, c.CallOptions.CreateSubscription...)
if err != nil {
return nil, err
}
return resp, nil
}
// GetSubscription gets the configuration details of a subscription.
func (c *SubscriberClient) GetSubscription(ctx context.Context, req *pubsubpb.GetSubscriptionRequest) (*pubsubpb.Subscription, error) {
md, _ := metadata.FromContext(ctx)
ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
var resp *pubsubpb.Subscription
err := gax.Invoke(ctx, func(ctx context.Context) error {
var err error
resp, err = c.subscriberClient.GetSubscription(ctx, req)
return err
}, c.CallOptions.GetSubscription...)
if err != nil {
return nil, err
}
return resp, nil
}
// ListSubscriptions lists matching subscriptions.
func (c *SubscriberClient) ListSubscriptions(ctx context.Context, req *pubsubpb.ListSubscriptionsRequest) *SubscriptionIterator {
md, _ := metadata.FromContext(ctx)
ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
it := &SubscriptionIterator{}
it.InternalFetch = func(pageSize int, pageToken string) ([]*pubsubpb.Subscription, string, error) {
var resp *pubsubpb.ListSubscriptionsResponse
req.PageToken = pageToken
if pageSize > math.MaxInt32 {
req.PageSize = math.MaxInt32
} else {
req.PageSize = int32(pageSize)
}
err := gax.Invoke(ctx, func(ctx context.Context) error {
var err error
resp, err = c.subscriberClient.ListSubscriptions(ctx, req)
return err
}, c.CallOptions.ListSubscriptions...)
if err != nil {
return nil, "", err
}
return resp.Subscriptions, resp.NextPageToken, nil
}
fetch := func(pageSize int, pageToken string) (string, error) {
items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
if err != nil {
return "", err
}
it.items = append(it.items, items...)
return nextPageToken, nil
}
it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
return it
}
// DeleteSubscription deletes an existing subscription. All pending messages in the subscription
// are immediately dropped. Calls to `Pull` after deletion will return
// `NOT_FOUND`. After a subscription is deleted, a new one may be created with
// the same name, but the new one has no association with the old
// subscription, or its topic unless the same topic is specified.
func (c *SubscriberClient) DeleteSubscription(ctx context.Context, req *pubsubpb.DeleteSubscriptionRequest) error {
md, _ := metadata.FromContext(ctx)
ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
err := gax.Invoke(ctx, func(ctx context.Context) error {
var err error
_, err = c.subscriberClient.DeleteSubscription(ctx, req)
return err
}, c.CallOptions.DeleteSubscription...)
return err
}
// ModifyAckDeadline modifies the ack deadline for a specific message. This method is useful
// to indicate that more time is needed to process a message by the
// subscriber, or to make the message available for redelivery if the
// processing was interrupted. Note that this does not modify the
// subscription-level `ackDeadlineSeconds` used for subsequent messages.
func (c *SubscriberClient) ModifyAckDeadline(ctx context.Context, req *pubsubpb.ModifyAckDeadlineRequest) error {
md, _ := metadata.FromContext(ctx)
ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
err := gax.Invoke(ctx, func(ctx context.Context) error {
var err error
_, err = c.subscriberClient.ModifyAckDeadline(ctx, req)
return err
}, c.CallOptions.ModifyAckDeadline...)
return err
}
// Acknowledge acknowledges the messages associated with the `ack_ids` in the
// `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages
// from the subscription.
//
// Acknowledging a message whose ack deadline has expired may succeed,
// but such a message may be redelivered later. Acknowledging a message more
// than once will not result in an error.
func (c *SubscriberClient) Acknowledge(ctx context.Context, req *pubsubpb.AcknowledgeRequest) error {
md, _ := metadata.FromContext(ctx)
ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
err := gax.Invoke(ctx, func(ctx context.Context) error {
var err error
_, err = c.subscriberClient.Acknowledge(ctx, req)
return err
}, c.CallOptions.Acknowledge...)
return err
}
// Pull pulls messages from the server. Returns an empty list if there are no
// messages available in the backlog. The server may return `UNAVAILABLE` if
// there are too many concurrent pull requests pending for the given
// subscription.
func (c *SubscriberClient) Pull(ctx context.Context, req *pubsubpb.PullRequest) (*pubsubpb.PullResponse, error) {
md, _ := metadata.FromContext(ctx)
ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
var resp *pubsubpb.PullResponse
err := gax.Invoke(ctx, func(ctx context.Context) error {
var err error
resp, err = c.subscriberClient.Pull(ctx, req)
return err
}, c.CallOptions.Pull...)
if err != nil {
return nil, err
}
return resp, nil
}
// ModifyPushConfig modifies the `PushConfig` for a specified subscription.
//
// This may be used to change a push subscription to a pull one (signified by
// an empty `PushConfig`) or vice versa, or change the endpoint URL and other
// attributes of a push subscription. Messages will accumulate for delivery
// continuously through the call regardless of changes to the `PushConfig`.
func (c *SubscriberClient) ModifyPushConfig(ctx context.Context, req *pubsubpb.ModifyPushConfigRequest) error {
md, _ := metadata.FromContext(ctx)
ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
err := gax.Invoke(ctx, func(ctx context.Context) error {
var err error
_, err = c.subscriberClient.ModifyPushConfig(ctx, req)
return err
}, c.CallOptions.ModifyPushConfig...)
return err
}
// SubscriptionIterator manages a stream of *pubsubpb.Subscription.
type SubscriptionIterator struct {
items []*pubsubpb.Subscription
pageInfo *iterator.PageInfo
nextFunc func() error
// InternalFetch is for use by the Google Cloud Libraries only.
// It is not part of the stable interface of this package.
//
// InternalFetch returns results from a single call to the underlying RPC.
// The number of results is no greater than pageSize.
// If there are no more results, nextPageToken is empty and err is nil.
InternalFetch func(pageSize int, pageToken string) (results []*pubsubpb.Subscription, nextPageToken string, err error)
}
// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
func (it *SubscriptionIterator) PageInfo() *iterator.PageInfo {
return it.pageInfo
}
// Next returns the next result. Its second return value is iterator.Done if there are no more
// results. Once Next returns Done, all subsequent calls will return Done.
func (it *SubscriptionIterator) Next() (*pubsubpb.Subscription, error) {
if err := it.nextFunc(); err != nil {
return nil, err
}
item := it.items[0]
it.items = it.items[1:]
return item, nil
}
func (it *SubscriptionIterator) bufLen() int {
return len(it.items)
}
func (it *SubscriptionIterator) takeBuf() interface{} {
b := it.items
it.items = nil
return b
}
|
jordanpotter/remote-backup
|
vendor/cloud.google.com/go/pubsub/apiv1/subscriber_client.go
|
GO
|
mit
| 13,956
|
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CountryListSortComponent } from './country-list-sort.component';
describe('CountryListSortComponent', () => {
let component: CountryListSortComponent;
let fixture: ComponentFixture<CountryListSortComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ CountryListSortComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CountryListSortComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});
|
liebsoer/country-viewer
|
src/app/component/country-list-sort/country-list-sort.component.spec.ts
|
TypeScript
|
mit
| 697
|
<?php
namespace AppBundle\Extensions\DataTag;
use AppBundle\Common\ArrayToolkit;
use Biz\Course\Service\CourseService;
use Biz\Course\Service\CourseSetService;
use Biz\Course\Service\MemberService;
use Biz\Task\Service\TaskService;
use Biz\User\Service\UserService;
use Topxia\Service\Common\ServiceKernel;
abstract class CourseBaseDataTag extends BaseDataTag implements DataTag
{
/**
* @return CourseService
*/
protected function getCourseService()
{
return $this->getServiceKernel()->createService('Course:CourseService');
}
/**
* @return CourseSetService
*/
protected function getCourseSetService()
{
return $this->getServiceKernel()->getBiz()->service('Course:CourseSetService');
}
/**
* @return MemberService
*/
protected function getCourseMemberService()
{
return $this->getServiceKernel()->createService('Course:MemberService');
}
/**
* @return UserService
*/
protected function getUserService()
{
return ServiceKernel::instance()->getBiz()->service('User:UserService');
}
/**
* @return TaskService
*/
protected function getTaskService()
{
return $this->getServiceKernel()->createService('Task:TaskService');
}
protected function getCategoryService()
{
return $this->getServiceKernel()->createService('Taxonomy:CategoryService');
}
protected function getThreadService()
{
return $this->getServiceKernel()->createService('Course:ThreadService');
}
protected function getReviewService()
{
return $this->getServiceKernel()->createService('Course:ReviewService');
}
protected function getActivityService()
{
return $this->getServiceKernel()->createService('Activity:ActivityService');
}
protected function checkUserId(array $arguments)
{
if (empty($arguments['userId'])) {
throw new \InvalidArgumentException($this->getServiceKernel()->trans('userId参数缺失'));
}
}
protected function checkCategoryId(array $arguments)
{
if (empty($arguments['categoryId'])) {
throw new \InvalidArgumentException($this->getServiceKernel()->trans('categoryId参数缺失'));
}
}
protected function checkCount(array $arguments)
{
if (empty($arguments['count'])) {
throw new \InvalidArgumentException($this->getServiceKernel()->trans('count参数缺失'));
}
if ($arguments['count'] > 100) {
throw new \InvalidArgumentException($this->getServiceKernel()->trans('count参数超出最大取值范围'));
}
}
protected function checkCourseId(array $arguments)
{
if (empty($arguments['courseId'])) {
throw new \InvalidArgumentException($this->getServiceKernel()->trans('courseId参数缺失'));
}
}
protected function checkCourseArguments(array $arguments)
{
if (empty($arguments['courseId'])) {
$conditions = array();
} else {
$conditions = array('courseId' => $arguments['courseId']);
}
return $conditions;
}
protected function checkThreadId(array $arguments)
{
if (empty($arguments['threadId'])) {
throw new \InvalidArgumentException($this->getServiceKernel()->trans('threadId参数缺失'));
}
}
protected function checkReviewId(array $arguments)
{
if (empty($arguments['reviewId'])) {
throw new \InvalidArgumentException($this->getServiceKernel()->trans('reviewId参数缺失'));
}
}
protected function checkGroupId(array $arguments)
{
if (empty($arguments['group'])) {
throw new \InvalidArgumentException($this->getServiceKernel()->trans('group参数缺失'));
}
}
protected function checkLessonId(array $arguments)
{
if (empty($arguments['lessonId'])) {
throw new \InvalidArgumentException($this->getServiceKernel()->trans('lessonId参数缺失'));
}
}
protected function fillCourseSetTeachersAndCategoriesAttribute(array $courseSets)
{
$userIds = array();
$categoryIds = array();
foreach ($courseSets as &$set) {
if (!empty($set['teacherIds'])) {
$userIds = array_merge($userIds, $set['teacherIds']);
}
$categoryIds[] = $set['categoryId'];
}
$users = $this->getUserService()->findUsersByIds($userIds);
$profiles = $this->getUserService()->findUserProfilesByIds($userIds);
foreach ($users as $key => $user) {
if ($user['id'] == $profiles[$user['id']]['id']) {
$users[$key]['profile'] = $profiles[$user['id']];
}
}
$categories = $this->getCategoryService()->findCategoriesByIds($categoryIds);
foreach ($courseSets as &$set) {
$categoryId = $set['categoryId'];
if ($categoryId != 0 && array_key_exists($categoryId, $categories)) {
$set['category'] = $categories[$categoryId];
}
$teachers = array();
if (empty($set['teacherIds'])) {
continue;
}
foreach ($set['teacherIds'] as $teacherId) {
if (!$teacherId) {
continue;
}
$user = $users[$teacherId];
unset($user['password']);
unset($user['salt']);
$teachers[] = $user;
}
$set['teachers'] = $teachers;
unset($set['teacherIds']);
}
$courseSets = $this->fillCourseTryLookVideo($courseSets);
return $courseSets;
}
protected function getCourseTeachersAndCategories($courses)
{
$userIds = array();
$categoryIds = array();
foreach ($courses as $course) {
$userIds = array_merge($userIds, $course['teacherIds']);
//$categoryIds[] = $course['categoryId'];
}
$users = $this->getUserService()->findUsersByIds($userIds);
$profiles = $this->getUserService()->findUserProfilesByIds($userIds);
foreach ($users as $key => $user) {
if ($user['id'] == $profiles[$user['id']]['id']) {
$users[$key]['profile'] = $profiles[$user['id']];
}
}
$categories = $this->getCategoryService()->findCategoriesByIds($categoryIds);
foreach ($courses as &$course) {
$teachers = array();
foreach ($course['teacherIds'] as $teacherId) {
if (!$teacherId) {
continue;
}
$user = $users[$teacherId];
unset($user['password']);
unset($user['salt']);
$teachers[] = $user;
}
$course['teachers'] = $teachers;
$categoryId = $course['categoryId'];
if ($categoryId != 0 && array_key_exists($categoryId, $categories)) {
$course['category'] = $categories[$categoryId];
}
}
return $courses;
}
protected function getCoursesAndUsers($courseRelations)
{
$userIds = array();
$courseIds = array();
foreach ($courseRelations as &$courseRelation) {
$userIds[] = $courseRelation['userId'];
$courseIds[] = $courseRelation['courseId'];
}
$users = $this->getUserService()->findUsersByIds($userIds);
$courses = $this->getCourseService()->findCoursesByIds($courseIds);
foreach ($courseRelations as &$courseRelation) {
$userId = $courseRelation['userId'];
$user = $users[$userId];
unset($user['password']);
unset($user['salt']);
$courseRelation['User'] = $user;
$courseId = $courseRelation['courseId'];
$course = $courses[$courseId];
$courseRelation['course'] = $course;
}
return $courseRelations;
}
protected function unsetUserPasswords($users)
{
foreach ($users as &$user) {
unset($user['password']);
unset($user['salt']);
}
return $users;
}
protected function fillCourseTryLookVideo($courseSets)
{
$courses = $this->getCourseService()->findCoursesByCourseSetIds(ArrayToolkit::column($courseSets, 'id'));
if (!empty($courses)) {
$tryLookAbleCourses = array_filter($courses, function ($course) {
return !empty($course['tryLookable']) && $course['status'] === 'published';
});
$tryLookAbleCourseIds = ArrayToolkit::column($tryLookAbleCourses, 'id');
$activities = $this->getActivityService()->findActivitySupportVideoTryLook($tryLookAbleCourseIds);
$activityIds = ArrayToolkit::column($activities, 'id');
$tasks = $this->getTaskService()->findTasksByActivityIds($activityIds);
$tasks = ArrayToolkit::index($tasks, 'activityId');
$activities = array_filter($activities, function ($activity) use ($tasks) {
return $tasks[$activity['id']]['status'] === 'published';
});
//返回有云视频任务的课程
$activities = ArrayToolkit::index($activities, 'fromCourseId');
foreach ($courses as &$course) {
if (!empty($activities[$course['id']])) {
$course['tryLookVideo'] = 1;
}
}
unset($course);
}
$tryLookVideoCourses = array_filter($courses, function ($course) {
return !empty($course['tryLookVideo']);
});
$courses = ArrayToolkit::index($courses, 'courseSetId');
$tryLookVideoCourses = ArrayToolkit::index($tryLookVideoCourses, 'courseSetId');
array_walk($courseSets, function (&$courseSet) use ($courses, $tryLookVideoCourses) {
if (isset($tryLookVideoCourses[$courseSet['id']])) {
$courseSet['course'] = $tryLookVideoCourses[$courseSet['id']];
} else {
$courseSet['course'] = $courses[$courseSet['id']];
}
});
return $courseSets;
}
}
|
richtermark/SMEAGOnline
|
src/AppBundle/Extensions/DataTag/CourseBaseDataTag.php
|
PHP
|
mit
| 10,382
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace _01_Problem
{
class StartUp
{
static void Main(string[] args)
{
var n = int.Parse(Console.ReadLine());
var list = new List<Person>();
for (int i = 0; i < n; i++)
{
var line = Console.ReadLine().Split(' ');
var age = int.Parse(line[1]);
var Person = new Person(line[0], age);
if (age > 30)
{
list.Add(Person);
}
}
foreach (var item in list.OrderBy(i => i.Name))
{
Console.WriteLine($"{item.Name} - {item.Age}");
}
}
}
}
|
vasilchavdarov/SoftUniHomework
|
Defining Classess/01 Problem/StartUp.cs
|
C#
|
mit
| 869
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace _3.CameraView
{
class Program
{
static void Main()
{
int[] array = Console.ReadLine().Split().Select(int.Parse).ToArray();
int skip = array[0];
int take = array[1];
string text = Console.ReadLine();
string pattern = "\\|<(\\w{" + skip + "})(\\w{0," + take + "})";
MatchCollection views = Regex.Matches(text, pattern);
List<string> results = new List<string>();
foreach (Match view in views)
{
results.Add(view.Groups[2].Value);
}
Console.WriteLine(String.Join(", ", results));
}
}
}
|
spacex13/SoftUni-Homework
|
RegEx-Exercises/3.CameraView/Program.cs
|
C#
|
mit
| 788
|
#!/bin/bash
#####################################
# Chef Client Downloader
# Ryan Moon
# Created 08/29/16
# Version 0.0.1 on 08/29/16
#####################################
# CURRENTLY REQUIRES WGET
#####################################
# This script iterates thru two arrays
# chef_versions and os_versions, to
# download specific chef-client versions.
# The DMG is mounted, the PKG is copied,
# then the DMG is removed.
# Currently I'm only testing 12.8.1-1 and
# 12.13.37-1 in OS 10.9, 10.10, and 10.11
# You can uncomment the ones you'd prefer
# using.
# On success you will see chef-$version_number-1.pkg in
# the chef_client_versions/$os_version_number
#####################################
main(){
chef_versions=(
12.8.1
# 12.9.38
# 12.9.41
# 12.10.24
# 12.11.18
# 12.12.15
# 12.13.30
12.13.37
)
os_versions=(
10.11
10.10
10.9
)
for ((i=0; i<${#chef_versions[@]}; i++)); do
for ((f=0; f<${#os_versions[@]}; f++)); do
if [[ ! -f ../chef_client_versions/${os_versions[$f]}/chef-${chef_versions[$i]}-1.pkg ]]; then
echo "Downloading -- MacOS ${os_versions[$f]} - Chef ${chef_versions[$i]}"
/usr/local/bin/wget -q https://packages.chef.io/stable/mac_os_x/${os_versions[$f]}/chef-${chef_versions[$i]}-1.dmg -O ../chef_client_versions/${os_versions[$f]}/chef-${chef_versions[$i]}-1.dmg
/usr/bin/hdiutil mount ../chef_client_versions/${os_versions[$f]}/chef-${chef_versions[$i]}-1.dmg -quiet
cp -r /Volumes/Chef\ Client/chef-${chef_versions[$i]}-1.pkg ../chef_client_versions/${os_versions[$f]}/chef-${chef_versions[$i]}-1.pkg
hdiutil unmount /Volumes/Chef\ Client -quiet
rm -rf ../chef_client_versions/${os_versions[$f]}/chef-${chef_versions[$i]}-1.dmg
echo "Finished -- OS ${os_versions[$f]} - Chef ${chef_versions[$i]}"
else
echo "MacOS ${os_versions[$f]} - Chef ${chef_versions[$i]}-1.pkg already exists."
fi
done
done
}
# Script
main "$@"
|
ryanmoon/at-action-park
|
scripts/chef-downloader.sh
|
Shell
|
mit
| 1,969
|
package com.sleep.soko;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import com.badlogic.gdx.math.Vector2;
import com.sleep.Constants;
import com.sleep.Entity;
public class CollisionGrid {
private Entity[][] collisionGrid;
public int[][] ghostPathGrid;
public int[][] spectrePathGrid;
private int columns, rows;
public Entity player;
public int columnCount() {
return columns;
}
public int rowCount() {
return rows;
}
public CollisionGrid(SokoLevelParser parser) {
collisionGrid = parser.getGrid();
ghostPathGrid = parser.getGhostPathGrid();
spectrePathGrid = parser.getSpectrePathGrid();
columns = parser.getColumns();
rows = parser.getRows();
player = parser.getPlayer();
}
public Vector2 getGridPos(float x, float y) {
int gridX = (int) x / Constants.GRID_CELL_SIZE;
int gridY = (int) y / Constants.GRID_CELL_SIZE;
return new Vector2(gridX, gridY);
}
public Entity getEntityAt(float x, float y) {
Vector2 floorGridPos = getGridPos(x, y);
if (floorGridPos.x < 0 || floorGridPos.y < 0 || floorGridPos.x >= columns || floorGridPos.y >= rows) {
return null;
} else {
return collisionGrid[(int) floorGridPos.x][(int) floorGridPos.y];
}
}
/**
* puts an entity on the grid at the given render position
*/
public Entity setEntityAt(Entity e, float x, float y) {
Vector2 gridPos = getGridPos(x, y);
if (gridPos.x < 0 || gridPos.y < 0 || gridPos.x >= columns || gridPos.y >= rows)
return null;
else
return collisionGrid[(int) gridPos.x][(int) gridPos.y] = e;
}
public void removeEntity(Entity e) {
Vector2 gridPos = getGridPos(e.position.x, e.position.y);
if (collisionGrid[(int) gridPos.x][(int) gridPos.y] == e) {
collisionGrid[(int) gridPos.x][(int) gridPos.y] = null;
}
}
public Entity moveEntityTo(Entity e, float x, float y) {
removeEntity(e);
return setEntityAt(e, x, y);
}
/**
* BFS search through the grid orthogonally, marking the distance in moves
* from any position to the player's position.
*
* -2 == not visited
* -1 == visited but unreachable
* >= 0 == visited and reachable
*/
void updateGhostPathGrid() {
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
ghostPathGrid[x][y] = -2;
}
}
int xPlayer = (int) player.position.x / Constants.GRID_CELL_SIZE;
int yPlayer = (int) player.position.y / Constants.GRID_CELL_SIZE;
Vector2 playerPos = new Vector2(xPlayer, yPlayer);
ghostPathGrid[xPlayer][yPlayer] = 0;
LinkedList<Vector2> queue = new LinkedList<Vector2>();
Vector2[] moves = new Vector2[4];
queue.add(playerPos);
while (!queue.isEmpty()) {
Vector2 currentPos = queue.poll();
moves[0] = new Vector2(currentPos.x - 1, currentPos.y);
moves[1] = new Vector2(currentPos.x + 1, currentPos.y);
moves[2] = new Vector2(currentPos.x, currentPos.y - 1);
moves[3] = new Vector2(currentPos.x, currentPos.y + 1);
for (Vector2 move : moves) {
if (move.x >= 0 && move.x < columns && move.y >= 0 && move.y < rows) {
if (ghostPathGrid[(int) move.x][(int) move.y] == -2) {
if (collisionGrid[(int) move.x][(int) move.y] == null) {
ghostPathGrid[(int) move.x][(int) move.y] = ghostPathGrid[(int) currentPos.x][(int) currentPos.y] + 1;
queue.add(move);
} else {
ghostPathGrid[(int) move.x][(int) move.y] = -1;
}
}
}
}
}
}
/**
* Works similarily to updateGhostPathGrid(), but searches through the grid
* diagonally rather than horizontally/vertically.
*
* The BFS searches from up to 5 initial positions: the player's position,
* and any adjacent available (unoccupied) orthogonal position.
*/
void updateSpectrePathGrid() {
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
spectrePathGrid[x][y] = -2;
}
}
int xPlayer = (int) player.position.x / Constants.GRID_CELL_SIZE;
int yPlayer = (int) player.position.y / Constants.GRID_CELL_SIZE;
List<Vector2> startingPositions = new ArrayList<Vector2>();
startingPositions.add(new Vector2(xPlayer, yPlayer));
spectrePathGrid[xPlayer][yPlayer] = 0;
if (collisionGrid[xPlayer - 1][yPlayer] == null) {
startingPositions.add(new Vector2(xPlayer - 1, yPlayer));
spectrePathGrid[xPlayer - 1][yPlayer] = 1;
}
if (collisionGrid[xPlayer + 1][yPlayer] == null) {
startingPositions.add(new Vector2(xPlayer + 1, yPlayer));
spectrePathGrid[xPlayer + 1][yPlayer] = 1;
}
if (collisionGrid[xPlayer][yPlayer - 1] == null) {
startingPositions.add(new Vector2(xPlayer, yPlayer - 1));
spectrePathGrid[xPlayer][yPlayer - 1] = 1;
}
if (collisionGrid[xPlayer][yPlayer + 1] == null) {
startingPositions.add(new Vector2(xPlayer, yPlayer + 1));
spectrePathGrid[xPlayer][yPlayer + 1] = 1;
}
for (Vector2 startingPos : startingPositions) {
LinkedList<Vector2> queue = new LinkedList<Vector2>();
Vector2[] moves = new Vector2[4];
queue.add(startingPos);
while (!queue.isEmpty()) {
Vector2 currentPos = queue.poll();
moves[0] = new Vector2(currentPos.x - 1, currentPos.y - 1);
moves[1] = new Vector2(currentPos.x - 1, currentPos.y + 1);
moves[2] = new Vector2(currentPos.x + 1, currentPos.y - 1);
moves[3] = new Vector2(currentPos.x + 1, currentPos.y + 1);
for (Vector2 move : moves) {
if (move.x >= 0 && move.x < columns && move.y >= 0 && move.y < rows) {
if (spectrePathGrid[(int) move.x][(int) move.y] == -2
|| spectrePathGrid[(int) move.x][(int) move.y] > spectrePathGrid[(int) currentPos.x][(int) currentPos.y] + 2) {
if (collisionGrid[(int) move.x][(int) move.y] == null) {
spectrePathGrid[(int) move.x][(int) move.y] = spectrePathGrid[(int) currentPos.x][(int) currentPos.y] + 2;
queue.add(move);
} else {
spectrePathGrid[(int) move.x][(int) move.y] = -1;
}
}
}
}
}
}
}
public int getPathDistance(int[][] pathGrid, int x, int y) {
return pathGrid[x][y];
}
/**
* calculates manhattan distance from position to player
*
* if position is occupied by an entity, return a number smaller than 0
* (-2).
*/
public int manhattanDistance(int x, int y) {
if (collisionGrid[x][y] != null)
return -2;
Vector2 playerGridPos = getGridPos(player.position.x, player.position.y);
return Math.abs((int) playerGridPos.x - x) + Math.abs((int) playerGridPos.y - y);
}
private void printGrid(int[][] distanceGrid) {
System.out.println("distance grid: ");
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
System.out.print(distanceGrid[x][y] + "\t");
}
System.out.println();
}
}
private void printGrid(char[][] distanceGrid) {
System.out.println("distance grid: ");
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
System.out.print(distanceGrid[x][y]);
}
System.out.println();
}
}
private void printGrid() {
for (int i = 0; i < 5; i++) {
System.out.println();
}
System.out.println("grid: ");
for (int y = 0; y < rows; y++) {
for (int x = 0; x < columns; x++) {
if (collisionGrid[x][y] == null) {
System.out.print(" ");
} else if (collisionGrid[x][y].getName().equals("Player")) {
System.out.print(Constants.PLAYER);
} else if (collisionGrid[x][y].getName().equals("Wall")) {
System.out.print(Constants.WALL);
} else if (collisionGrid[x][y].getName().equals("Box")) {
System.out.print(Constants.BOX);
} else if (collisionGrid[x][y].getName().equals("Ghost")) {
System.out.print(Constants.GHOST);
} else if (collisionGrid[x][y].getName().equals("Spectre")) {
System.out.print(Constants.SPECTRE);
}
// System.out.print("\t");
}
System.out.println();
}
}
}
|
galnegus/sleep
|
src/com/sleep/soko/CollisionGrid.java
|
Java
|
mit
| 7,772
|
//VARIABLES
var currentCountries = [];
var lastbenchrmak = null;
var test = "test";
var measures;
var calculatedBenchmark = null;
var routeJson = null;
// UTILITY FUNCTIONS
// SELECTION
function selectedBenchmarkMenu(menu) {
if (menu == "cbenchmark")
return $('#cbenchmark').val();
if (menu == 'disabledbenchmark')
return $('#disabledbenchmark').val();
if (menu == 'tempbenchmark')
return $('#tempbenchmark').val();
}
function selectedBenchmark() {
if ($.isEmptyObject(selectedBenchmarkMenu("cbenchmark")))
return selectedBenchmarkMenu("disabledbenchmark");
else
return selectedBenchmarkMenu("cbenchmark");
}
function loading() {
$('#loading_button').button('loading')
disableInput();
}
function loaded() {
$('#loading_button').button('reset')
enableInput();
}
function customer() {
return $('#customers').val();
}
function country() {
return $('#country').val();
}
function day() {
return $('#day').val();
}
// INPUT
function disableInput() {
$("#day").multiselect('disable')
$("#country").multiselect('disable')
$("#customers").multiselect('disable')
$("#benchmarks").multiselect('disable')
$('.todisable').prop('disabled', true);
}
function enableInput() {
$("#day").multiselect('enable')
$("#country").multiselect('enable')
$("#customers").multiselect('enable')
$("#benchmarks").multiselect('enable')
$('.todisable').prop('disabled', false);
}
function initBenchmarkMenus() {
$("#benchmarks").multiselect('dataprovider', []);
}
// GRAPHS
function noPlot() {
$('#graph').highcharts({
title : {
text : 'No data in line chart'
},
series : [ {
type : 'line',
name : 'Random data',
data : []
} ],
lang : {},
/* Custom options */
noData : {
position : {},
attr : {},
style : {}
}
});
}
function plot(jdata, country, customer, graph, day, id, suffix) {
var suffix = "";
if (graph == 'ACDA' || graph == 'ACDV') {
suffix = " Seconds";
} else if (graph == 'Buy' || graph == 'Sell') {
suffix = " EUR Cent";
} else if (graph == 'ARSV' || graph == 'GpPercent') {
suffix = "%;"
} else {
suffix = " Minutes";
}
var yserie = [];
$.each(jdata, function(day, graphs) {
var numbers = [];
for ( var g in graphs) {
$.each(graphs[g], function(route, measures) {
numbers = [];
for ( var m in measures) {
var me = measures[m];
numbers.push({
x : me["Hour"],
y : me[graph]
});
}
console.log(route);
yserie.push({
name : customer + " " + country + " day " + day,
data : numbers
});
});
}
yserie.sort(function(a, b) {
return a.x - b.x
});
});
$('#' + id).highcharts({
chart : {
borderColor : '#2f7ed8',
borderWidth : 3,
type : 'line'
},
title : {
text : 'Daily ' + id,
x : -20
},
subtitle : {
text : 'Source: Golem srl',
x : -20
},
xAxis : {
categories : [ '0', '1', '2' ]
},
yAxis : {
title : {
text : id
},
plotLines : [ {
value : 0,
width : 1,
color : '#808080'
} ]
},
plotOptions : {
line : {
dataLabels : {
enabled : false,
style : {
textShadow : '0 0 3px white, 0 0 3px white'
}
},
enableMouseTracking : true
}
},
tooltip : {
valueDecimals : 5,
valueSuffix : suffix
},
series : yserie,
noData : {
// Custom positioning/aligning options
position : {},
attr : {},
style : {}
}
});
};
function multiplot(jdata, country, customer, graph, day) {
plot(jdata, country, customer, graph, day, 'graph');
plot(jdata, country, customer, 'Minutes', day, 'minutes');
plot(jdata, country, customer, 'Revenue', day, 'revenue');
plot(jdata, country, customer, 'ACDV', day, 'acdv');
plot(jdata, country, customer, 'ARSV', day, 'arsv');
}
function benchmarkPlot(benchmark, graph, html) {
console.log(benchmark)
if (graph != "Multiplot") {
var chart = $('#' + html).highcharts();
var serie = [];
for ( var m in benchmark) {
var me = benchmark[m];
serie.push({
x : me["Hour"],
y : me[graph]
});
}
serie.sort(function(a, b) {
return a.x - b.x
});
chart.addSeries({
name : "benchmark",
data : serie
});
} else {
benchmarkPlot(benchmark, 'Minutes', 'minutes')
benchmarkPlot(benchmark, 'Revenue', 'revenue')
benchmarkPlot(benchmark, 'ACDV', 'acdv')
benchmarkPlot(benchmark, 'ARSV', 'arsv')
}
}
// CALLS
function bcall(country, customer) {
var servlet = "/benchmark";
var call = "?list=true&country=" + country + "&customer=" + customer;
var options_active = [];
var options_disabled = [];
initBenchmarkMenus();
console.log(call);
$.getJSON(servlet + call, function(json) {
setTimeout(function() {
$.each(json["active_opt"], function(index, name) {
options_active.push({
label : name,
value : name
});
});
$.each(json["disabled_opt"], function(index, name) {
options_disabled.push({
label : name,
value : name
});
});
console.log(options_active)
console.log(options_disabled)
$.each(json["toplot"], function(index, benchmark) {
benchmarkPlot(benchmark['measures'], $('#sampleTabs>.active')
.text(), 'graph');
});
$("#benchmarks").multiselect('dataprovider', options_active);
$("#benchmakr_scope").multiselect('dataprovider', options_active);
$("#benchmakr_scope").multiselect('dataprovider', options_disabled);
$("#benchmarks").multiselect('dataprovider', options_disabled);
}, 2000);
});
}
function gcall(country, customer, graph, day) {
var servlet = 'graph';
var call = '?day=' + day + '&country=' + country + '&customer=' + customer;
console.log(call);
if (measures != null) {
multiplot(measures, country, customer, graph, day);
} else {
$.getJSON(servlet + call, function(jdata) {
console.log(jdata);
if (jQuery.isEmptyObject(jdata) || jdata["message"] != null) {
console.log(jdata["message"]);
noPlot();
} else {
measures = jdata;
multiplot(jdata, country, customer, graph, day);
}
});
}
};
// BUTTONS
function changeButtonText(id, val) {
$('#' + id).html(val)
};
// ALERTING-CALLS
function markAsRead(id, button) {
$.ajax({
url : "/alert?id=" + id,
type : 'GET',
success : function() {
$(button).parent().parent().parent().remove();
}
});
};
// USERS-CALLS
function makeAdmin(id, button) {
$.ajax({
url : "/user?admin=true&id=" + id,
type : 'POST',
success : function() {
$(button).parent().parent().parent().remove();
setTimeout(function() {
location.reload();
}, 0001);
}
});
};
function makeUser(id, button) {
$.ajax({
url : "/user?admin=false&id=" + id,
type : 'POST',
success : function() {
$(button).parent().parent().parent().remove();
setTimeout(function() {
location.reload();
}, 0001);
}
});
};
function upgrade(id, button) {
$.ajax({
url : "/user?up=true&id=" + id,
type : 'POST',
success : function() {
$(button).parent().parent().parent().remove();
setTimeout(function() {
location.reload();
}, 0001);
}
});
}
function downgrade(id, button) {
$.ajax({
url : "/user?down=true&id=" + id,
type : 'POST',
success : function() {
$(button).parent().parent().parent().remove();
setTimeout(function() {
location.reload();
}, 0001);
}
});
}
// ACTIONS
$(function() {
$('#savebutton').click(function() {
$.ajax({
url : "/sliding?customer=" + customer() + "&country=" + country(),
type : 'POST',
success : function() {
setTimeout(function() {
bcall(country(), customer());
}, 1000);
}
});
calculatedBenchmark = null;
});
$('#calcbutton').click(
function() {
var servlet = "/sliding"
var graph = $("ul#sampleTabs li.active").text();
var call = "?day=" + day() + "&customer=" + customer()
+ "&country=" + country();
console.log(call)
if (day() != null && customer() != null && country() != null) {
$.getJSON(servlet + call, function(json) {
if (!$.isEmptyObject(json)) {
calculatedBenchmark = json;
benchmarkPlot(calculatedBenchmark, $(
'#sampleTabs>.active').text(), 'graph');
} else {
console.log("No local benchmark");
alert("No local benchmark, press calculate");
}
});
}
});
});
// SELECT_MENU
$(function() {
$('#day').change(function() {
var days = [];
days.push($(this).val());
if (days == "0,1")
days = [ "0", "1" ];
if ($.isEmptyObject(day()))
return;
var call = '/routes?days=' + days
console.log(call)
loading();
$.getJSON(call, function(j) {
routeJson = j;
var options = [ {
label : "None Selected",
value : "none"
} ];
var optionsCheck = [];
$.each(days, function(index, d) {
for (var i = 0; i < j.length; i++) {
if (j[i].day == d) {
if ($.inArray(j[i].customer, optionsCheck) == -1) {
optionsCheck.push(j[i].customer);
options.push({
label : j[i].customer,
value : j[i].customer
})
}
}
}
});
setTimeout(function() {
$("#customers").multiselect('dataprovider', options)
loaded();
}, 005);
}
);
});
$('#customers')
.change(
function() {
loading();
if ($.isEmptyObject(customer()))
return;
if (routeJson == null) {
$.getJSON('/routes?days=' + $('#day').val(),
function(j) {
routeJson = j;
var options = '';
j.sort(function(ja, jb) {
return ja.order - jb.order
});
for (var i = 0; i < j.length; i++) {
options.push({
label : routeJson[i].country,
value : routeJson[i].country
})
}
});
} else {
var options = [];
var optionsUnique = [];
options.push({
label : "None Selected",
value : "none"
})
var days = [];
days.push($('#day').val());
if (days == "0,1")
days = [ "0", "1" ];
routeJson.sort(function(ja, jb) {
return ja.order - jb.order
});
for (var i = 0; i < routeJson.length; i++) {
$
.each(
days,
function(index, d) {
if (routeJson[i].day == d
&& routeJson[i].customer == customer()
&& (optionsUnique
.indexOf(routeJson[i].country) == -1)) {
currentCountries
.push(routeJson[i].country);
optionsUnique
.push(routeJson[i].country);
options
.push({
label : routeJson[i].country,
value : routeJson[i].country
})
}
});
}
}
setTimeout(function() {
$("#country").multiselect('dataprovider', options);
loaded();
}, 001);
});
$('#country').change(
function() {
loading();
measures = null;
if (country() != null && customer() != null && day() != null) {
setTimeout(function() {
gcall(country(), customer(), $('#sampleTabs>.active')
.text(), day());
bcall(country(), customer());
loaded();
}, 001);
}
});
$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function(e) {
var action = $('#sampleTabs>.active').text();
if (action == "Benchmark") {
} else if (country() != null && customer() != null && day() != null) {
gcall(country(), customer(), action, day());
bcall(country(), customer());
}
});
$('#benchmarks').change(
function() {
measures = null;
var servlet = "/benchmark";
var benchmark = $(this).val();
var call = "?benchmark=" + benchmark + "&list=false";
console.log(call)
if (!$.isEmptyObject(benchmark)) {
$.getJSON(servlet + call, function(jsonB) {
console.log(jsonB)
buttonChange(jsonB, $(this).attr('ref'));
benchmarkPlot(jsonB["measures"], $(
'#sampleTabs>.active').text(), 'graph');
});
}
});
});
function buttonChange(jb, ref) {
if (jb["Alwaysplot"])
changeButtonText("alwaysbutton_" + ref, "Always");
else
changeButtonText("alwaysbutton", "OnDemand");
}
function editBenchmark() {
var active = $('#benchmark_active:checked').val();
var alwaysPlot = $('#always_plot:checked').val();
var id = $("#benchmakr_scope").val()
$.ajax({
url : "/benchmark/update?id=" + id + "&activation=" + active
+ "&alwaysplot=" + alwaysPlot,
type : 'POST',
success : function() {
bcall();
}
});
}
function deleteBenchmark() {
var id = $("#benchmakr_scope").val()
console.log(id);
$.ajax({
url : "/benchmark/delete?id=" + id,
type : 'POST',
success : function() {
console.log("deleted "+id)
}
});
}
|
riccardotommasini/GDA
|
war/js/golem-scripts.js
|
JavaScript
|
mit
| 12,711
|
'use strict';
/* istanbul ignore next */
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('hashes', {
h1: {
allowNull: false,
primaryKey: true,
type: Sequelize.STRING(128),
},
s2: {
allowNull: false,
type: Sequelize.STRING(64),
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('hashes');
},
};
|
gabrieltanchen/xpns-api
|
migrations/20180618230743-create-hashes-table.js
|
JavaScript
|
mit
| 451
|
<html>
<head>
<title>Tessa Munt's panel show appearances</title>
<script type="text/javascript" src="../common.js"></script>
<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>
<script type="text/javascript" src="../people.js"></script>
<!--#include virtual="head.txt" -->
</head>
<body>
<!--#include virtual="nav.txt" -->
<div class="page">
<h1>Tessa Munt's panel show appearances</h1>
<p>Tessa Munt (born 1959-10-16<sup><a href="https://en.wikipedia.org/wiki/Tessa_Munt">[ref]</a></sup>) has appeared in <span class="total">3</span> episodes between 2012-2015. <a href="https://en.wikipedia.org/wiki/Tessa_Munt">Tessa Munt on Wikipedia</a>.</p>
<div class="performerholder">
<table class="performer">
<tr style="vertical-align:bottom;">
<td><div style="height:100px;" class="performances female" title="1"></div><span class="year">2012</span></td>
<td><div style="height:0px;" class="performances female" title=""></div><span class="year">2013</span></td>
<td><div style="height:100px;" class="performances female" title="1"></div><span class="year">2014</span></td>
<td><div style="height:100px;" class="performances female" title="1"></div><span class="year">2015</span></td>
</tr>
</table>
</div>
<ol class="episodes">
<li><strong>2015-02-26</strong> / <a href="../shows/question-time.html">Question Time</a></li>
<li><strong>2014-06-12</strong> / <a href="../shows/question-time.html">Question Time</a></li>
<li><strong>2012-11-15</strong> / <a href="../shows/question-time.html">Question Time</a></li>
</ol>
</div>
</body>
</html>
|
slowe/panelshows
|
people/de1s3mno.html
|
HTML
|
mit
| 1,596
|
set(vtktiff_LOADED 1)
set(vtktiff_DEPENDS "vtkjpeg;vtkzlib")
set(vtktiff_LIBRARIES "vtktiff")
set(vtktiff_INCLUDE_DIRS "/home/tim/CMU/SunTracker/IMU/VTK-6.2.0/ThirdParty/tiff")
set(vtktiff_LIBRARY_DIRS "")
set(vtktiff_RUNTIME_LIBRARY_DIRS "/home/tim/CMU/SunTracker/IMU/VTK-6.2.0/lib")
set(vtktiff_WRAP_HIERARCHY_FILE "")
set(vtktiff_EXCLUDE_FROM_WRAPPING 1)
|
timkrentz/SunTracker
|
IMU/VTK-6.2.0/lib/cmake/vtk-6.2/Modules/vtktiff.cmake
|
CMake
|
mit
| 359
|
/*
* Generated by class-dump 3.3.4 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
*/
#import "NSObject.h"
@class PBCodable;
@interface AWDMetricContainer : NSObject
{
PBCodable *_metric;
unsigned int _metricId;
}
@property(readonly, nonatomic) unsigned int metricId; // @synthesize metricId=_metricId;
@property(retain, nonatomic) PBCodable *metric; // @synthesize metric=_metric;
- (void)dealloc;
- (id)initWithMetricId:(unsigned int)arg1;
@end
|
matthewsot/CocoaSharp
|
Headers/PrivateFrameworks/WirelessDiagnostics/AWDMetricContainer.h
|
C
|
mit
| 516
|
package com.caner.mirzabey.kalah.game.data;
import com.caner.mirzabey.kalah.user.User;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Stack;
/**
* Created by ecanmir on 14.06.2016.
*/
public class Side {
public static final int HOUSE_COUNT = 6;
private User owner;
private boolean turnOnMe;
private Stack<Seed> kalah = new Stack<>();
private List<Stack<Seed>> pit = new ArrayList<>(HOUSE_COUNT);
public Side(int seedCount) {
init(seedCount);
}
public Side(User owner, int seedCount) {
init(seedCount);
this.owner = owner;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
private void init(int seedCount) {
for (int i = 1; i <= HOUSE_COUNT; i++) {
Stack<Seed> seeds = new Stack<>();
for (int j = 1; j <= seedCount; j++) {
seeds.push(new Seed((i * 10) + j));
}
pit.add(seeds);
}
}
public void setKalah(Stack<Seed> kalah) {
this.kalah = kalah;
}
public void setPit(List<Stack<Seed>> pit) {
this.pit = pit;
}
public List<Stack<Seed>> getPit() {
return pit;
}
public Stack<Seed> getKalah() {
return kalah;
}
public boolean isTurnOnMe() {
return turnOnMe;
}
public void setTurnOnMe(boolean turnOnMe) {
this.turnOnMe = turnOnMe;
}
@Override
public String toString() {
return "Side{" +
"owner=" + owner +
", turnOnMe=" + turnOnMe +
", kalah=" + kalah +
", pit=" + pit +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Side)) {
return false;
}
Side side = (Side) o;
return isTurnOnMe() == side.isTurnOnMe() &&
Objects.equals(getOwner(), side.getOwner()) &&
Objects.equals(getKalah(), side.getKalah()) &&
Objects.equals(getPit(), side.getPit());
}
@Override
public int hashCode() {
return Objects.hash(getOwner(), isTurnOnMe(), getKalah(), getPit());
}
}
|
canermirzabey/mancala
|
src/main/java/com/caner/mirzabey/kalah/game/data/Side.java
|
Java
|
mit
| 2,348
|
To build and publish a tag:
./release.sh <tag>
If the tag is new, you'll have to create a `build/<tag>.sh` file. Just copying the
second-most-recent tag's build file will probably work.
To build and publish an arbitrary commit:
./release.sh <sha>
This will run the build file of the tag immediately preceding the commit, and will use the
output of `git describe --tags` as the release name.
Of course, if you don't work at [DataPad](http://datapad.io), you'll have to clone this
repo to run these commands (the script will automatically use the right git endpoint). Pull
requests containing new build files welcome.
|
datapad/bower-angular-all
|
README.md
|
Markdown
|
mit
| 630
|
namespace EnumPlusPlus.Tests
{
using System;
using Xunit;
public class IsValidExtensionTests
{
[Fact]
public void IsValidOnInt_NotEnumType_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() =>
{
2.IsValid<LookAlike>();
});
}
[Fact]
public void IsValidOnInt_IsTooLow_ReturnsFalse()
{
Assert.False((-1).IsValid<Color>());
}
[Fact]
public void IsValidOnInt_LowestValue_ReturnsTrue()
{
Assert.True(0.IsValid<Color>());
}
[Fact]
public void IsValidOnInt_IsValid_ReturnsTrue()
{
Assert.True(2.IsValid<Color>());
}
[Fact]
public void IsValidOnInt_HighestValue_ReturnsTrue()
{
Assert.True(7.IsValid<Color>());
}
[Fact]
public void IsValidOnInt_IsTooHigh_ReturnsFalse()
{
Assert.False(8.IsValid<Color>());
}
[Fact]
public void IsValidOnIntOutResult_NotEnumType_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() =>
{
LookAlike result;
2.IsValid(out result);
});
}
[Fact]
public void IsValidOnIntOutResult_IsTooLow_ReturnsFalse()
{
Color result;
Assert.False((-1).IsValid(out result));
}
[Fact]
public void IsValidOnIntOutResult_LowestValue_ReturnsTrue()
{
Color result;
Assert.True(0.IsValid(out result));
}
[Fact]
public void IsValidOnIntOutResult_IsValid_ReturnsTrue()
{
Color result;
Assert.True(2.IsValid(out result));
}
[Fact]
public void IsValidOnIntOutResult_HighestValue_ReturnsTrue()
{
Color result;
Assert.True(7.IsValid(out result));
}
[Fact]
public void IsValidOnIntOutResult_IsTooHigh_ReturnsFalse()
{
Color result;
Assert.False(8.IsValid(out result));
}
[Fact]
public void IsValidOnIntOutResult_IsTooLow_OutsDefault()
{
Color result;
(-1).IsValid(out result);
Assert.Equal(default(Color), result);
}
[Fact]
public void IsValidOnIntOutResult_LowestValue_OutsBlack()
{
Color result;
0.IsValid(out result);
Assert.Equal(Color.Black, result);
}
[Fact]
public void IsValidOnIntOutResult_IsValid_OutsGreen()
{
Color result;
2.IsValid(out result);
Assert.Equal(Color.Green, result);
}
[Fact]
public void IsValidOnIntOutResult_HighestValue_OutsWhite()
{
Color result;
7.IsValid(out result);
Assert.Equal(Color.White, result);
}
[Fact]
public void IsValidOnIntOutResult_IsTooHigh_OutsDefault()
{
Color result;
8.IsValid(out result);
Assert.Equal(default(Color), result);
}
[Fact]
public void IsValidOnIntWithFlagsEnum_ValueNegative1_ReturnsFalse()
{
Assert.False((-1).IsValid<Colors>());
}
[Fact]
public void IsValidOnIntWithFlagsEnum_Value0_ReturnsTrue()
{
Assert.True(0.IsValid<Colors>());
}
[Fact]
public void IsValidOnIntWithFlagsEnum_Value2_ReturnsTrue()
{
Assert.True(2.IsValid<Colors>());
}
[Fact]
public void IsValidOnIntWithFlagsEnum_Value6_ReturnsTrue()
{
Assert.True(6.IsValid<Colors>());
}
[Fact]
public void IsValidOnIntWithFlagsEnum_Value7_ReturnsTrue()
{
Assert.True(7.IsValid<Colors>());
}
[Fact]
public void IsValidOnIntWithFlagsEnum_Value8_ReturnsFalse()
{
Assert.False(8.IsValid<Colors>());
}
[Fact]
public void IsValidOnIntWithFlagsEnum_ValueNegative1_OutsDefault()
{
Colors result;
(-1).IsValid(out result);
Assert.Equal(default(Colors), result);
}
[Fact]
public void IsValidOnIntWithFlagsEnum_Value0_OutsBlack()
{
Colors result;
0.IsValid(out result);
Assert.Equal(Colors.Black, result);
}
[Fact]
public void IsValidOnIntWithFlagsEnum_Value1_OutsRed()
{
Colors result;
1.IsValid(out result);
Assert.Equal(Colors.Red, result);
}
[Fact]
public void IsValidOnIntWithFlagsEnum_Value2_OutsGreen()
{
Colors result;
2.IsValid(out result);
Assert.Equal(Colors.Green, result);
}
[Fact]
public void IsValidOnIntWithFlagsEnum_Value3_OutsRedGreen()
{
Colors result;
3.IsValid(out result);
Assert.Equal(Colors.Red | Colors.Green, result);
}
[Fact]
public void IsValidOnIntWithFlagsEnum_Value4_OutsBlue()
{
Colors result;
4.IsValid(out result);
Assert.Equal(Colors.Blue, result);
}
[Fact]
public void IsValidOnIntWithFlagsEnum_Value5_OutsRedBlue()
{
Colors result;
5.IsValid(out result);
Assert.Equal(Colors.Red | Colors.Blue, result);
}
[Fact]
public void IsValidOnIntWithFlagsEnum_Value6_OutsGreenBlue()
{
Colors result;
6.IsValid(out result);
Assert.Equal(Colors.Green | Colors.Blue, result);
}
[Fact]
public void IsValidOnIntWithFlagsEnum_Value7_OutsRedGreenBlue()
{
Colors result;
7.IsValid(out result);
Assert.Equal(Colors.Red | Colors.Green | Colors.Blue, result);
}
[Fact]
public void IsValidOnIntWithFlagsEnum_Value8_OutsDefault()
{
Colors result;
8.IsValid(out result);
Assert.Equal(default(Colors), result);
}
[Fact]
public void IsValidOnIntWithFlagsEnum_Value9_ReturnsFalse()
{
Assert.False(9.IsValid<Colors>());
}
[Fact]
public void IsValidOnIntWithFlagsEnum_Value9_OutsDefault()
{
Colors result;
9.IsValid(out result);
Assert.Equal(default(Colors), result);
}
}
}
|
boriseetgerink/EnumPlusPlus
|
src/EnumPlusPlus.Tests/IsValidExtensionTests.cs
|
C#
|
mit
| 6,746
|
<?php
namespace Elektra\SeedBundle\Entity\Companies;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="Elektra\SeedBundle\Repository\Companies\CompanyPersonRepository")
* @ORM\Table("persons_company")
*
* @ORM\HasLifecycleCallbacks()
*
* Unique: nothing
*/
class CompanyPerson extends Person
{
/**
* @var CompanyLocation
*
* @ORM\ManyToOne(targetEntity="Elektra\SeedBundle\Entity\Companies\CompanyLocation", inversedBy="persons",
* fetch="EXTRA_LAZY")
* @ORM\JoinColumn(name="locationId", referencedColumnName="locationId")
*
*/
protected $location;
/**
* @var bool
*
* @ORM\Column(type="boolean")
*/
protected $isPrimary;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
}
/*************************************************************************
* Getters / Setters
*************************************************************************/
/**
* @param CompanyLocation $location
*/
public function setLocation($location)
{
$this->location = $location;
}
/**
* @return CompanyLocation
*/
public function getLocation()
{
return $this->location;
}
/**
* @param bool $isPrimary
*/
public function setIsPrimary($isPrimary)
{
$this->isPrimary = $isPrimary;
}
/**
* @return bool
*/
public function getIsPrimary()
{
return $this->isPrimary;
}
/*************************************************************************
* EntityInterface
*************************************************************************/
// nothing
/*************************************************************************
* Lifecycle callbacks
*************************************************************************/
// none
}
|
feichler/CESU
|
src/Elektra/SeedBundle/Entity/Companies/CompanyPerson.php
|
PHP
|
mit
| 1,962
|
import React from 'react';
import { assert } from 'chai';
import {
createMount,
createShallow,
describeConformance,
getClasses,
} from '@material-ui/core/test-utils';
import DialogTitle from './DialogTitle';
describe('<DialogTitle />', () => {
let mount;
let shallow;
let classes;
before(() => {
mount = createMount({ strict: true });
shallow = createShallow({ dive: true });
classes = getClasses(<DialogTitle>foo</DialogTitle>);
});
after(() => {
mount.cleanUp();
});
describeConformance(<DialogTitle>foo</DialogTitle>, () => ({
classes,
inheritComponent: 'div',
mount,
refInstanceof: window.HTMLDivElement,
skip: ['componentProp'],
}));
it('should render JSX children', () => {
const children = <p className="test">Hello</p>;
const wrapper = shallow(<DialogTitle disableTypography>{children}</DialogTitle>);
assert.strictEqual(wrapper.childAt(0).equals(children), true);
});
it('should render string children as given string', () => {
const children = 'Hello';
const wrapper = shallow(<DialogTitle>{children}</DialogTitle>);
assert.strictEqual(wrapper.childAt(0).props().children, children);
});
});
|
allanalexandre/material-ui
|
packages/material-ui/src/DialogTitle/DialogTitle.test.js
|
JavaScript
|
mit
| 1,202
|
import {RootState} from '../reducers/rootReducer'
export const selectBackend = (state: RootState) => state.backend
|
hwaterke/sec
|
frontend/src/redux/selectors/backend.ts
|
TypeScript
|
mit
| 116
|
var a = require('./a');
exports.value = 3;
|
RReverser/grunt-pure-cjs
|
test/fixtures/c.js
|
JavaScript
|
mit
| 42
|
#include "Snap.h"
#include "path.h"
#include "io.h"
#include "dlink.h"
#include "shortest_path.h"
#include "multiclass.h"
int main()
{
std::string m_file_folder = "../../data/input_files_6by6grid_multiclass";
// std::string m_file_folder = "../../data/input_files_7link_fix";
// std::string m_file_folder = "../../data/input_files_philly";
// std::string m_file_folder = "../../data/input_files_SR41_fix";
// std::string m_file_folder = "../../data/input_files_MckeesRocks_SPC";
// std::string m_file_folder = "/home/lemma/Documents/truck/Final data for DPFE/tmp_truck";
MNM_ConfReader *m_config;
MNM_Node_Factory *m_node_factory;
MNM_Link_Factory *m_link_factory;
MNM_OD_Factory *m_od_factory;
PNEGraph m_graph;
printf("1\n");
m_node_factory = new MNM_Node_Factory_Multiclass();
m_link_factory = new MNM_Link_Factory_Multiclass();
m_od_factory = new MNM_OD_Factory_Multiclass();
m_config = new MNM_ConfReader(m_file_folder + "/config.conf", "DTA");
MNM_IO_Multiclass::build_node_factory_multiclass(m_file_folder, m_config, m_node_factory);
MNM_IO_Multiclass::build_link_factory_multiclass(m_file_folder, m_config, m_link_factory);
MNM_IO_Multiclass::build_od_factory(m_file_folder, m_config, m_od_factory, m_node_factory);
m_graph = MNM_IO_Multiclass::build_graph(m_file_folder, m_config);
printf("3\n");
// std::map<TInt, TFlt> cost_map = std::map<TInt, TFlt>();
// for (auto _it = m_link_factory -> m_link_map.begin(); _it != m_link_factory -> m_link_map.end(); ++_it){
// cost_map.insert(std::pair<TInt, TFlt>(_it -> first, TFlt(1)));
// }
// std::map<TInt, TInt> output_map = std::map<TInt, TInt>();
// MNM_Shortest_Path::all_to_one_Dijkstra(6, m_graph, cost_map, output_map);
// MNM_Path *p = MNM::extract_path(1, 6, output_map, m_graph);
// printf("node:%d, link:%d\n", p -> m_node_vec.size(),p -> m_link_vec.size());
Path_Table *path_table = MNM::build_pathset(m_graph, m_od_factory, m_link_factory);
printf("Finish running\n");
// MNM_Path *p;
// for (size_t i = 0; i< path_table -> find(1) -> second -> find(5) -> second -> m_path_vec.size(); ++i){
// p = path_table -> find(1) -> second -> find(5) -> second -> m_path_vec[i];
// printf("node:%d, link:%d\n", p -> m_node_vec.size(),p -> m_link_vec.size());
// }
MNM::save_path_table(path_table, m_od_factory, true);
printf("Finish saving\n");
// Path_Table *path_table;
// path_table = MNM_IO::load_path_table("path_table", m_graph, 189065);
// for (size_t i = 0; i< path_table -> find(1) -> second -> find(5) -> second -> m_path_vec.size(); ++i){
// p = path_table -> find(1) -> second -> find(5) -> second -> m_path_vec[i];
// printf("node:%d, link:%d\n", p -> m_node_vec.size(),p -> m_link_vec.size());
// }
return 0;
}
|
Lemma1/MAC-POSTS
|
src/examples/test_path.cpp
|
C++
|
mit
| 2,805
|
// @ts-ignore
import Fragment from "ember-data-model-fragments/fragment";
import Store from "@ember-data/store";
import { attr } from "@ember-data/model";
import { computed } from "@ember/object";
import { isBlank } from "@ember/utils";
import { task } from "ember-concurrency-decorators";
import { inject as service } from "@ember/service";
import { tracked } from "@glimmer/tracking";
import { taskFor } from "ember-concurrency-ts";
import AddressService from "../services/address";
export default class Address extends Fragment {
// @ts-ignore
@service("address") addressing!: AddressService;
@service store!: Store;
/**
* This is the Address format that will be used to validate the address
* This checks on the requied fields (depending on the country)
* The format of postal codes, ...
*/
@tracked format?: any;
@attr("string")
countryCode?: string;
@attr("string")
administrativeArea?: string;
@attr("string")
locality?: string;
@attr("string")
dependentLocality?: string;
@attr("string")
postalCode?: string;
@attr("string")
sortingCode?: string;
@attr("string")
addressLine1?: string;
@attr("string")
addressLine2?: string;
copyAddress(): Address {
// @ts-ignore
const newAddress = <Address>this.store.createFragment("address");
newAddress.countryCode = this.countryCode;
newAddress.administrativeArea = this.administrativeArea;
newAddress.locality = this.locality;
newAddress.dependentLocality = this.dependentLocality;
newAddress.postalCode = this.postalCode;
newAddress.sortingCode = this.sortingCode;
newAddress.addressLine1 = this.addressLine1;
newAddress.addressLine2 = this.addressLine2;
return newAddress;
}
setAllFromAddress(address: Address) {
this.countryCode = address.countryCode;
this.administrativeArea = address.administrativeArea;
this.locality = address.locality;
this.dependentLocality = address.dependentLocality;
this.postalCode = address.postalCode;
this.sortingCode = address.sortingCode;
this.addressLine1 = address.addressLine1;
this.addressLine2 = address.addressLine2;
}
clear() {
this.countryCode = undefined;
this.administrativeArea = undefined;
this.locality = undefined;
this.dependentLocality = undefined;
this.postalCode = undefined;
this.sortingCode = undefined;
this.addressLine1 = undefined;
this.addressLine2 = undefined;
}
/**
* Returns a plain old javascript object with the attributes filled in as keys, and the values as values
*/
getPOJO() {
const pojo = {
countryCode: this.countryCode,
administrativeArea: this.administrativeArea,
locality: this.locality,
dependentLocality: this.dependentLocality,
postalCode: this.postalCode,
sortingCode: this.sortingCode,
addressLine1: this.addressLine1,
addressLine2: this.addressLine2,
};
return pojo;
}
clearExceptAddressLines() {
this.countryCode = undefined;
this.administrativeArea = undefined;
this.locality = undefined;
this.dependentLocality = undefined;
this.postalCode = undefined;
this.sortingCode = undefined;
}
@computed(
"countryCode",
"administrativeArea",
"locality",
"dependentLocality",
"postalCode",
"sortingCode",
"addressLine1",
"addressLine2"
)
get isBlankModel(): boolean {
return (
isBlank(this.countryCode) &&
isBlank(this.administrativeArea) &&
isBlank(this.locality) &&
isBlank(this.dependentLocality) &&
isBlank(this.postalCode) &&
isBlank(this.sortingCode) &&
isBlank(this.addressLine1) &&
isBlank(this.addressLine2)
);
}
@computed(
"format",
"countryCode",
"administrativeArea",
"locality",
"dependentLocality",
"postalCode",
"sortingCode",
"addressLine1",
"addressLine2"
)
get isValidModel(): boolean {
const ignoreFields = [
"organization",
"givenName",
"additionalName",
"familyName",
];
let returnValue = true;
if (!isBlank(this.format)) {
const requiredFields = this.format.data.attributes["required-fields"];
// @ts-ignore
requiredFields.some((requiredField: string) => {
if (!ignoreFields.includes(requiredField)) {
// @ts-ignore
if (isBlank(this.get(requiredField))) {
returnValue = false;
return !returnValue;
}
}
});
}
return returnValue;
}
@task
async loadFormat(): Promise<void> {
if (!this.countryCode) {
if (!this.isBlankModel) {
// no country code is chosen, the address must be cleared
this.clear();
this.format = undefined;
}
} else {
if (!this.format || this.format.data.id !== this.countryCode) {
const format = await taskFor(this.addressing.getAddressFormat).perform(
this.countryCode
);
this.format = format;
}
}
}
}
|
pjcarly/ember-mist-components
|
addon/models/address.ts
|
TypeScript
|
mit
| 5,036
|
export function threePointSecondDerivative(previous, current, next, uniformDistance) {
return (next - 2 * current + previous) / (uniformDistance * uniformDistance);
}
|
woochi/sensic
|
src/board/differential.js
|
JavaScript
|
mit
| 169
|
// Copyright (C) 2011 - Will Glozer. All rights reserved.
package outils.crypt.jni;
/**
* {@code LibraryLoaders} will create the appropriate {@link LibraryLoader} for
* the VM it is running on.
*
* The system property {@code com.lambdaworks.jni.loader} may be used to override
* loader auto-detection, or to disable loading native libraries entirely via use
* of the nil loader.
*
* @author Will Glozer
*/
public class LibraryLoaders {
/**
* Create a new {@link LibraryLoader} for the current VM.
*
* @return the loader.
*/
public static LibraryLoader loader() {
String type = System.getProperty("com.lambdaworks.jni.loader");
if (type != null) {
if (type.equals("sys")) return new SysLibraryLoader();
if (type.equals("nil")) return new NilLibraryLoader();
if (type.equals("jar")) return new JarLibraryLoader();
throw new IllegalStateException("Illegal value for com.lambdaworks.jni.loader: " + type);
}
String vmSpec = System.getProperty("java.vm.specification.name");
return vmSpec.startsWith("Java") ? new JarLibraryLoader() : new SysLibraryLoader();
}
}
|
Chnapy/Timeflies_Serveur_v2
|
src/main/java/outils/crypt/jni/LibraryLoaders.java
|
Java
|
mit
| 1,192
|
import uuid
from typing import Optional, Union
from mitmproxy import connection
from mitmproxy import flow
from mitmproxy import http
from mitmproxy import tcp
from mitmproxy import websocket
from mitmproxy.test.tutils import treq, tresp
from wsproto.frame_protocol import Opcode
def ttcpflow(client_conn=True, server_conn=True, messages=True, err=None) -> tcp.TCPFlow:
if client_conn is True:
client_conn = tclient_conn()
if server_conn is True:
server_conn = tserver_conn()
if messages is True:
messages = [
tcp.TCPMessage(True, b"hello", 946681204.2),
tcp.TCPMessage(False, b"it's me", 946681204.5),
]
if err is True:
err = terr()
f = tcp.TCPFlow(client_conn, server_conn)
f.messages = messages
f.error = err
f.live = True
return f
def twebsocketflow(messages=True, err=None, close_code=None, close_reason='') -> http.HTTPFlow:
flow = http.HTTPFlow(tclient_conn(), tserver_conn())
flow.request = http.Request(
"example.com",
80,
b"GET",
b"http",
b"example.com",
b"/ws",
b"HTTP/1.1",
headers=http.Headers(
connection="upgrade",
upgrade="websocket",
sec_websocket_version="13",
sec_websocket_key="1234",
),
content=b'',
trailers=None,
timestamp_start=946681200,
timestamp_end=946681201,
)
flow.response = http.Response(
b"HTTP/1.1",
101,
reason=b"Switching Protocols",
headers=http.Headers(
connection='upgrade',
upgrade='websocket',
sec_websocket_accept=b'',
),
content=b'',
trailers=None,
timestamp_start=946681202,
timestamp_end=946681203,
)
flow.websocket = twebsocket()
flow.websocket.close_reason = close_reason
if close_code is not None:
flow.websocket.close_code = close_code
else:
if err is True:
# ABNORMAL_CLOSURE
flow.websocket.close_code = 1006
else:
# NORMAL_CLOSURE
flow.websocket.close_code = 1000
flow.live = True
return flow
def tflow(
*,
client_conn: Optional[connection.Client] = None,
server_conn: Optional[connection.Server] = None,
req: Optional[http.Request] = None,
resp: Union[bool, http.Response] = False,
err: Union[bool, flow.Error] = False,
ws: Union[bool, websocket.WebSocketData] = False,
live: bool = True,
) -> http.HTTPFlow:
"""Create a flow for testing."""
if client_conn is None:
client_conn = tclient_conn()
if server_conn is None:
server_conn = tserver_conn()
if req is None:
req = treq()
if resp is True:
resp = tresp()
if err is True:
err = terr()
if ws is True:
ws = twebsocket()
assert resp is False or isinstance(resp, http.Response)
assert err is False or isinstance(err, flow.Error)
assert ws is False or isinstance(ws, websocket.WebSocketData)
f = http.HTTPFlow(client_conn, server_conn)
f.request = req
f.response = resp or None
f.error = err or None
f.websocket = ws or None
f.live = live
return f
class DummyFlow(flow.Flow):
"""A flow that is neither HTTP nor TCP."""
def __init__(self, client_conn, server_conn, live=None):
super().__init__("dummy", client_conn, server_conn, live)
def tdummyflow(client_conn=True, server_conn=True, err=None) -> DummyFlow:
if client_conn is True:
client_conn = tclient_conn()
if server_conn is True:
server_conn = tserver_conn()
if err is True:
err = terr()
f = DummyFlow(client_conn, server_conn)
f.error = err
f.live = True
return f
def tclient_conn() -> connection.Client:
c = connection.Client.from_state(dict(
id=str(uuid.uuid4()),
address=("127.0.0.1", 22),
mitmcert=None,
tls_established=True,
timestamp_start=946681200,
timestamp_tls_setup=946681201,
timestamp_end=946681206,
sni="address",
cipher_name="cipher",
alpn=b"http/1.1",
tls_version="TLSv1.2",
tls_extensions=[(0x00, bytes.fromhex("000e00000b6578616d"))],
state=0,
sockname=("", 0),
error=None,
tls=False,
certificate_list=[],
alpn_offers=[],
cipher_list=[],
))
return c
def tserver_conn() -> connection.Server:
c = connection.Server.from_state(dict(
id=str(uuid.uuid4()),
address=("address", 22),
source_address=("address", 22),
ip_address=("192.168.0.1", 22),
timestamp_start=946681202,
timestamp_tcp_setup=946681203,
timestamp_tls_setup=946681204,
timestamp_end=946681205,
tls_established=True,
sni="address",
alpn=None,
tls_version="TLSv1.2",
via=None,
state=0,
error=None,
tls=False,
certificate_list=[],
alpn_offers=[],
cipher_name=None,
cipher_list=[],
via2=None,
))
return c
def terr(content: str = "error") -> flow.Error:
err = flow.Error(content, 946681207)
return err
def twebsocket(messages: bool = True) -> websocket.WebSocketData:
ws = websocket.WebSocketData()
if messages:
ws.messages = [
websocket.WebSocketMessage(Opcode.BINARY, True, b"hello binary", 946681203),
websocket.WebSocketMessage(Opcode.TEXT, True, b"hello text", 946681204),
websocket.WebSocketMessage(Opcode.TEXT, False, b"it's me", 946681205),
]
ws.close_reason = "Close Reason"
ws.close_code = 1000
ws.closed_by_client = False
ws.timestamp_end = 946681205
return ws
|
mitmproxy/mitmproxy
|
mitmproxy/test/tflow.py
|
Python
|
mit
| 5,859
|
require 'spec_helper'
describe Pub do
it "should find all pubs" do
list_of_pubs = Pub.all
list_of_pubs.size.should > 150
end
it "should find at least one Bishops" do
Pub.all.detect {|pub| pub.name =~ /Bishops/ } .should_not be_nil
end
it "should find names on em all" do
Pub.all.each { |pub| pub.name.should_not be_nil }
end
it "should find latitude on em all" do
Pub.all.each { |pub| pub.latitude.should_not be_nil }
end
it "should find longitude on em all" do
Pub.all.each { |pub| pub.longitude.should_not be_nil }
end
it "should find one pub near me" do
nearest_pub = Pub.find
nearest_pub.name .should_not be_nil
nearest_pub.latitude .should_not be_nil
nearest_pub.longitude.should_not be_nil
end
it "should find oliver twist" do
oliver = Pub.find :address => "Repslagargatan 6, Stockholm"
oliver.name.should == 'Oliver Twist'
end
it "should find relative a point" do
amsterdam = Pub.find :point => [57.71, 11.98]
amsterdam.name.should == 'Het Amsterdammertje'
end
it "should find any number of pubs" do
pubs = Pub.find :count => 5
pubs.size.should == 5
end
end
|
froderik/thirst
|
spec/thirst_quencher_spec.rb
|
Ruby
|
mit
| 1,178
|
package javaProbs;
/**
* LeetCode - Problem 9
*
* Determine whether an integer is a palindrome. Do this without extra space.
*
* @author DJTai
*
*/
public class Solution_009_Palindrome
{
public static void main(String[] args)
{
int num1 = 10109;
int num2 = 10101;
int num3 = 123454321;
System.out.println(isPalindrome(num1));
System.out.println(isPalindrome(num2));
System.out.println(isPalindrome(num3));
} // end main
//-----Solution-----//
public static boolean isPalindrome(int x)
{
int revX = x;
int y = 0;
while (revX > 0)
{
y = y * 10 + revX % 10;
revX /= 10;
}
return y == x;
} // end isPalindrome
} // end class
|
DJ-Tai/practice-problems
|
leet-code/java/javaProbs/Solution_009_Palindrome.java
|
Java
|
mit
| 750
|
class TempGenerator
attr_reader :date, :filename, :title, :file_array
def initialize(date)
@date = date
end
def to_file
if File.exist? @filename
puts "The file already exists. Quitting"
return
end
File.open(@filename, 'w') do |f|
@file_array.each { |line| f.write line }
end
puts "File written to #{@filename}"
end
end
|
lannonbr/cosi-temp
|
lib/cosi-temp/temp-generator.rb
|
Ruby
|
mit
| 373
|
#include "stdafx.h"
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute("Project2")];
[assembly:AssemblyDescriptionAttribute("Project2 - Amrit Panesar - 77260")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("")];
[assembly:AssemblyProductAttribute("Project2")];
[assembly:AssemblyCopyrightAttribute("Copyright (c) Amrit Panesar 2015 ALL RIGHTS RESERVED")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly:AssemblyVersionAttribute("1.0.*")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];
[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
|
Neo-Desktop/Coleman-Code
|
COM380/Project2/Project2/AssemblyInfo.cpp
|
C++
|
mit
| 1,357
|
package ofuangka.propmessages.api.security;
public interface SecurityService {
String getUserId();
String getUsername();
String getLogoutUrl(String afterUrl);
}
|
ofuangka/prop-messages
|
api/src/main/java/ofuangka/propmessages/api/security/SecurityService.java
|
Java
|
mit
| 168
|
.icon-product-navy {
background-image: url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2223%22%20height%3D%2223%22%20viewBox%3D%220%200%2023%2023%22%3E%3Ctitle%3Eicons-singletons%3C%2Ftitle%3E%3Cpolygon%20points%3D%226.38%206.19%2011.5%203.28%2016.62%206.19%2011.5%209.28%206.38%206.19%22%20fill%3D%22%23375667%22%2F%3E%3Cpath%20d%3D%22M11.5%2C0.25L1.87%2C5.72V17.28l9.63%2C5.47%2C9.63-5.47V5.72ZM19%2C6.15L11.5%2C10.68%2C4%2C6.15%2C11.5%2C1.87ZM3.28%2C7.37L10.8%2C11.9v8.83L3.28%2C16.46V7.37ZM12.2%2C20.73V11.9l7.52-4.52v9.09Z%22%20fill%3D%22%23375667%22%2F%3E%3C%2Fsvg%3E');
background-repeat: no-repeat;
}
.icon-product-teal {
background-image: url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2223%22%20height%3D%2223%22%20viewBox%3D%220%200%2023%2023%22%3E%3Ctitle%3Eicons-singletons%3C%2Ftitle%3E%3Cpolygon%20points%3D%226.38%206.19%2011.5%203.28%2016.62%206.19%2011.5%209.28%206.38%206.19%22%20fill%3D%22%2322b8af%22%2F%3E%3Cpath%20d%3D%22M11.5%2C0.25L1.87%2C5.72V17.28l9.63%2C5.47%2C9.63-5.47V5.72ZM19%2C6.15L11.5%2C10.68%2C4%2C6.15%2C11.5%2C1.87ZM3.28%2C7.37L10.8%2C11.9v8.83L3.28%2C16.46V7.37ZM12.2%2C20.73V11.9l7.52-4.52v9.09Z%22%20fill%3D%22%2322b8af%22%2F%3E%3C%2Fsvg%3E');
background-repeat: no-repeat;
}
.icon-product-black {
background-image: url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2223%22%20height%3D%2223%22%20viewBox%3D%220%200%2023%2023%22%3E%3Ctitle%3Eicons-singletons%3C%2Ftitle%3E%3Cpolygon%20points%3D%226.38%206.19%2011.5%203.28%2016.62%206.19%2011.5%209.28%206.38%206.19%22%20fill%3D%22%23000000%22%2F%3E%3Cpath%20d%3D%22M11.5%2C0.25L1.87%2C5.72V17.28l9.63%2C5.47%2C9.63-5.47V5.72ZM19%2C6.15L11.5%2C10.68%2C4%2C6.15%2C11.5%2C1.87ZM3.28%2C7.37L10.8%2C11.9v8.83L3.28%2C16.46V7.37ZM12.2%2C20.73V11.9l7.52-4.52v9.09Z%22%20fill%3D%22%23000000%22%2F%3E%3C%2Fsvg%3E');
background-repeat: no-repeat;
}
.icon-product-gray {
background-image: url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2223%22%20height%3D%2223%22%20viewBox%3D%220%200%2023%2023%22%3E%3Ctitle%3Eicons-singletons%3C%2Ftitle%3E%3Cpolygon%20points%3D%226.38%206.19%2011.5%203.28%2016.62%206.19%2011.5%209.28%206.38%206.19%22%20fill%3D%22%239baab2%22%2F%3E%3Cpath%20d%3D%22M11.5%2C0.25L1.87%2C5.72V17.28l9.63%2C5.47%2C9.63-5.47V5.72ZM19%2C6.15L11.5%2C10.68%2C4%2C6.15%2C11.5%2C1.87ZM3.28%2C7.37L10.8%2C11.9v8.83L3.28%2C16.46V7.37ZM12.2%2C20.73V11.9l7.52-4.52v9.09Z%22%20fill%3D%22%239baab2%22%2F%3E%3C%2Fsvg%3E');
background-repeat: no-repeat;
}
.icon-product {
background-image: url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2223%22%20height%3D%2223%22%20viewBox%3D%220%200%2023%2023%22%3E%3Ctitle%3Eicons-singletons%3C%2Ftitle%3E%3Cpolygon%20points%3D%226.38%206.19%2011.5%203.28%2016.62%206.19%2011.5%209.28%206.38%206.19%22%20fill%3D%22%2322b8af%22%2F%3E%3Cpath%20d%3D%22M11.5%2C0.25L1.87%2C5.72V17.28l9.63%2C5.47%2C9.63-5.47V5.72ZM19%2C6.15L11.5%2C10.68%2C4%2C6.15%2C11.5%2C1.87ZM3.28%2C7.37L10.8%2C11.9v8.83L3.28%2C16.46V7.37ZM12.2%2C20.73V11.9l7.52-4.52v9.09Z%22%20fill%3D%22%23375667%22%2F%3E%3C%2Fsvg%3E');
background-repeat: no-repeat;
}
.icon-product-white {
background-image: url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2223%22%20height%3D%2223%22%20viewBox%3D%220%200%2023%2023%22%3E%3Ctitle%3Eicons-singletons%3C%2Ftitle%3E%3Cpolygon%20points%3D%226.38%206.19%2011.5%203.28%2016.62%206.19%2011.5%209.28%206.38%206.19%22%20fill%3D%22%23ffffff%22%2F%3E%3Cpath%20d%3D%22M11.5%2C0.25L1.87%2C5.72V17.28l9.63%2C5.47%2C9.63-5.47V5.72ZM19%2C6.15L11.5%2C10.68%2C4%2C6.15%2C11.5%2C1.87ZM3.28%2C7.37L10.8%2C11.9v8.83L3.28%2C16.46V7.37ZM12.2%2C20.73V11.9l7.52-4.52v9.09Z%22%20fill%3D%22%23ffffff%22%2F%3E%3C%2Fsvg%3E');
background-repeat: no-repeat;
}
|
vhx/quartz-rails
|
vendor/assets/stylesheets/vhx-quartz.icon-product.css
|
CSS
|
mit
| 4,041
|
from django.test import Client
import mock as mock
from image_converter.tests.base import ImageConversionBaseTestCase
from image_converter.utils.convert_image import convert_image_to_jpeg
__author__ = 'Dominic Dumrauf'
class ViewsTestCase(ImageConversionBaseTestCase):
"""
Tests the 'views'.
"""
def test_upload_get(self):
"""
Tests GETting the form initially.
"""
# Given
c = Client()
# When
response = c.get('/')
# Then
self.assertTemplateUsed(response, template_name='upload.html')
self.assertEqual(response.status_code, 200)
self.assertIn('form', response.context)
def test_upload_post_without_file(self):
"""
Tests POSTing a form which *lacks* a file.
"""
# Given
c = Client()
# When
response = c.post('/')
# Then
self.assertTemplateUsed(response, template_name='upload.html')
self.assertFormError(response, 'form', 'file', 'This field is required.')
self.assertEqual(response.status_code, 200)
self.assertIn('form', response.context)
def test_upload_post_with_non_image_file(self):
"""
Tests POSTing a form which contains a file but the file is not an image.
"""
# Given
c = Client()
# When
with open(self.non_image_file_path) as fp:
response = c.post('/', {'file': fp})
# Then
self.assertTemplateUsed(response, template_name='unsupported_image_file_error.html')
self.assertEqual(response.status_code, 200)
self.assertIn('file', response.context)
self.assertIn(self.non_image_file_name, response.content)
def test_upload_post_with_image_file(self):
"""
Tests POSTing a form which contains a file where the file is an image.
"""
# Given
c = Client()
# When
with open(self.image_file_path) as fp:
response = c.post('/', {'file': fp})
converted_image = convert_image_to_jpeg(fp)
# Then
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Disposition'], 'attachment; filename={0}.jpg'.format(self.image_file_name))
self.assertEqual(response.content, converted_image.getvalue())
@mock.patch('image_converter.views.convert_image_to_jpeg')
def test_unexpected_error_in_image_conversion_handling(self, convert_image_to_jpeg):
"""
Tests POSTing a form where converting the image raises an unexpected exception.
"""
# Given
convert_image_to_jpeg.side_effect = Exception()
c = Client()
# When
with open(self.non_image_file_path) as fp:
response = c.post('/', {'file': fp})
# Then
self.assertTemplateUsed(response, template_name='generic_error.html')
self.assertEqual(response.status_code, 200)
self.assertIn('file', response.context)
self.assertIn(self.non_image_file_name, response.content)
|
dumrauf/web_tools
|
image_converter/tests/test_views.py
|
Python
|
mit
| 3,078
|
<?php
namespace AppBundle\Controller;
//use AppBundle\Entity\RarOrder;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManagerInterface;
class LogoutController extends Controller
{
/**
* @Route("/logout", name="logout")
*/
public function logoutAction()
{
}
}
|
Jo3lefou/ERPBackRA
|
src/AppBundle/Controller/LogoutController.php
|
PHP
|
mit
| 486
|
package net.woeye.verbatim.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static DatabaseHelper instance = null;
private final static int DATABASE_VERSION = 1;
private final static String DATABASE_NAME = "verbatim";
private Context ctx;
public static DatabaseHelper getInstance(Context ctx) {
if (instance == null) {
instance = new DatabaseHelper(ctx.getApplicationContext());
}
return instance;
}
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.ctx = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "";
// Collection
sql = "create table collection (" +
"col_id integer primary key, " +
"name" +
")";
db.execSQL(sql);
// Card
sql = "create table card (" +
"card_id integer primary key, " +
"col_id integer, " +
"front text, " +
"back text, " +
"level integer, " +
"last_training integer, " + // unix timestamp
"foreign key(col_id) references collection(col_id)" +
")";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
|
woeye/verbatim-android
|
Verbatim/src/main/java/net/woeye/verbatim/db/DatabaseHelper.java
|
Java
|
mit
| 1,554
|
namespace DbTestMonkey.Contracts
{
using System.Configuration;
public class DatabasesConfigurationCollection : ConfigurationElementCollection
{
public DatabaseConfiguration this[int index]
{
get
{
return base.BaseGet(index) as DatabaseConfiguration;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
public new DatabaseConfiguration this[string responseString]
{
get
{
return (DatabaseConfiguration)BaseGet(responseString);
}
set
{
if (BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new DatabaseConfiguration();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((DatabaseConfiguration)element).DatabaseName;
}
}
}
|
DbTestMonkey/DbTestMonkey
|
src/DbTestMonkey.Contracts/DatabasesConfigurationCollection.cs
|
C#
|
mit
| 1,272
|
<?php
// make an associative array of senders we know, indexed by phone number
$people = array(
"+14158675309"=>"Curious George",
"+14158675310"=>"Boots",
"+14158675311"=>"Virgil",
);
// if the sender is known, then greet them by name
// otherwise, consider them just another monkey
if(!$name = $people[$_REQUEST['From']]) {
$name = "Monkey";
}
// now greet the sender
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<Response>
<Sms><?php echo $name ?>, thanks for the message!</Sms>
</Response>
|
gmittal/gautam.cc
|
hacks/ancient/gautam.cc-backups/gautam.cc-old.cc/sms/sms-reply.php
|
PHP
|
mit
| 560
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>XAMPP 访问 Access forbidden 问题 – 再试,再失败,更好地失败</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="当安装好 XAMPP 用 IP 进行访问的时候会出现以下的提示">
<meta name="author" content="tudousi">
<meta name="keywords" content="Access forbidden">
<link rel="canonical" href="http://tudousi.github.io//tools/2015/02/27/xampp-access-forbidden/">
<link rel="alternate" type="application/rss+xml" title="RSS Feed for 再试,再失败,更好地失败" href="/feed.xml" />
<meta name="baidu-site-verification" content="3865RHLBYn" />
<!-- Custom CSS -->
<link rel="stylesheet" href="/css/pixyll.css?201603180337" type="text/css">
<!-- Fonts -->
<!--
<link href='//fonts.googleapis.com/css?family=Merriweather:900,900italic,300,300italic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Lato:900,300' rel='stylesheet' type='text/css'>
-->
<!-- Verifications -->
<!-- Open Graph -->
<!-- From: https://github.com/mmistakes/hpstr-jekyll-theme/blob/master/_includes/head.html -->
<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="XAMPP 访问 Access forbidden 问题">
<meta property="og:description" content="一个菜鸟的前端学习历程 html css javascript node node.js">
<meta property="og:url" content="http://tudousi.github.io//tools/2015/02/27/xampp-access-forbidden/">
<meta property="og:site_name" content="再试,再失败,更好地失败">
<!-- Twitter Card -->
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="XAMPP 访问 Access forbidden 问题" />
<meta name="twitter:description" content="当安装好 XAMPP 用 IP 进行访问的时候会出现以下的提示" />
<meta name="twitter:url" content="http://tudousi.github.io//tools/2015/02/27/xampp-access-forbidden/" />
<!-- Icons -->
<link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180x180.png">
<link rel="icon" type="image/png" href="/favicon-192x192.png" sizes="192x192">
<link rel="icon" type="image/png" href="/favicon-160x160.png" sizes="160x160">
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
</head>
<body class="site">
<div class="site-wrap">
<header class="site-header px2 px-responsive">
<div class="mt2 wrap">
<div class="measure">
<a href="http://tudousi.github.io/" class="site-title">再试,再失败,更好地失败</a>
<nav class="site-nav">
<a href="/mtb/">MTB</a>
<a href="/about/">About</a>
<a href="/contact/">Contact</a>
</nav>
<div class="clearfix"></div>
</div>
</div>
</header>
<div class="post p2 p-responsive wrap" role="main">
<div class="measure">
<div class="post-header mb2">
<h1>XAMPP 访问 Access forbidden 问题</h1>
<span class="post-meta">2015-02-27</span><br>
<span class="post-meta small">
1 minute read
</span>
</div>
<article class="post-content">
<p>当安装好 XAMPP 用 IP 进行访问的时候会出现以下的提示</p>
<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">Access</span> <span class="nx">forbidden</span><span class="o">!</span>
<span class="o">--------------------------------------------------------------------------------</span>
<span class="nx">New</span> <span class="nx">XAMPP</span> <span class="nx">security</span> <span class="nx">concept</span><span class="err">:</span>
<span class="nx">Access</span> <span class="nx">to</span> <span class="nx">the</span> <span class="nx">requested</span> <span class="nx">object</span> <span class="nx">is</span> <span class="nx">only</span> <span class="nx">available</span> <span class="nx">from</span> <span class="nx">the</span> <span class="nx">local</span> <span class="nx">network</span><span class="p">.</span>
<span class="nx">This</span> <span class="nx">setting</span> <span class="nx">can</span> <span class="nx">be</span> <span class="nx">configured</span> <span class="k">in</span> <span class="nx">the</span> <span class="nx">file</span> <span class="s2">"httpd-xampp.conf"</span><span class="p">.</span></code></pre></figure>
<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="err">根据提示,修改</span> <span class="nx">httpd</span><span class="o">-</span><span class="nx">xampp</span><span class="p">.</span><span class="nx">conf</span> <span class="err">即可</span>
<span class="err">#</span>
<span class="err">#</span> <span class="nx">New</span> <span class="nx">XAMPP</span> <span class="nx">security</span> <span class="nx">concept</span>
<span class="err">#</span>
<span class="o"><</span><span class="nx">LocationMatch</span> <span class="s2">"^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))"</span><span class="o">></span>
<span class="nx">Require</span> <span class="nx">local</span>
<span class="nx">ErrorDocument</span> <span class="mi">403</span> <span class="o">/</span><span class="nx">error</span><span class="o">/</span><span class="nx">XAMPP_FORBIDDEN</span><span class="p">.</span><span class="nx">html</span><span class="p">.</span><span class="kd">var</span>
<span class="o"><</span><span class="sr">/LocationMatch></span><span class="err">
</span>
<span class="err">修改为</span>
<span class="err">#</span>
<span class="err">#</span> <span class="nx">New</span> <span class="nx">XAMPP</span> <span class="nx">security</span> <span class="nx">concept</span>
<span class="err">#</span>
<span class="o"><</span><span class="nx">LocationMatch</span> <span class="s2">"^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))"</span><span class="o">></span>
<span class="err">#</span><span class="nx">Require</span> <span class="nx">local</span>
<span class="nx">Options</span> <span class="nx">All</span>
<span class="nx">AllowOverride</span> <span class="nx">All</span>
<span class="nx">Order</span> <span class="nx">deny</span><span class="p">,</span><span class="nx">allow</span>
<span class="nx">Allow</span> <span class="nx">from</span> <span class="nx">all</span>
<span class="nx">ErrorDocument</span> <span class="mi">403</span> <span class="o">/</span><span class="nx">error</span><span class="o">/</span><span class="nx">XAMPP_FORBIDDEN</span><span class="p">.</span><span class="nx">html</span><span class="p">.</span><span class="kd">var</span>
<span class="o"><</span><span class="sr">/LocationMatch></span></code></pre></figure>
<p>如果出现</p>
<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="nx">Access</span> <span class="nx">forbidden</span><span class="o">!</span> <span class="nx">You</span> <span class="nx">don</span><span class="err">’</span><span class="nx">t</span> <span class="nx">have</span> <span class="nx">permission</span> <span class="nx">to</span> <span class="nx">access</span> <span class="nx">the</span> <span class="nx">requested</span> <span class="nx">object</span><span class="p">.</span> <span class="nx">It</span> <span class="nx">is</span> <span class="nx">either</span> <span class="nx">read</span><span class="o">-</span><span class="kr">protected</span> <span class="nx">or</span> <span class="nx">not</span> <span class="nx">readable</span> <span class="nx">by</span> <span class="nx">the</span> <span class="nx">server</span><span class="p">.</span></code></pre></figure>
<p>这时可以找到apache的httpd.conf文件,找出<directory></directory>
修改成如下:</p>
<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="o"><</span><span class="nx">Directory</span> <span class="o">/></span>
<span class="nx">Options</span> <span class="nx">All</span>
<span class="nx">AllowOverride</span> <span class="nx">All</span>
<span class="nx">Order</span> <span class="nx">deny</span><span class="p">,</span><span class="nx">allow</span>
<span class="nx">Allow</span> <span class="nx">from</span> <span class="nx">all</span>
<span class="o"><</span><span class="sr">/Directory></span><span class="err">
</span><span class="c1">// mac执行 sudo chmod -R 777 /Applications/XAMPP/xamppfiles/htdocs</span></code></pre></figure>
<p>重启服务即可</p>
</article>
</div>
</div>
</div>
<footer class="center">
<div class="measure">
<small>
© 2015 <a href="http://createthink.net">createthink.net</a> with Help from <a href="http://jekyllrb.com/">Jekyll</a> and Theme crafted with by <a href="http://johnotander.com">John Otander</a>
</small>
</div>
</footer>
<script>
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "//hm.baidu.com/hm.js?86487f6d309f8a041841232abb6ff18d";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script>
<script>
(function(){
var bp = document.createElement('script');
bp.src = '//push.zhanzhang.baidu.com/push.js';
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(bp, s);
})();
</script>
</body>
</html>
|
tudousi/tudousi.github.io
|
_site/tools/2015/02/27/xampp-access-forbidden/index.html
|
HTML
|
mit
| 10,479
|
using System.Collections.Immutable;
using NQuery.Authoring.BraceMatching;
namespace NQuery.Authoring.Composition.BraceMatching
{
public interface IBraceMatcherService
{
ImmutableArray<IBraceMatcher> Matchers { get; }
}
}
|
terrajobst/nquery-vnext
|
src/NQuery.Authoring.Composition/BraceMatching/IBraceMatcherService.cs
|
C#
|
mit
| 245
|
<!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"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>V8 API Reference Guide for node.js v7.6.0: v8_inspector::V8StackTrace Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">V8 API Reference Guide for node.js v7.6.0
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><b>v8_inspector</b></li><li class="navelem"><a class="el" href="classv8__inspector_1_1V8StackTrace.html">V8StackTrace</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="classv8__inspector_1_1V8StackTrace-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">v8_inspector::V8StackTrace Class Reference<span class="mlabels"><span class="mlabel">abstract</span></span></div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:a969853e542a4df1eafd84da4cdd53728"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a969853e542a4df1eafd84da4cdd53728"></a>
virtual bool </td><td class="memItemRight" valign="bottom"><b>isEmpty</b> () const =0</td></tr>
<tr class="separator:a969853e542a4df1eafd84da4cdd53728"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a66a69050f9e87393455fbbf989f1d01d"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a66a69050f9e87393455fbbf989f1d01d"></a>
virtual <a class="el" href="classv8__inspector_1_1StringView.html">StringView</a> </td><td class="memItemRight" valign="bottom"><b>topSourceURL</b> () const =0</td></tr>
<tr class="separator:a66a69050f9e87393455fbbf989f1d01d"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a12a71905644e1faf9c820abafa9d94f9"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a12a71905644e1faf9c820abafa9d94f9"></a>
virtual int </td><td class="memItemRight" valign="bottom"><b>topLineNumber</b> () const =0</td></tr>
<tr class="separator:a12a71905644e1faf9c820abafa9d94f9"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a7c6a4edfd7769e73e2f0562659a57a53"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a7c6a4edfd7769e73e2f0562659a57a53"></a>
virtual int </td><td class="memItemRight" valign="bottom"><b>topColumnNumber</b> () const =0</td></tr>
<tr class="separator:a7c6a4edfd7769e73e2f0562659a57a53"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a82e378f1190c0215d21656980c427b13"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a82e378f1190c0215d21656980c427b13"></a>
virtual <a class="el" href="classv8__inspector_1_1StringView.html">StringView</a> </td><td class="memItemRight" valign="bottom"><b>topScriptId</b> () const =0</td></tr>
<tr class="separator:a82e378f1190c0215d21656980c427b13"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a0d7ede4b2a6ba52372a42295924fd7f1"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a0d7ede4b2a6ba52372a42295924fd7f1"></a>
virtual <a class="el" href="classv8__inspector_1_1StringView.html">StringView</a> </td><td class="memItemRight" valign="bottom"><b>topFunctionName</b> () const =0</td></tr>
<tr class="separator:a0d7ede4b2a6ba52372a42295924fd7f1"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a6dbec10e0db0c650f43465f75c35c8e3"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a6dbec10e0db0c650f43465f75c35c8e3"></a>
virtual std::unique_ptr< protocol::Runtime::API::StackTrace > </td><td class="memItemRight" valign="bottom"><b>buildInspectorObject</b> () const =0</td></tr>
<tr class="separator:a6dbec10e0db0c650f43465f75c35c8e3"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a05bb91a501d40686481c4971b4dee7f9"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a05bb91a501d40686481c4971b4dee7f9"></a>
virtual std::unique_ptr< <a class="el" href="classv8__inspector_1_1StringBuffer.html">StringBuffer</a> > </td><td class="memItemRight" valign="bottom"><b>toString</b> () const =0</td></tr>
<tr class="separator:a05bb91a501d40686481c4971b4dee7f9"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a5d03e8bfb799b8ced2bfd5c31615d64a"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a5d03e8bfb799b8ced2bfd5c31615d64a"></a>
virtual std::unique_ptr< <a class="el" href="classv8__inspector_1_1V8StackTrace.html">V8StackTrace</a> > </td><td class="memItemRight" valign="bottom"><b>clone</b> ()=0</td></tr>
<tr class="separator:a5d03e8bfb799b8ced2bfd5c31615d64a"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<hr/>The documentation for this class was generated from the following file:<ul>
<li>deps/v8/include/<a class="el" href="v8-inspector_8h_source.html">v8-inspector.h</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.11
</small></address>
</body>
</html>
|
v8-dox/v8-dox.github.io
|
20127e0/html/classv8__inspector_1_1V8StackTrace.html
|
HTML
|
mit
| 8,714
|
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2020
//
// 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.
// This file was automatically generated and should not be edited directly.
using System;
using System.Runtime.InteropServices;
namespace SharpVk.Interop.NVidia.Experimental
{
/// <summary>
///
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct PhysicalDeviceMultiviewPerViewAttributesProperties
{
/// <summary>
/// The type of this structure.
/// </summary>
public SharpVk.StructureType SType;
/// <summary>
/// Null or an extension-specific structure.
/// </summary>
public void* Next;
/// <summary>
///
/// </summary>
public Bool32 PerViewPositionAllComponents;
}
}
|
FacticiusVir/SharpVk
|
src/SharpVk/Interop/NVidia/Experimental/PhysicalDeviceMultiviewPerViewAttributesProperties.gen.cs
|
C#
|
mit
| 1,909
|
#!/usr/bin/python3
#
# Copyright © 2017 jared <jared@jared-devstation>
#
from pydub import AudioSegment, scipy_effects, effects
import os
import settings, util
# combine two audio samples with a crossfade
def combine_samples(acc, file2, CROSSFADE_DUR=100):
util.debug_print('combining ' + file2)
sample2 = AudioSegment.from_wav(file2)
output = acc.append(sample2, crossfade=CROSSFADE_DUR)
output = effects.normalize(output)
return output
# combine audio samples with crossfade, from within program
def combine_prog_samples(acc, nsamp, CROSSFADE_DUR=100):
output = acc.append(nsamp, crossfade=CROSSFADE_DUR)
return output
# split an audio file into low, mid, high bands
def split_file(fname):
curr_file = AudioSegment.from_file(fname)
low_seg = scipy_effects.low_pass_filter(curr_file, settings.LOW_FREQUENCY_LIM).export(fname + '_low.wav', 'wav')
mid_seg = scipy_effects.band_pass_filter(curr_file, settings.LOW_FREQUENCY_LIM, settings.HIGH_FREQUENCY_LIM).export(fname + '_mid.wav', 'wav')
high_seg = scipy_effects.high_pass_filter(curr_file, settings.HIGH_FREQUENCY_LIM).export(fname + '_high.wav', 'wav')
## add a sample to an existing wav
#def add_sample(fname, samplefile, CROSSFADE_DUR=100):
# new_file = combine_samples(fname, samplefile, CROSSFADE_DUR)[0]
# os.rename(fname, 'old_' + fname)
# os.rename(new_file, fname)
# return new_file[1]
|
techlover10/StochasticSoundscape
|
src/audio.py
|
Python
|
mit
| 1,411
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.