code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
line_mean
float64
0.5
100
line_max
int64
1
1k
alpha_frac
float64
0.25
1
autogenerated
bool
1 class
#region License /* The MIT License * * Copyright (c) 2011 Red Badger Consulting * * 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. */ #endregion namespace RedBadger.Xpf.Graphics { /// <summary> /// Represents a Texture. /// </summary> public interface ITexture { /// <summary> /// Gets the height of this texture in pixels. /// </summary> int Height { get; } /// <summary> /// Gets the width of this texture in pixels. /// </summary> int Width { get; } } }
redbadger/XPF
XPF/RedBadger.Xpf/Graphics/ITexture.cs
C#
mit
1,630
35.906977
80
0.672393
false
<?php namespace fufudao\base; use yii\behaviors\TimestampBehavior; //use yii\behaviors\AttributeBehavior; use yii\db\ActiveRecord as ar; use yii\db\Expression; class ActiveRecord extends ar { public function behaviors() { return [ 'timestamp' => [ 'class' => TimestampBehavior::className(), 'attributes' => [ ActiveRecord::EVENT_BEFORE_INSERT => ['created','modified'], ActiveRecord::EVENT_BEFORE_UPDATE => ['modified'] ], 'value' => new Expression(date('\'Y-m-d H:i:s\'')), ], ]; } public function newID(){ $schema = $this->getTableSchema(); $primaryKey = $schema->primaryKey[0]; $col = $schema->columns[$primaryKey]; $ret = $this->getAttribute($primaryKey); if( empty($ret) ){ if( $col->phpType === \yii\db\Schema::TYPE_STRING ){ switch ($col->size){ case 13: $ret = uniqid(); break; case 32: $ret = md5(uniqid(mt_rand(), true)); break; } } } return $ret; } }
fufudao/yii2-base
base/ActiveRecord.php
PHP
mit
1,074
21.395833
80
0.545624
false
SET DEFINE OFF; CREATE SEQUENCE AFW_07_AUDIT_STRUC_APLIC_SEQ START WITH 1 MAXVALUE 9999999999999999999999999999 MINVALUE 1 NOCYCLE CACHE 20 NOORDER /
lgcarrier/APEXFramework
5.2.3/Database/Sequences/AFW_07_AUDIT_STRUC_APLIC_SEQ.sql
SQL
mit
162
17
44
0.771605
false
# # Cookbook Name:: dokku # Spec:: plugins # # Copyright (c) 2015 Nick Charlton, MIT licensed. require "spec_helper" describe "dokku::plugins" do context "when all attributes are default" do let(:chef_run) do runner = ChefSpec::ServerRunner.new runner.converge(described_recipe) end before do stub_command("which nginx").and_return("/usr/bin/nginx") end it "does nothing" do expect { chef_run }.to_not raise_error end end context "when plugins exist in attributes and no actions are listed" do let(:chef_run) do runner = ChefSpec::ServerRunner.new do |node| node.override["dokku"]["plugins"] = [{ name: "redis", url: "https://github.com/dokku/dokku-redis.git" }] end runner.converge(described_recipe) end before do stub_command("which nginx").and_return("/usr/bin/nginx") end it "installs plugins" do expect(chef_run).to install_dokku_plugin( "redis").with(url: "https://github.com/dokku/dokku-redis.git") end end context "when plugins exist in attributes" do let(:chef_run) do runner = ChefSpec::ServerRunner.new do |node| node.override["dokku"]["plugins"] = [ { name: "redis", url: "https://github.com/dokku/dokku-redis.git", action: "install" }, { name: "mongo", url: "https://github.com/dokku/dokku-mongo.git", action: "uninstall" }, ] end runner.converge(described_recipe) end before do stub_command("which nginx").and_return("/usr/bin/nginx") end it "manages plugins" do expect(chef_run).to install_dokku_plugin( "redis").with(url: "https://github.com/dokku/dokku-redis.git") expect(chef_run).to uninstall_dokku_plugin( "mongo").with(url: "https://github.com/dokku/dokku-mongo.git") end end context "when plugins to be installed provide a commit to fetch" do let(:chef_run) do runner = ChefSpec::ServerRunner.new do |node| node.override["dokku"]["plugins"] = [ { name: "redis", url: "https://github.com/dokku/dokku-redis.git", action: "install", committish: "0.4.4" }, ] end runner.converge(described_recipe) end before do stub_command("which nginx").and_return("/usr/bin/nginx") end it "installs the plugins specifying that committish" do expect(chef_run).to install_dokku_plugin("redis").with( url: "https://github.com/dokku/dokku-redis.git", committish: "0.4.4", ) end end end
nickcharlton/dokku-cookbook
spec/unit/recipes/plugins_spec.rb
Ruby
mit
2,604
27
77
0.612135
false
'use strict'; // Load the application's configuration const config = require('../server/config'); const url = config.express_host + '/api'; // Required modules const async = require('async'); const colors = require('colors'); const request = require('request'); // Counter for the Measurements let counter = 1; // Read the arguments from the command line or set them to the default values const interval = process.argv[2] || 2000; const thingName = process.argv[3] || 'Demo'; const thingLocLat = process.argv[4] || 51.964113; const thingLocLng = process.argv[5] || 7.624862; // REST API authentication token let token; console.log('\n////////////////////////////////////////////////////////////\n'); console.log(' STARTING DEMONSTRATION...'.cyan); console.log('\n////////////////////////////////////////////////////////////\n'); async.waterfall([ // Create a new User function(callback) { console.log(' Creating a new', 'User...\n'.cyan); const userJson = { email: 'demo#' + Math.random().toFixed() + '@example.com', password: 'demoPass' }; // Post the new User request.post({ headers: {'content-type': 'application/json'}, url: url + '/users', json: userJson }, function(error, response, body) { if (!error) { console.log(' New User', 'created.'.green); token = body.token; } else { console.log(' New User creation', 'failed'.red); } console.log('\n------------------------------------------------------------\n'); callback(error, body._id); }); }, // Create a new Thing function(userId, callback) { console.log(' Creating a new', 'Thing...\n'.cyan); const thingJson = { name: thingName, loc: { coordinates: [ thingLocLat, thingLocLng ] }, userId: userId, waterbodyId: '5752d2d7e5d703480187e0d9', token: token }; // Post the new Thing request.post({ headers: {'content-type': 'application/json'}, url: url + '/things', json: thingJson }, function(error, response, body) { if (!error) { console.log(' New Thing', 'created.'.green); } else { console.log(' New Thing creation', 'failed'.red); } console.log('\n------------------------------------------------------------\n'); callback(error, body._id); }); }, // Create a new Feature function(thingId, callback) { console.log(' Creating a new', 'Feature...\n'.cyan); const featureJson = { name: 'demoFeature', unit: 'foo', token: token }; // Post the new Feature request.post({ headers: {'content-type': 'application/json'}, url: url + '/features', json: featureJson }, function(error, response, body) { if (!error) { console.log(' New Feature', 'created'.green); } else { console.log(' New Feature creation', 'failed'.red); } console.log('\n------------------------------------------------------------\n'); callback(error, thingId, body._id); }); }, // Create a new Sensor function(thingId, featureId, callback) { console.log(' Creating a new', 'Sensor...\n'.cyan); const sensorJson = { name: 'demoSensor', interval: interval, refLevel: 2, warnLevel: 6, riskLevel: 8, thingId: thingId, featureId: featureId, token: token }; // Post the new Sensor request.post({ headers: {'content-type': 'application/json'}, url: url + '/sensors', json: sensorJson }, function(error, response, body) { if (!error) { console.log(' New Sensor', 'created.'.green); } else { console.log(' New Sensor creation', 'failed'.red); } console.log('\n------------------------------------------------------------\n'); callback(error, body._id); }); }, // Create new Measurements in an interval function(sensorId, callback) { console.log(' Finished demo setup. Measuring now...'.cyan); console.log('\n------------------------------------------------------------\n'); let value = 4; setInterval(function() { console.log(' Creating a new', 'Measurement...\n'.cyan); // Calculate the Measurement's value as a random number with respect to its previous value if (value < 1 || Math.random() > 0.5) { value += Math.random(); } else { value -= Math.random(); } value = parseFloat(value.toFixed(2)); let measurementJson = { date: Date.now(), value: value, sensorId: sensorId, token: token }; // Post the new Measurement request.post({ headers: {'content-type': 'application/json'}, url: url + '/measurements', json: measurementJson }, function(error, response, body) { if (!error) { console.log(' New Measurement', ('#' + counter).cyan, 'created.'.green, '\nValue:', body.value.cyan); counter++; } else { console.log(' New Measurement creation', 'failed'.red); callback(error); } console.log('\n------------------------------------------------------------\n'); }); }, interval); } ], function(err, result) { if (err) { console.log(err); } });
mrunde/WoT-Vertical-Approach
server/demo/demoSensorController.js
JavaScript
mit
5,051
25.041237
107
0.547812
false
import React from 'react' import {HOC, Link} from 'cerebral-view-react' import PageProgress from '../PageProgress' // View class AutoReload extends React.Component { constructor (props) { super(props) this.state = { secondsElapsed: 0 } this.onInterval = this.onInterval.bind(this) } componentWillMount () { this.intervals = [] } componentWillUnmount () { this.intervals.forEach(clearInterval) } componentDidMount () { this.setInterval(this.onInterval, 1000) } setInterval () { this.intervals.push(setInterval.apply(null, arguments)) } onInterval () { let secondsElapsed = 0 if (this.props.isEnabled) { secondsElapsed = this.state.secondsElapsed + 1 if (secondsElapsed >= this.props.triggerAfterSeconds) { this.trigger() secondsElapsed = 0 } } if (secondsElapsed !== this.state.secondsElapsed) { this.setState({ secondsElapsed: secondsElapsed }) } } trigger () { this.props.triggers.map((trigger) => trigger()) } triggerNow (e) { if (e) { e.preventDefault() } if (this.props.isEnabled) { if (this.state.secondsElapsed > 0) { this.trigger() this.setState({ secondsElapsed: 0 }) } } } render () { const signals = this.props.signals const progress = { isEnabled: this.props.isEnabled, elapsed: this.state.secondsElapsed, total: this.props.triggerAfterSeconds } return ( <div> <PageProgress {...progress} /> <hr /> <pre> BastardAutoloaderFromHell<br /> =========================<br /> [{'='.repeat(this.state.secondsElapsed)}{'.'.repeat(this.props.triggerAfterSeconds - this.state.secondsElapsed - 1)}]<br /> isEnabled: {this.props.isEnabled ? 'yepp' : 'nope'}<br /> triggerAfterSeconds: {this.props.triggerAfterSeconds}<br /> numberOfTriggers: {this.props.triggers.length}<br /> secondsElapsed: {this.state.secondsElapsed}<br /> secondsBeforeReload: {this.props.triggerAfterSeconds - this.state.secondsElapsed}<br /> -------------------------<br /> <Link signal={signals.app.reload.reloadingDisabled}>clickmeto_<b>disable</b>_reloading</Link><br /> --<br /> <Link signal={signals.app.reload.reloadingEnabled}>clickmeto_<b>enable</b>_reloading</Link><br /> --<br /> <Link signal={signals.app.reload.reloadingToggled}>clickmeto_<b>toggle</b>_reloading</Link><br /> -------------------------<br /> <a onClick={(e) => this.triggerNow(e)}>clickmeto_<b>trigger_NOW</b></a><br /> -------------------------<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 10}}>clickmeto_reload_@<b>10_seconds</b></Link><br /> --<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 20}}>clickmeto_reload_@<b>20_seconds</b></Link><br /> --<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 30}}>clickmeto_reload_@<b>30_seconds</b></Link><br /> --<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 60}}>clickmeto_reload_@<b>60_seconds</b></Link><br /> ====<br /> <i>designed by pbit</i> </pre> </div> ) } } // Model AutoReload.propTypes = { isEnabled: React.PropTypes.bool, triggerAfterSeconds: React.PropTypes.number, signals: React.PropTypes.object, triggers: React.PropTypes.array } AutoReload.defaultProps = { triggers: [] } // Binding const StatefullAutoReload = HOC(AutoReload, { isEnabled: ['app', 'reload', 'isEnabled'], triggerAfterSeconds: ['app', 'reload', 'triggerAfterSeconds'] }) // API export default StatefullAutoReload
burning-duck/twibral
src/ui/components/AutoReload/index.js
JavaScript
mit
3,914
31.347107
139
0.598876
false
#!/bin/bash #SBATCH --partition=mono #SBATCH --ntasks=1 #SBATCH --time=4-0:00 #SBATCH --mem-per-cpu=8000 #SBATCH -J Deep-RBM_DBM_4_inc_bin_PARAL_base #SBATCH -e Deep-RBM_DBM_4_inc_bin_PARAL_base.err.txt #SBATCH -o Deep-RBM_DBM_4_inc_bin_PARAL_base.out.txt source /etc/profile.modules module load gcc module load matlab cd ~/deepLearn && srun ./deepFunction 4 'RBM' 'DBM' '128 1000 1500 10' '0 1 1 1' '4_inc_bin' 'PARAL_base' "'iteration.n_epochs', 'learning.lrate', 'learning.cd_k', 'learning.persistent_cd', 'parallel_tempering.use'" '200 1e-3 1 0 1' "'iteration.n_epochs', 'learning.persistent_cd'" '200 1'
aciditeam/matlab-ts
jobs/deepJobs_RBM_DBM_4_inc_bin_PARAL_base.sh
Shell
mit
619
40.333333
297
0.696284
false
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Task Management System</title> <!-- Bootstrap Core CSS --> <link href="<?=base_url()?>assets/css/bootstrap.min.css" rel="stylesheet"> <!-- MetisMenu CSS --> <link href="<?=base_url()?>assets/css/metisMenu.min.css" rel="stylesheet"> <!-- DataTables CSS --> <link href="<?=base_url()?>assets/css/dataTables.bootstrap.css" rel="stylesheet"> <link href="<?=base_url()?>assets/css/bootstrap-editable.css" rel="stylesheet"> <!-- Custom CSS --> <link href="<?=base_url()?>assets/css/main.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="<?=base_url()?>assets/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <!-- Custom tab icons --> <link rel="shortcut icon" href="<?=base_url()?>assets/images/favicon.ico" type="image/x-icon"> <link href="<?=base_url()?>assets/js/jquery-ui-1.11.4.custom/jquery-ui.css" rel="stylesheet" type="text/css" /> <link href="<?=base_url()?>assets/js/jquery-ui-1.11.4.custom/jquery-ui-custom-datepicker.css" rel="stylesheet" type="text/css" /> <input type="hidden" id="base-url" value="<?=base_url()?>"/> <input type="hidden" id="current-page" value=""/> <input type="hidden" id="current-status-filter" value=""/> <input type="hidden" id="current-page-child" value=""/> <input type="hidden" id="current-parentID" value=""/> <input type="hidden" id="current-status-filter-child" value=""/> <input type="hidden" id="current-child-parentID" value=""/> <style> .inline-block{display:inline-block;} </style> </head> <body> <div id="wrapper"> <!-- Navigation --> <nav class="navbar navbar-inverse navbar-static-top text-center" role="navigation" style="margin-bottom: 0"> <div class="navbar-header"> <a class="navbar-brand" href="<?=base_url();?>"> <div class="inline"> Welcome to Streamfream Task Management System </div> </a> </div> </nav> <!-- /.navbar-header --> <!-- /.navbar-top-links -->
rudiliu/task_management
application/views/frame/header_view.php
PHP
mit
2,394
33.710145
133
0.588972
false
<!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/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="css/style.css" /> <title>Test Users Roles Demote</title> </head> <body> <?php require_once('test-util.php'); require_once(dirname(__FILE__) . '/../lib/ca-main.php'); echo '<div class="apitest">'; echo '<h1>users_roles_demote</h1>'; $ca = new CityApi(); $ca->debug = true; $ca->json = true; $userid = 238801; $roleid = 986632; $args = array('title' => 'Participant'); $results = $ca->users_roles_demote($userid, $roleid, $args); echo '<h2>Formatted JSON results: </h2>'; echo '<pre>'; echo format_json($results); echo '</pre>'; echo '</div>'; ?> </body> </html>
johnroberts/thecity-admin-php
test/test-users-roles-demote.php
PHP
mit
861
22.27027
121
0.645761
false
# coffeehaus A coffeescript shop for JVM locals. ## /!\ Extraction in progress This library is the extraction of the coffeescript compiler used in [coffeescripted-sbt](https://github.com/softprops/coffeescripted-sbt) for use as a standalone library ## install (todo) ## usage This library provides scala interfaces for compiling [vanilla][vanilla] and [iced][iced] CoffeeScript. It uses the versions `1.6.3` and `1.6.3-b` respectively. To compile vanilla coffeescript ```scala coffeehaus.Compile.vanilla()("alert 'vanilla'") ``` or simply ```scala coffeehaus.Compile("alert 'vanilla'") ``` To compile iced coffeescript ```scala coffeehaus.Compile.iced()("alert 'iced'") ``` These will return a `Either[coffeehaus.CompilerError, String]` with the compiled source. Don't have time to wait while your coffee's being brewed? Try moving to the side of the counter. ```scala import coffeehaus.Compile import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future Future(Compile("alert 'vanilla'")).map { coffee => Thread.sleep(1000) coffee.fold(println, println) } println("checkin' my tweets") ``` ### Be Your Own Barista This library will always make a best attempt at providing interfaces to the latest coffeescript compilers. That doesn't mean you can't experiment with your own brews ( other versions of coffeescript ) by extending `coffeehaus.Compile` providing a resource path to the source of the script. As an example the built-in vanilla coffeescript compiler is defined as follows ```scala Vanilla extends Compile("vanilla/coffee-script.js") ``` enjoy. Doug Tangren (softprops) 2013 [vanilla]: http://coffeescript.org/ [iced]: http://maxtaco.github.io/coffee-script/
softprops/coffeehaus
README.md
Markdown
mit
1,727
24.397059
137
0.759699
false
# Author: John Elkins <john.elkins@yahoo.com> # License: MIT <LICENSE> from common import * if len(sys.argv) < 2: log('ERROR output directory is required') time.sleep(3) exit() # setup the output directory, create it if needed output_dir = sys.argv[1] if not os.path.exists(output_dir): os.makedirs(output_dir) # log in and load personal library api = open_api() library = load_personal_library() def playlist_handler(playlist_name, playlist_description, playlist_tracks): # skip empty and no-name playlists if not playlist_name: return if len(playlist_tracks) == 0: return # setup output files playlist_name = playlist_name.replace('/', '') open_log(os.path.join(output_dir,playlist_name+u'.log')) outfile = codecs.open(os.path.join(output_dir,playlist_name+u'.csv'), encoding='utf-8',mode='w') # keep track of stats stats = create_stats() export_skipped = 0 # keep track of songids incase we need to skip duplicates song_ids = [] log('') log('============================================================') log(u'Exporting '+ unicode(len(playlist_tracks)) +u' tracks from ' +playlist_name) log('============================================================') # add the playlist description as a "comment" if playlist_description: outfile.write(tsep) outfile.write(playlist_description) outfile.write(os.linesep) for tnum, pl_track in enumerate(playlist_tracks): track = pl_track.get('track') # we need to look up these track in the library if not track: library_track = [ item for item in library if item.get('id') in pl_track.get('trackId')] if len(library_track) == 0: log(u'!! '+str(tnum+1)+repr(pl_track)) export_skipped += 1 continue track = library_track[0] result_details = create_result_details(track) if not allow_duplicates and result_details['songid'] in song_ids: log('{D} '+str(tnum+1)+'. '+create_details_string(result_details,True)) export_skipped += 1 continue # update the stats update_stats(track,stats) # export the track song_ids.append(result_details['songid']) outfile.write(create_details_string(result_details)) outfile.write(os.linesep) # calculate the stats stats_results = calculate_stats_results(stats,len(playlist_tracks)) # output the stats to the log log('') log_stats(stats_results) log(u'export skipped: '+unicode(export_skipped)) # close the files close_log() outfile.close() # the personal library is used so we can lookup tracks that fail to return # info from the ...playlist_contents() call playlist_contents = api.get_all_user_playlist_contents() for playlist in playlist_contents: playlist_name = playlist.get('name') playlist_description = playlist.get('description') playlist_tracks = playlist.get('tracks') playlist_handler(playlist_name, playlist_description, playlist_tracks) if export_thumbs_up: # get thumbs up playlist thumbs_up_tracks = [] for track in library: if track.get('rating') is not None and int(track.get('rating')) > 1: thumbs_up_tracks.append(track) # modify format of each dictionary to match the data type # of the other playlists thumbs_up_tracks_formatted = [] for t in thumbs_up_tracks: thumbs_up_tracks_formatted.append({'track': t}) playlist_handler('Thumbs up', 'Thumbs up tracks', thumbs_up_tracks_formatted) if export_all: all_tracks_formatted = [] for t in library: all_tracks_formatted.append({'track': t}) playlist_handler('All', 'All tracks', all_tracks_formatted) close_api()
soulfx/gmusic-playlist
ExportLists.py
Python
mit
3,890
29.873016
83
0.618766
false
require "./test/test_helper" require "pinker/rule" include Pinker regarding "remember helps gather up things that get returned if the rule is valid." do class Request def initialize(path_info, query_string=nil) @path_info = path_info @query_string = query_string end end test "stick things in memory, return them with a successful result" do rule = RuleBuilder.new(Request) { declare("Path must have at least three sections"){@path_info.split("/").length>=3} remember { |memory| memory[:resource_type] = @path_info.split("/")[2] } }.build assert{ rule.apply_to(Request.new("/v1/widgets/foo")).memory == {:resource_type => "widgets"} } end test "disregard the results of remembers" do rule = RuleBuilder.new(Request) { remember { |memory, context| memory[:x] = "y" nil #caused explosions at one time } }.build assert{ rule.apply_to(Request.new("/v1/widgets/foo")).memory == {:x => "y"} } end test "cache useful things across calls using context" do the_rule = RuleBuilder.new(Request) { declare("Path must have at least three sections") { |call, context| (context[:path_parts]=@path_info.split("/")).length>=3 } with_rule(:text_is_widgets){|rule, context|rule.apply_to(context[:path_parts][2])} rule(:text_is_widgets) { declare("Must be widgets"){self=="widgets"} } remember { |memory, context| memory[:resource_type] = context[:path_parts][2] } }.build assert{ the_rule.apply_to(Request.new("/v1/widgets/foo")).satisfied? } assert{ the_rule.apply_to(Request.new("/v1/widgets/foo")).memory == {:resource_type => "widgets"} } end test "if a remember fails and nothing else has, bubble up the error" do rule = RuleBuilder.new(Request) { declare { |call, context| (context[:path_parts]=@path_info.split("/")).length>=3 || call.fail("Path must have at least three sections") } remember { |memory, context| raise StandardError.new("blam!") } }.build assert{ rescuing{ rule.apply_to(Request.new("/v1/widgets/foo")) }.message == "blam!" } end test "if something else has already failed, swallow the exception. this is a 'best effort'/completeness failure strategy." do rule = RuleBuilder.new(Request) { declare { |call, context| @path_info.split("/").length>=99 || call.fail("Path must have at least 99 sections") } remember { |memory, context| raise StandardError.new("blam!") } }.build assert{ rescuing{ rule.apply_to(Request.new("/v1/widgets/foo")) }.nil? } assert{ rule.apply_to(Request.new("/v1/widgets/foo")).problems.first.message == "Path must have at least 99 sections" } end test "merge together memory hashes from rules" do grammar = RuleBuilder.new(:foo) { rule(:a) { remember{|memory|memory[:a] = 1} with_rule(:b){|rule|rule.apply_to("y")} } rule(:b) { remember{|memory|memory[:b] = 2} } }.build assert{ grammar.apply_to("x").memory == {:a => 1, :b => 2} } end end
sconover/pinker
test/remember_test.rb
Ruby
mit
3,447
28.211864
128
0.56745
false
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // Why base-58 instead of standard base-64 encoding? // - Don't want 0OIl characters that look the same in some fonts and // could be used to create visually identical looking account numbers. // - A string with non-alphanumeric characters is not as easily accepted as an account number. // - E-mail usually won't line-break if there's no punctuation to break at. // - Double-clicking selects the whole number as one word if it's all alphanumeric. // #ifndef BITCOIN_BASE58_H #define BITCOIN_BASE58_H #include <string> #include <vector> #include "bignum.h" #include "key.h" #include "script.h" static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; // Encode a byte sequence as a base58-encoded string inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend) { CAutoBN_CTX pctx; CBigNum bn58 = 58; CBigNum bn0 = 0; // Convert big endian data to little endian // Extra zero at the end make sure bignum will interpret as a positive number std::vector<unsigned char> vchTmp(pend-pbegin+1, 0); reverse_copy(pbegin, pend, vchTmp.begin()); // Convert little endian data to bignum CBigNum bn; bn.setvch(vchTmp); // Convert bignum to std::string std::string str; // Expected size increase from base58 conversion is approximately 137% // use 138% to be safe str.reserve((pend - pbegin) * 138 / 100 + 1); CBigNum dv; CBigNum rem; while (bn > bn0) { if (!BN_div(&dv, &rem, &bn, &bn58, pctx)) throw bignum_error("EncodeBase58 : BN_div failed"); bn = dv; unsigned int c = rem.getulong(); str += pszBase58[c]; } // Leading zeroes encoded as base58 zeros for (const unsigned char* p = pbegin; p < pend && *p == 0; p++) str += pszBase58[0]; // Convert little endian std::string to big endian reverse(str.begin(), str.end()); return str; } // Encode a byte vector as a base58-encoded string inline std::string EncodeBase58(const std::vector<unsigned char>& vch) { return EncodeBase58(&vch[0], &vch[0] + vch.size()); } // Decode a base58-encoded string psz into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet) { CAutoBN_CTX pctx; vchRet.clear(); CBigNum bn58 = 58; CBigNum bn = 0; CBigNum bnChar; while (isspace(*psz)) psz++; // Convert big endian string to bignum for (const char* p = psz; *p; p++) { const char* p1 = strchr(pszBase58, *p); if (p1 == NULL) { while (isspace(*p)) p++; if (*p != '\0') return false; break; } bnChar.setulong(p1 - pszBase58); if (!BN_mul(&bn, &bn, &bn58, pctx)) throw bignum_error("DecodeBase58 : BN_mul failed"); bn += bnChar; } // Get bignum as little endian data std::vector<unsigned char> vchTmp = bn.getvch(); // Trim off sign byte if present if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80) vchTmp.erase(vchTmp.end()-1); // Restore leading zeros int nLeadingZeros = 0; for (const char* p = psz; *p == pszBase58[0]; p++) nLeadingZeros++; vchRet.assign(nLeadingZeros + vchTmp.size(), 0); // Convert little endian data to big endian reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size()); return true; } // Decode a base58-encoded string str into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58(str.c_str(), vchRet); } // Encode a byte vector to a base58-encoded string, including checksum inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn) { // add 4-byte hash check to the end std::vector<unsigned char> vch(vchIn); uint256 hash = Hash(vch.begin(), vch.end()); vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4); return EncodeBase58(vch); } // Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet) { if (!DecodeBase58(psz, vchRet)) return false; if (vchRet.size() < 4) { vchRet.clear(); return false; } uint256 hash = Hash(vchRet.begin(), vchRet.end()-4); if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) { vchRet.clear(); return false; } vchRet.resize(vchRet.size()-4); return true; } // Decode a base58-encoded string str that includes a checksum, into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58Check(str.c_str(), vchRet); } /** Base class for all base58-encoded data */ class CBase58Data { protected: // the version byte unsigned char nVersion; // the actually encoded data std::vector<unsigned char> vchData; CBase58Data() { nVersion = 0; vchData.clear(); } ~CBase58Data() { // zero the memory, as it may contain sensitive data if (!vchData.empty()) memset(&vchData[0], 0, vchData.size()); } void SetData(int nVersionIn, const void* pdata, size_t nSize) { nVersion = nVersionIn; vchData.resize(nSize); if (!vchData.empty()) memcpy(&vchData[0], pdata, nSize); } void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend) { SetData(nVersionIn, (void*)pbegin, pend - pbegin); } public: bool SetString(const char* psz) { std::vector<unsigned char> vchTemp; DecodeBase58Check(psz, vchTemp); if (vchTemp.empty()) { vchData.clear(); nVersion = 0; return false; } nVersion = vchTemp[0]; vchData.resize(vchTemp.size() - 1); if (!vchData.empty()) memcpy(&vchData[0], &vchTemp[1], vchData.size()); memset(&vchTemp[0], 0, vchTemp.size()); return true; } bool SetString(const std::string& str) { return SetString(str.c_str()); } std::string ToString() const { std::vector<unsigned char> vch(1, nVersion); vch.insert(vch.end(), vchData.begin(), vchData.end()); return EncodeBase58Check(vch); } int CompareTo(const CBase58Data& b58) const { if (nVersion < b58.nVersion) return -1; if (nVersion > b58.nVersion) return 1; if (vchData < b58.vchData) return -1; if (vchData > b58.vchData) return 1; return 0; } bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; } bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; } bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; } bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; } bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; } }; /** base58-encoded Bitcoin addresses. * Public-key-hash-addresses have version 0 (or 111 testnet). * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key. * Script-hash-addresses have version 5 (or 196 testnet). * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script. */ class CBitcoinAddress; class CBitcoinAddressVisitor : public boost::static_visitor<bool> { private: CBitcoinAddress *addr; public: CBitcoinAddressVisitor(CBitcoinAddress *addrIn) : addr(addrIn) { } bool operator()(const CKeyID &id) const; bool operator()(const CScriptID &id) const; bool operator()(const CNoDestination &no) const; }; class CBitcoinAddress : public CBase58Data { public: enum { PUBKEY_ADDRESS = 25, // Basecoin: address begin with 'B' SCRIPT_ADDRESS = 8, PUBKEY_ADDRESS_TEST = 111, SCRIPT_ADDRESS_TEST = 196, }; bool Set(const CKeyID &id) { SetData(fTestNet ? PUBKEY_ADDRESS_TEST : PUBKEY_ADDRESS, &id, 20); return true; } bool Set(const CScriptID &id) { SetData(fTestNet ? SCRIPT_ADDRESS_TEST : SCRIPT_ADDRESS, &id, 20); return true; } bool Set(const CTxDestination &dest) { return boost::apply_visitor(CBitcoinAddressVisitor(this), dest); } bool IsValid() const { unsigned int nExpectedSize = 20; bool fExpectTestNet = false; switch(nVersion) { case PUBKEY_ADDRESS: nExpectedSize = 20; // Hash of public key fExpectTestNet = false; break; case SCRIPT_ADDRESS: nExpectedSize = 20; // Hash of CScript fExpectTestNet = false; break; case PUBKEY_ADDRESS_TEST: nExpectedSize = 20; fExpectTestNet = true; break; case SCRIPT_ADDRESS_TEST: nExpectedSize = 20; fExpectTestNet = true; break; default: return false; } return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize; } CBitcoinAddress() { } CBitcoinAddress(const CTxDestination &dest) { Set(dest); } CBitcoinAddress(const std::string& strAddress) { SetString(strAddress); } CBitcoinAddress(const char* pszAddress) { SetString(pszAddress); } CTxDestination Get() const { if (!IsValid()) return CNoDestination(); switch (nVersion) { case PUBKEY_ADDRESS: case PUBKEY_ADDRESS_TEST: { uint160 id; memcpy(&id, &vchData[0], 20); return CKeyID(id); } case SCRIPT_ADDRESS: case SCRIPT_ADDRESS_TEST: { uint160 id; memcpy(&id, &vchData[0], 20); return CScriptID(id); } } return CNoDestination(); } bool GetKeyID(CKeyID &keyID) const { if (!IsValid()) return false; switch (nVersion) { case PUBKEY_ADDRESS: case PUBKEY_ADDRESS_TEST: { uint160 id; memcpy(&id, &vchData[0], 20); keyID = CKeyID(id); return true; } default: return false; } } bool IsScript() const { if (!IsValid()) return false; switch (nVersion) { case SCRIPT_ADDRESS: case SCRIPT_ADDRESS_TEST: { return true; } default: return false; } } }; bool inline CBitcoinAddressVisitor::operator()(const CKeyID &id) const { return addr->Set(id); } bool inline CBitcoinAddressVisitor::operator()(const CScriptID &id) const { return addr->Set(id); } bool inline CBitcoinAddressVisitor::operator()(const CNoDestination &id) const { return false; } /** A base58-encoded secret key */ class CBitcoinSecret : public CBase58Data { public: void SetSecret(const CSecret& vchSecret, bool fCompressed) { assert(vchSecret.size() == 32); SetData(128 + (fTestNet ? CBitcoinAddress::PUBKEY_ADDRESS_TEST : CBitcoinAddress::PUBKEY_ADDRESS), &vchSecret[0], vchSecret.size()); if (fCompressed) vchData.push_back(1); } CSecret GetSecret(bool &fCompressedOut) { CSecret vchSecret; vchSecret.resize(32); memcpy(&vchSecret[0], &vchData[0], 32); fCompressedOut = vchData.size() == 33; return vchSecret; } bool IsValid() const { bool fExpectTestNet = false; switch(nVersion) { case (128 + CBitcoinAddress::PUBKEY_ADDRESS): break; case (128 + CBitcoinAddress::PUBKEY_ADDRESS_TEST): fExpectTestNet = true; break; default: return false; } return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1)); } bool SetString(const char* pszSecret) { return CBase58Data::SetString(pszSecret) && IsValid(); } bool SetString(const std::string& strSecret) { return SetString(strSecret.c_str()); } CBitcoinSecret(const CSecret& vchSecret, bool fCompressed) { SetSecret(vchSecret, fCompressed); } CBitcoinSecret() { } }; #endif
basecoin/basecoin
src/base58.h
C
mit
13,111
27.502174
140
0.602242
false
/* Client-side router settings */ Router.configure({ layoutTemplate:"layout", notFoundTemplate:"page_not_found", loadingTemplate:"loading" }); Router.route("/", { name:"home", template:"home" }); Router.route("/profile", { name:"profile", template:"profile" }); Router.route("/admin", { name:"admin", template:"admin" }); Router.route("/user/:_id", { name:"user", template:"user", data: function(){ return Meteor.users.findOne({_id: this.params._id}); } });
RadioRevolt/DABelFish
client/router.js
JavaScript
mit
494
15.466667
57
0.625506
false
/*--------------------------------------------------------------------------------- Name : amixer.c Author : Marvin Raaijmakers Description : Plugin for keyTouch that can change the volume (using amixer). Date of last change: 24-Sep-2006 History : 24-Sep-2006 Added two new plugin functions: "Volume increase 10%" and "Volume decrease 10%" 05-Mar-2006 - clean_exit() will be used to exit the client process, that manages the volume bar, cleanly - update_window() now returns a boolean indicating if the function should be called again 29-Jan-2006 Added the GUI volume bar to the plugin Copyright (C) 2005-2006 Marvin Raaijmakers 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 2 of the License, or 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -----------------------------------------------------------------------------------*/ #define _GNU_SOURCE #include <stdlib.h> #include <signal.h> #include <unistd.h> #include <gtk/gtk.h> #include <time.h> #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <string.h> #include <plugin.h> #include <amixer-plugin.h> void vol_increase (KTPreferences *preferences); void vol_decrease (KTPreferences *preferences); void vol_increase_10 (KTPreferences *preferences); void vol_decrease_10 (KTPreferences *preferences); void mute (KTPreferences *preferences); static void create_window (VOLUMEBAR_INFO *volumebar_info); static int get_current_volume (void); static void update_volume_bar (GtkWidget *volume_bar); static gboolean update_window (VOLUMEBAR_INFO *volumebar_info); static void clean_exit (int sig); static void start_window (void); static char *get_keytouch_user_dir (void); static void change_volume (char *command); static Boolean is_muted = FALSE; KeytouchPlugin plugin_struct = { {"Amixer", "Marvin Raaijmakers", "GPL 2", "2.3", "This plugin allows you to change the volume. It also shows\n" "the current volume when it changes. To use this plugin amixer\n" "needs to be installed."}, "amixer.so", 5, {{"Volume increase", KTPluginFunctionType_Function, {.function = vol_increase}}, {"Volume decrease", KTPluginFunctionType_Function, {.function = vol_decrease}}, {"Volume increase 10%", KTPluginFunctionType_Function, {.function = vol_increase_10}}, {"Volume decrease 10%", KTPluginFunctionType_Function, {.function = vol_decrease_10}}, {"Mute", KTPluginFunctionType_Function, {.function = mute}}, } }; void create_window (VOLUMEBAR_INFO *volumebar_info) /* Input: - Output: volumebar_info - The window element points to the created window and the volume_bar element points to the volume progressbar in the window Returns: - Description: This function creates a window with a progressbar with the following properties: - It is positioned in the center ot the screen. - It has no window decorations and can not be resized by the user. - It will allways be above other windows. - It is visible on all desktops. - It will not be visible in the taskbar an pager. - It does not accept focus. */ { volumebar_info->window = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_window_set_position (GTK_WINDOW (volumebar_info->window), GTK_WIN_POS_CENTER); gtk_window_set_resizable (GTK_WINDOW (volumebar_info->window), FALSE); gtk_window_set_decorated (GTK_WINDOW (volumebar_info->window), FALSE); /* The window will allways be above others */ gtk_window_set_keep_above (GTK_WINDOW (volumebar_info->window), TRUE); /* Let the window be visible on all desktops: */ gtk_window_stick (GTK_WINDOW (volumebar_info->window)); /* This window will not be visible in the taskbar: */ gtk_window_set_skip_taskbar_hint (GTK_WINDOW (volumebar_info->window), TRUE); /* This window will not be visible in the pager: */ gtk_window_set_skip_pager_hint (GTK_WINDOW (volumebar_info->window), TRUE); gtk_window_set_accept_focus (GTK_WINDOW (volumebar_info->window), FALSE); volumebar_info->volume_bar = gtk_progress_bar_new(); gtk_widget_show (volumebar_info->volume_bar); gtk_container_add (GTK_CONTAINER (volumebar_info->window), volumebar_info->volume_bar); gtk_widget_set_size_request (volumebar_info->volume_bar, 231, 24); gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (volumebar_info->volume_bar), 0.52); gtk_progress_bar_set_pulse_step (GTK_PROGRESS_BAR (volumebar_info->volume_bar), 0.02); gtk_progress_bar_set_text (GTK_PROGRESS_BAR (volumebar_info->volume_bar), "Volume"); } int get_current_volume (void) /* Returns: The current volume retrieved from amixer. -1 will be returned when retrieving the volume failed. */ { FILE *amixer; char c; int volume = -1; amixer = popen ("amixer sget Master | grep \"Front Left:\"", "r"); if (amixer) { do { c = getc(amixer); /* We have found the volume when the following appears: * '[' followed by an integer followed by '%' */ if (c == '[' && fscanf(amixer, "%d", &volume) && (c = getc(amixer)) == '%') { break; } volume = -1; } while (c != '\n' && c != EOF); pclose (amixer); } return (volume); } void update_volume_bar (GtkWidget *volume_bar) /* Output: volume_bar - Will show the percentage of the current volume */ { int volume; gchar *text; volume = get_current_volume(); if (volume && volume != -1) { text = g_strdup_printf("Volume %d%%", volume); if (text) { gtk_progress_bar_set_text (GTK_PROGRESS_BAR(volume_bar), text); g_free (text); } } else { volume = 0; gtk_progress_bar_set_text (GTK_PROGRESS_BAR(volume_bar), "Muted"); } gtk_progress_set_percentage (GTK_PROGRESS(volume_bar), (gdouble)volume/100.0); /* Directly draw the progressbar: */ while (g_main_context_iteration(NULL, FALSE)) ; /* NULL Statement */ } gboolean update_window (VOLUMEBAR_INFO *volumebar_info) /* Input: volumebar_info->close_time - The time to close the window Output: volumebar_info - Will be updated Returns: TRUE if this function should be called again after UPDATE_INTERVAL miliseconds, otherwise FALSE. Description: This function destroys volumebar_info->window and escapes from the GTK main routine if the current time is later than volumebar_info->close_time. If not then the volume bar will be updated with the current volume. */ { MSGBUF msg; Boolean close_window; /* Check if there is a new message on the queue */ if (msgrcv(volumebar_info->msgqid, &msg, sizeof(msg.time), 1, IPC_NOWAIT) != -1) { volumebar_info->close_time = msg.time + SHOW_WINDOW_TIME; } close_window = (time(NULL) > volumebar_info->close_time); if (!close_window) { update_volume_bar (volumebar_info->volume_bar); } else { gtk_widget_destroy (volumebar_info->window); gtk_main_quit(); } return !close_window; } void start_window (void) /* Description: This function creates a window with a volume bar and shows it SHOW_WINDOW_TIME seconds when it receives a message on the message queue. The key of the message queue is generated by running ftok(get_keytouch_user_dir(), MSGQ_AMIXER_PROJ_ID). The messages that are sent to this queue should contain the time they are sent. The volume window will be showed from the time this function receives the message, until the time the message was sent plus SHOW_WINDOW_TIME seconds. */ { MSGBUF msg; VOLUMEBAR_INFO volumebar_info; key_t msgq_key; char *keytouch_user_dir; gtk_init (0, NULL); keytouch_user_dir = get_keytouch_user_dir(); /* Get the key for the message queue */ msgq_key = ftok(keytouch_user_dir, MSGQ_AMIXER_PROJ_ID); free (keytouch_user_dir); if (msgq_key == -1) { perror ("keytouch amixer plugin"); return; } /* Get the message queue identifier and create the queue if necessary */ volumebar_info.msgqid = msgget(msgq_key, 0); if (volumebar_info.msgqid == -1) { perror ("keytouch amixer plugin"); return; } while (1) { if (msgrcv(volumebar_info.msgqid, &msg, sizeof(msg.time), 1, 0) != -1) { volumebar_info.close_time = msg.time + SHOW_WINDOW_TIME; if (time(NULL) <= volumebar_info.close_time) { create_window (&volumebar_info); update_volume_bar (volumebar_info.volume_bar); gtk_widget_show (volumebar_info.window); g_timeout_add (UPDATE_INTERVAL, (GSourceFunc) update_window, &volumebar_info); gtk_main(); } } } } char *get_keytouch_user_dir (void) /* Returns: The address of some new allocated space which is a string containing the value of the environment variable HOME followed by "/.keytouch2". */ { char *keytouch_dir, *home; home = getenv("HOME"); if (home == NULL) { fputs ("keytouch amixer plugin: could not get environment variable $HOME", stderr); exit (EXIT_FAILURE); } if (asprintf(&keytouch_dir, "%s/.keytouch2", home) == -1) { fputs ("keytouch amixer plugin: asprintf() failed. " "This is probably caused because it failed to allocate memory.", stderr); exit (EXIT_FAILURE); } return (keytouch_dir); } void clean_exit (int sig) { exit (EXIT_SUCCESS); } void send_volume_changed_signal (void) /* Description: This function sends a signal to the child program that manages the volumebar. The child will receive the signal and will show the volumebar. The child process will be created if it does not exist yet. */ { static int qid = -1; MSGBUF msg; /* If this is the first time this function was called */ if (qid == -1) { key_t msgq_key; char *keytouch_user_dir; keytouch_user_dir = get_keytouch_user_dir(); /* Get the key for the message queue */ msgq_key = ftok(keytouch_user_dir, MSGQ_AMIXER_PROJ_ID); free (keytouch_user_dir); if (msgq_key == -1) { perror ("keytouch amixer plugin"); return; } /* Get the message queue identifier and create the queue if necessary */ qid = msgget(msgq_key, MSGQ_PERMISSIONS | IPC_CREAT); if (qid == -1) { perror ("keytouch amixer plugin"); return; } if (fork() == 0) { /* Trap key signals */ signal (SIGINT, clean_exit); signal (SIGQUIT, clean_exit); signal (SIGTERM, clean_exit); /* We will now start the run_window() function in our * child process for showing a volume bar to the user */ start_window(); exit (EXIT_SUCCESS); /* We will never get here because of * the infinite loop in run_window() */ } } msg.mtype = 1; msg.time = time(NULL); if (msgsnd(qid, &msg, sizeof(msg.time), 0) == -1) { perror ("keytouch amixer plugin"); } } void change_volume (char *command) /* Input: command - The command that changes the volume. Description: This function executes 'command' in a child process and then calls send_volume_changed_signal(). */ { if (fork() == 0) { execlp ("sh", "sh", "-c", command, NULL); exit (EXIT_SUCCESS); } else { send_volume_changed_signal(); } } void vol_increase (KTPreferences *preferences) { is_muted = FALSE; change_volume ( CHANGE_VOL_CMD(VOL_DEFAULT_INCR) ); } void vol_decrease (KTPreferences *preferences) { is_muted &= !get_current_volume(); change_volume ( CHANGE_VOL_CMD(VOL_DEFAULT_DECR) ); } void vol_increase_10 (KTPreferences *preferences) { is_muted = FALSE; change_volume ( CHANGE_VOL_CMD(VOL_10PERCENT_INCR) ); } void vol_decrease_10 (KTPreferences *preferences) { is_muted &= !get_current_volume(); change_volume ( CHANGE_VOL_CMD(VOL_10PERCENT_DECR) ); } void mute (KTPreferences *preferences) { static int prev_volume = -1; int current_volume; char *command = NULL; current_volume = get_current_volume(); is_muted &= !current_volume; if (is_muted) { /* Tell amixer to set the volume to prev_volume */ if (asprintf(&command, "amixer sset Master %d%% > /dev/null", prev_volume) == -1) { fputs ("keytouch amixer plugin: asprintf() failed. " "This is probably caused because it failed to allocate memory.", stderr); } } else if (current_volume) { /* Tell amixer to set the volume to 0 */ command = strdup("amixer sset Master 0% > /dev/null"); if (command == NULL) { perror ("keytouch amixer plugin"); } prev_volume = current_volume; } /* Do we have to mute/unmute? */ if (command) { if (fork() == 0) { execlp ("sh", "sh", "-c", command, NULL); exit (EXIT_SUCCESS); } else { send_volume_changed_signal(); } free (command); is_muted = !is_muted; } }
paulmadore/G-Keymap
Reference Code/keymap/keytouch-2.2.4/plugins/amixer.c
C
mit
13,098
26.808917
88
0.66911
false
<?php namespace S327at\L51blog\Models; use Illuminate\Database\Eloquent\Model; class Group extends Model { }
s327at/l51blog
src/Models/Group.php
PHP
mit
114
9.454545
39
0.763158
false
# Dokumenttien laatiminen Tämän ohjesivun sisältö: - Dokumentoinnin periaatteet - Uuden sivudokumentin laatiminen, muokkaaminen ja päivittäminen - Taulukoiden tekeminen piazzalla - Uuden tiedostodokumentin laatiminen, tiedoston nostaminen piazzalle, muokkaaminen ja päivittäminen - Dokumenttien linkitys - Kuvan liittäminen dokumenttiin - Dokumenttien poistaminen - Dokumenttien ja kansioiden muut tiedot Lue myös [dokumenttien ylläpito](dokumentin_yllapito) ja [Toimintaohjeet](toimintaohjeet). ---- ## Uuden dokumentin laatimisen periaatteita Jotta prosessidokumentit (prosessikaaviot, prosessikuvaukset, apteekkiohjeet, toimintaohjeet, kokousmuistiot, sisäisten arviointien muistiot) ovat ulkoasultaan yhdenmukaiset, niille kannattaa laatia jo prosessikehittämisen alussa **mallipohjat**. Tässä esimerkki prosessikuvauksen mallipohjasta, kun dokumentti laaditaan sivuna. ![Image](kuvat/toimintaohjeet.png) ---- Näin tunnistetiedot, fontit ja otsikot tulevat kohdalleen, eikä niitä tarvitse miettiä joka kerta erikseen. Dokumenttien yhtenäinen ulkoasu näyttää mukavalta, kertoo yhdenmukaisista toimintatavoista myös dokumentoinnissa. ---- Jos mallipohjat on jokaiselle dokumenttityypille, niille kannattaa laatia oman kansionsa Mallipohjat, josta pohjat löytyvät helposti. ![Image](kuvat/dokumenttienlaatiminen2.png) Kansioiden lisäämisestä ja ylläpidosta on [tarkempaa ohjetta](kansiot). ---- Dokumentteja voi laatia piazzalle kahdella tapaa: **joko suoraan sivuna** tai **nostaa liitetiedostona** (tiedostona vanha tapa). Nykyisin suositellaan, että kaikki perustekstit (Wordit, esim. kuvaukset, ohjeet ja muistiot) laaditaan sivuna, jolloin niiden hallinta on helpompaa ja yksinkertaisempaa.<br> Niitä pystyy muokkaamaan suoraan piazzalla, myös hakutoiminto etsii tekstin (esim. ohjeen) sisällöstä. Jos tekstissä on taulukko tai muita erikoismerkkejä, tekstit laaditaan teksinkäsittelyohjelmalla ja käsitellään piazzalla tiedostona, näin myös powerpoint-, pdf- ja excel-muotoiset. Käytännössä vain prosessikaaviot, mittarit ja koulutusmateriaali vaativat tiedostokäsittelyn, muut voidaan laatia helposti sivuna. ---- ## Uuden sivudokumentin laatiminen ja päivittäminen Käytettäessä mallipohjaa (suositus) avataan Mallipohja -kansio tai kansio, jossa mallipohja on. Valitaan kansion vihreästä valikosta **Sisältö** -> ruksataan pohja -> valitaan **Kopio**. ![Image](kuvat/uusisivudokumentti.png) Tämän jälkeen avataan kansio, johon pohja halutaan siirtää (laatia uusi dokumentti).<br> Valitaan vihreästä valikosta Sisältö -> valitaan **Leikkaa**, jolloin pohja kopioituu sopivaan kansioon. ---- Tämän jälkeen avataan siirretty pohja -> valitaan **Muokkaa -> muutetaan otsikko, tunnistetiedot** ym. Nyt pääset kirjoittamaan tekstiä. **Tallenna** aina välillä (alaosassa Tallenna). Sitten kun jatkat kirjoittamista, avaa dokumentti, valitse Muokkaa, muuta tarvittaessa pvm ja jatka kirjoittamista. Sitten kun dokumentti on valmis, se lähetetään [hyväksyttäväksi](dokumentin_yllapito/#dokumentin-hyvaksyminen). Päivitettäessä dokumenttia (dokumentti on jo hyväksytty) muuttuneet kohdat kirjoitetaan esim. kursiivilla tai miten muutokset on sovittu merkittäväksi. Kun dokumenttia muutetaan seuraavan kerran, kursiivit oikaistaan ja uudet muuttuneet kohdat kursiivilla. Kursiivia käytetään vasta kun dokumentit on hyväksytty. Muistetaan muuttaa aina myös päivämäärä ja laatija tarvittaessa.<br> Myös päivitetyt dokumentit lähetetään [hyväksyttäväksi](dokumentin_yllapito/#dokumentin-hyvaksyminen). Jos et käytä mallipohjaa, avaa kansio, johon haluat laatia dokumentin. Valitse valikosta **Lisää uusi** -> **Sivu**. Avaa sitten ko. sivu -> **Muokkaa** -> aloita kirjoittaminen. Uusi dokumentti menee alimmaiseksi. Voit siirtää sen haluamaasi paikkaan samalla tavalla kuin [kansioiden sisältöä järjestetään](kansiot/#kansion-sisallon-jarjestaminen-uudelleen). ---- ## Kuvaukset ja ohjeet aikaisemmin olleet tiedostoina Aikaisemmin käytäntönä oli, että dokumentit laadittiin tietokoneella tiedostoina, jotka nostettiin piazzalle.<br> Tämä käytäntö on kerrottu seuraavassa otsikossa. __Suositeltavaa on__, että dokumentin seuraavan päivityksen yhteydessä tekstit tehdään sivuina, jotta niiden käsittely jatkossa on helpompaa. Se tehdään näin: - Kopioi mallipohja ko. kansioon tai laadi uusi sivu edellä kuvatun mukaisesti. - Avaa päivitettävä tiedosto. - Maalaa teksti alusta loppuun (yläotsikkoa ei pysty maalaamaan ainakaan helposti), vie se leikepöydälle (contrl c). - Avaa äsken tehty sivu, valitse muokkaa, vie kursori tekstikenttään ja liitä tiedoston teksti (control w), jolloin teksti siirtyy sivulle. Lopuksi tallenna. - Tarvittaessa poista ylimääräiset rivit, lihavoi/kursivoi sekä kirjoita päivitettävä teksti ja lopuksi tallenna. - Poista vanha tiedosto. Siirtymisen tiedostoista voi tehdä myös "urakkana", esim. joku keskitetysti tekee siirrot. Muistetaan muuttaa tekijät oikeiksi. ---- ## Uuden tiedostodokumentin laatiminen - Avataan mallipohja -> tallennetaan se tietokoneelle (esim. työpöydälle) mahdollisimman kuvaavalla lyhyellä nimellä. - Muutetaan tunnistetiedot ja jatketaan kirjoittamista tekstinkäsittelyohjelmalla. - Tallennuksen jälkeen tiedosto siirretään piazzalle. - Myös keskeneräiset kannattaa nostaa piazzalle. ### Tiedoston nostaminen piazzalle Avataan kansio, johon tiedosto halutaan liittää.<br> Valitaan vihreästä valikosta **Lisää uusi** -> **Tiedosto**. ![Image](kuvat/kuva-120.png) Kirjoitetaan nimikkeeksi tiedoston nimi. Kuvaus ei ole pakollinen, mutta suositeltava. Siinä voi hieman tarkentaa mitä tämä liitetiedosto pitää sisällään tai jotain muuta siihen liittyvää tietoa. Varsinainen tiedosto poimitaan omalta koneelta **Browse** tai **Selaa** -toiminnolla. Lopuksi **Tallenna**, jolla tiedosto siirtyy fyysisesti piazzalle.<br> Työpöydältä käydään poistamassa tiedosto, jotta sinne ei kerry tiedostoja. ### Tiedoston muokkaaminen ja täydentäminen Tiedostoja ei voi muokata suoraan piazzalla, vaan ne on aina tehtävä tekstinkäsittelyohjelmalla. Suositeltavaa on, että päivitettävä tiedosto avataan piazzalla, jotta päivitetään viimeisintä versiota. Tiedosto tallennetaan tietokoneelle ja tehdään muutokset koneelle. Jos tiedostodokumentti on jo hyväksytty, muuttuneet kohdat esim. kursiivilla tai miten muutokset on sovittu merkittäväksi. Muistetaan muuttaa aina myös päivämäärä ja laatija tarvittaessa. Päivitetty tiedosto mostetaan piazzalle seuraavasti: - Avataan päivitettävä tiedosto - Valitaan **Muokkaa** - Valitaan **Korvaa uudella tiedostolla**, haetaan tiedosto koneelta, lopuksi **Tallenna**. ![Image](kuvat/kuva-126.png) ![Image](kuvat/kuva-121.png) ![Image](kuvat/kuva-123.png) ---- ## Taulukoiden laatiminen Piazzalla voi laatia myös taulukoita joko omiksi dokumenteikseen (esim. koulukortit, projektisuunnitelmat) tai taulukoita sivudokumenttien tekstiin. Taulukon laatiminen tekstidokumenttiin tehdään Muokkaa-tilassa: - Mene dokumentissa kohtaan, johon haluat taulukon - Valitse ylläolevasta valikosta taulukko - Lisää sarakkeiden ja rivien määrä - Tallenna tai täytä taulokkoa samantien Jos laaditaan taulukkodokumentteja (esim. koulutuskortteja), tehdään näin: - Lisää uusi sivu - Kirjoita Nimike ja lisää tekstiin (kommentti) taulukko em. opastuksen mukaisesti Taulukossa ei ole kaikkia excelin hienouksia, mutta perustaulukon tekemiseen varsin kätevä, esim.rivejä ja sarakkeita on helppo lisätä tai poistaa. ## Dokumenttien linkitys Piazzalla on mahdollista myös dokumenttien linkitys, esim. asiakastyytyväisyystutkimus markkinoinnin ja asiakaspalveluprosessien mittarina tai halutaan linkittää dokumenttia sivulta toiselle. Ylläpidon hallinnan kannalta on tärkeää, että dokumentti on vain yhdessä paikassa. Linkitys voidaan tehdä kahdella tavalla. ### Linkitys sivulta dokumenttiin !!! note "Huom" Linkitys ei toimi Internet Explorerilla.<br> Käytä Mozilla Firefoxia tai Google Chromea linkkien lisäämiseen. Sivueditorin (tekstieditorin) tulee olla muotoa [TinyMCE](sivueditorit/#tinymce-editori).<br> Näkyy ja muutetaan tarvittaessa piazzan pääsivulla Asetukset. * Avataan/lisätään sivudokumentti, johon linkitys halutaan. * Valitaan **Muokkaa**, "maalataan" linkitettävä sana/-t, valitaan editoripalkista **Lisää/muuta linkki** (ketju). * Näyttöön avautuu Lisää/muokkaa -näkymä. * Jos halutaan linkittää piazzalla oleva dokumentti, valitaan sisäisestä linkitettävä dokumentti, eli avataan kansioita niin pitkälle, että dokumentti löytyy. * Ruksataan linkitettävä dokumentti ja lopuksi OK. Linkitys näkyy dokumentissa alleviivauksena. * Vastaavasti linkitetään ulkoinen linkki (nettisvu). Tällä tavalla on erityisen helppoa linkittää sivuna laadittuun dokumenttiin muita dokumentteja, esim. kaikki toimintaohjeet toimintaohjeluetteloon. ![Image](kuvat/linkityssivultasivulle.png) ### Myös näin on mahdollista linkittää Etenkin aikaisemmin suosittiin tätä kategorisoinnin kautta tapahtuvaa linkitystä, joka tehdään näin. * Luodaan tai avataan sivu, johon linkitys halutaan. * Valitaan **Muokkaa**, valitaan "Kategorisointi", avautuvalta sivulta valitaan **Samasta aiheesta** ja **Lisää** -toiminnolla haetaan sopiva dokumentti linkitettäväksi avaamalla kansioita niin pitkälle, että dokumentti löytyy, ja lopuksi "Tallenna". * Makuasia kumpaako tapaa haluaa käyttää. ---- ## Kuvan liittäminen dokumenttiin Sivudokumenttiin on helppo liittää kuva esim. havainnollistaakseen tekstiä. Kuvia voi lisätä tekstiin näin (ensin kuva haetaan piazzalle omaan kansioon): - Avaa oma kansio (löytyy ylhäältä oikealta) - Lisää uusi kuva, hae se tietokoneeltasi ja lopuksi tallenna (siis jos kuvaa ei ole piazzalla) - Avaa dokumentti, johon haluat liittää kuvan. Valitse Muokkaa ja mene siihen kohtaan, johon haluat kuvan. - Valitse ylläolevasta valikosta vasemmasta laidasta ”kuvaruutu” (lisää/muuta kuva). - Valitse näkymän oikeasta kulmasta keskimmäinen List view. - Valitse Pääsivu, jolloin näkyviin tulee kansiorakenteenne piazzalla. - Valitse sieltä Käyttäjät -> oma kansiosi ja sieltä valitse kuva ja lopuksi ok - Ja ihan viimeiseksi tallenna ko. dokumentti. Jos kuva on jo piazzalla, liitä kuva näin: - Avaa dokumentti, johon haluat liittää kuvan. Valitse Muokkaa ja mene siihen kohtaan, johon haluat kuvan. - Valitse ylläolevasta valikosta vasemmasta laidasta ”kuvaruutu” (lisää/muuta kuva). - Valitse näkymän oikeasta kulmasta keskimmäinen List view. - Valitse Pääsivu, jolloin näkyviin tulee kansiorakenteenne piazzalla. - Avaa kansio, jossa kuva on. Valitse kuva ja ok. - Lopuksi tallenna dokumentti. ---- ## Dokumenttien poistaminen Piazzan dokumentit ja liitetiedostot voidaan poistaa helposti, jos niitä ei enää tarvita tai ovat vanhentuneita, ja joku uusi dokumentti korvaa ne. Poisto voidaan tehdä monellakin tavalla, mutta yleisin on ottaa dokumentti ensin esiin, ja sen jälkeen avataan toiminnot -valikko, josta löytyy kohta **Poista**. ![Image](kuvat/kuva-137.png) Ennen varsinaista poistoa piazza vielä kysyy käyttäjältä varmistuksen poistolle. ---- ## Dokumenttien ja kansioiden muut tiedot **Muuokkaa** -tilassa on mahdollista antaa myös muita sisältöön liittyviä tietoja. Ruudulla on viisi __"välilehden"__ näköistä osioita, joista avautuu kyseiseen kansioon tai sisältöön liittyvää lisätietoa. ![Image](kuvat/kuva-127.png) * __Kategorisointi__ - Voidaan antaa sisällölle joitain avainsanoja, jotka ovat hyödyllisiä esim. haettaessa tietyntyyppisiä dokumentteja **Haku**-toiminnolla. - Sitä voidaan myös käyttää ns. älykansioissa hyödyksi, jolloin saadaan kaikki samantyyppiset dokumentit koottua __"loogiseen kansioon"__ vaikka ne fyysisesti olisivatkin hajallaan ympäri sisältörakennetta. * __Päivät__ - Voidaan antaa dokumentin julkaisemisen alkamis- ja päättymispäivät. - Tulee kyseeseen aika harvoin, mutta on mahdollista jos on joku tietyn ajan voimassa oleva dokumentti tai jos haluaa jukaista dokumentin tiettynä ajankohtana. * __Omistaja__ - _tärkeä_ - Täällä voidaan käydä vaihtamassa dokumentin omistaja- tai tekijä toiseksi. - Esim. tilanteessa jossa vastuu dokumentin tai kansion sisällöstä siirretään toiselle henkilölle, kts. [tekijän muuttaminen](kansiot/#kansion-tekijan-muuttaminen). * __Asetukset__ - Oletusarvona, että kommentointi sallittua. ![Image](kuvat/kuva-125.png) ----
netmiller/piazzadoc
sivut/dokumentin_tekeminen.md
Markdown
mit
12,723
42.14386
312
0.813679
false
package com.calebmeyer.bettercrafting.creativetab; import com.calebmeyer.bettercrafting.constants.Project; import com.calebmeyer.bettercrafting.initialization.ModItems; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; public class CreativeTabBCT { public static final CreativeTabs BETTER_CRAFTING_TABLES_TAB = new CreativeTabs(Project.MOD_ID) { /** * This method returns an item, whose icon is used for this creative tab * * @return an item to use for the creative tab's icon */ @Override public Item getTabIconItem() { return ModItems.craftingPanel; } /** * Gets the label for this creative tab. * * @return the label */ @Override public String getTranslatedTabLabel() { return Project.MOD_NAME; } }; }
calebmeyer/Better-Crafting-Tables
src/main/java/com/calebmeyer/bettercrafting/creativetab/CreativeTabBCT.java
Java
mit
907
27.34375
100
0.638368
false
//Change class of "Home" and "About" function setActive() { document.getElementById("about").className += "active" document.getElementById("home").setAttribute('class','no') }
losko/CodeNameSite
public/js/helper.js
JavaScript
mit
184
35.8
62
0.701087
false
<?php class PostModel extends CI_Model { public $id; public $title; public $content; public $date; public $author; public $upvotes = 0; public $downvotes = 0; public $voters; public function __construct() { parent::__construct(); } public function GetAll() { $this->db->order_by('date', 'desc'); $query = $this->db->get('posts'); return $query->result(); } public function GetByID($id) { $query = $this->db->get_where('posts', array('id' => $id)); return $query->row(); } private function Insert($post) { session_start(); $this->author = $_SESSION["username"]; return $this->db->insert('posts', $this); } private function Update($post) { $this->db->set('title', $this->title); $this->db->set('content', $this->content); $this->db->where('id', $this->id); return $this->db->update('posts'); } public function Delete() { $this->db->where('id', $this->id); return $this->db->delete('posts'); } public function Save() { if (isset($this->id)) { return $this->Update(); } else { return $this->Insert(); } } public function Vote() { $this->db->set('upvotes', $this->upvotes); $this->db->set('downvotes', $this->downvotes); $this->db->set('voters', $this->voters); $this->db->where('id', $this->id); return $this->db->update('posts'); } } ?>
vonderborch/CS483
final/application/models/PostModel.php
PHP
mit
1,606
20.4
67
0.492519
false
--- title: 'PB &#038; Homemade J' author: lbjay layout: post permalink: /2007/10/05/pb-homemade-j/ categories: - "What's for Lunch" --- <abbr class="unapi-id" title=""><!-- &nbsp; --></abbr> <div style="float: right; margin-left: 10px; margin-bottom: 10px;"> <a href="http://www.flickr.com/photos/37849137@N00/1490397893/" title="photo sharing"><img src="http://farm2.static.flickr.com/1243/1490397893_cac4375203_m.jpg" alt="" style="border: solid 2px #000000;" /></a><br /> <br /> <span style="font-size: 0.9em; margin-top: 0px;"><br /> <a href="http://www.flickr.com/photos/37849137@N00/1490397893/">PB &#038; Homemade J</a><br /> <br /> Originally uploaded by <a href="http://www.flickr.com/people/37849137@N00/">jayluker</a><br /> </span> </div> This one&#8217;s been stuck in the Flickr queue for a couple of weeks. Also it wasn&#8217;t truly Peanut Butter, but Sunflower Butter. It just seems so awkward to call it a SFB &#038; J. The jelly is grape and was made by my neighbor Leah from <a href='http://en.wikipedia.org/wiki/Concord_grape' target='_blank'>Concord grapes</a> growing on a trellis right out her back door. The pile &#8216;o&#8217; orange in the foreground is some delicious carrot slaw made with honey, walnuts and dried cranberries. <br clear="all" />
lbjay/lbjay.github.io
_posts/2007-10-05-pb-homemade-j.md
Markdown
mit
1,285
63.3
485
0.698833
false
--- layout: default --- <h2>{{ page.title }}</h2> <div class="post"> {{ content }} </div>
jiko/stopabadcure
_layouts/post.html
HTML
mit
90
11.857143
25
0.533333
false
body { color: #ffffff; font-family: Monospace, sans-serif; font-size: 13px; text-align: center; font-weight: bold; background-color: #000000; margin: 0; overflow: hidden; cursor: none; -webkit-touch-callout: none; /* iOS Safari */ -webkit-user-select: none; /* Chrome/Safari/Opera */ -khtml-user-select: none; /* Konqueror */ -moz-user-select: none; /* Firefox */ -ms-user-select: none; /* Internet Explorer/Edge */ user-select: none; } ul { list-style: none; } .found { text-decoration: line-through; color: #00ff00; } .player-information { font-size: 1.2em; font-weight: bold; position: absolute; left: 0; top: 0; padding: 1em; z-index: 2147483647; } .items { font-size: 1.2em; font-weight: bold; position: absolute; right: 0; top: 0; padding-right: 1em; z-index: 2147483647; height: 90%; overflow: hidden; } .refreshButton { position: absolute; left: 0; top: 5.5em; margin-left: 10px; padding: 1.25em; color: white; font-size: larger; text-decoration: none; border-radius: 1em; background-repeat: no-repeat; background-image: url('./../ui/refresh.svg'); background-size: contain; background-color: teal; z-index: 2147483647; } /********************* Player Settings **********************/ #settings { display: none; width: 25%; min-width: 300px; margin: 1% auto; } #settings label { display: block; } #settings label.inline { display: inline-block; } #settings input { padding: 5px 10px; margin-bottom: 10px; } #settings input.small { width: 25px; } #settings button { display: block; margin: 15px auto; padding: 5px 10px; }
Devoxx4KidsDE/workshop-maze-vr
app/css/style.css
CSS
mit
1,806
17.242424
61
0.581395
false
<html><body> <h4>Windows 10 x64 (18362.329)</h4><br> <h2>_CM_UOW_SET_VALUE_KEY_DATA</h2> <font face="arial"> +0x000 PreparedCell : Uint4B<br> +0x004 OldValueCell : Uint4B<br> +0x008 NameLength : Uint2B<br> +0x00c DataSize : Uint4B<br> </font></body></html>
epikcraw/ggool
public/Windows 10 x64 (18362.329)/_CM_UOW_SET_VALUE_KEY_DATA.html
HTML
mit
296
35.25
58
0.597973
false
/// <reference types="xrm" /> export declare function findIndex(handlers: Xrm.Events.ContextSensitiveHandler[], handler: Xrm.Events.ContextSensitiveHandler): number;
camelCaseDave/xrm-mock
dist/xrm-mock-generator/helpers/array.helper.d.ts
TypeScript
mit
166
82
135
0.795181
false
<?php namespace Vilks\DataObject; use Vilks\DataObject\Exception\DirectPropertySetException; use Vilks\DataObject\Exception\PropertyNotFoundException; use Vilks\DataObject\Exception\PropertyValidationFailedException; use Vilks\DataObject\Exception\WrongEvolutionInheritanceException; use Vilks\DataObject\Validator\DataObjectValidatorFactory; /** * Base DataObject * * @package Vilks\DataObject */ abstract class DataObject { private static $validators = []; /** * Create instance of DataObject * * @return static */ public static function create() { return new static; } /** * Create instance of DataObject with values based on related DataObject * * @param DataObject $source Data source object * * @return static * @throws Exception\WrongEvolutionInheritanceException If DataObjects has different chain of inheritance */ public static function mutate(DataObject $source) { $replica = static::create(); if ($replica instanceof $source) { $properties = get_object_vars($source); } elseif ($source instanceof $replica) { $properties = get_object_vars($replica); } else { throw new WrongEvolutionInheritanceException( $replica, $source, sprintf('Class "%s" must be parent or child for "%s"', get_class($source), get_class($replica)) ); } foreach ($properties as $name => $value) { $replica->$name = $value; } return $replica; } /** * Magic set property of DataObject * * IMPORTANT: For better performance in production you need * to overwrite method for each property in final DataObjects * * @param string $name * @param array $arguments * * @return static */ public function __call($name, array $arguments) { $this->_isPropertyExists($name); if (!count($arguments)) { return $this->$name; } else { $value = $arguments[0]; $this->_validateDataType($name, $value); $replica = static::_isMutable() ? $this : clone $this; $replica->$name = $value; return $replica; } } /** * Magic get property of DataObject * * IMPORTANT: For better performance in production you need * to make properties public in final DataObjects * * @param string $name * * @return mixed */ public function __get($name) { $this->_isPropertyExists($name); return $this->$name; } /** * Disallow direct setting of properties * * @param string $name * @param string $value * * @throws Exception\DirectPropertySetException * @deprecated */ public function __set($name, $value) { throw new DirectPropertySetException($name, $value, $this); } /** * Turning off constructor outside object * Use Class::create() */ protected function __construct() {} /** * List of datatypes for properties * * @return string[] */ protected static function _getDataTypes() { return []; } /** * Setting for DataObject which set behavior on property changing. * If it's false changing of property will generate new DataObject with same values, * if it's true changing of property will just change property in object * * @return bool */ protected static function _isMutable() { return false; } /** * Exclude validators from serialization * * @return string[] */ public function __sleep() { $properties = array_keys(get_object_vars($this)); unset($properties['validators']); return $properties; } private static function _getPropertyValidator($class, $property) { $key = sprintf('%s.%s', $class, $property); if (!array_key_exists($key, self::$validators)) { $types = static::_getDataTypes(); self::$validators[$key] = array_key_exists($property, $types) ? DataObjectValidatorFactory::getValidator($class)->getValidationCallback($types[$property]) : null; } return self::$validators[$key]; } private function _validateDataType($property, $value) { if (!is_null($value)) { $validator = self::_getPropertyValidator(get_class($this), $property); if ($validator && !$validator($value)) { throw new PropertyValidationFailedException( $property, $value, static::_getDataTypes()[$property], $this ); } } } private function _isPropertyExists($name, $strict = true) { $result = property_exists($this, $name); if ($strict && !$result) { throw new PropertyNotFoundException($this, $name); } return $result; } }
igrizzli/data-object
src/Vilks/DataObject/DataObject.php
PHP
mit
5,163
25.341837
111
0.572535
false
import _plotly_utils.basevalidators class ShowexponentValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="showexponent", parent_name="scatterpolar.marker.colorbar", **kwargs ): super(ShowexponentValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), values=kwargs.pop("values", ["all", "first", "last", "none"]), **kwargs )
plotly/plotly.py
packages/python/plotly/plotly/validators/scatterpolar/marker/colorbar/_showexponent.py
Python
mit
554
31.588235
78
0.590253
false
<?php namespace Midnight\Crawler\Plugin\TestData; class MuryoTestData extends AbstractTestData { /** * @var string **/ protected $rss_name = 'muryo.xml'; /** * @var array **/ protected $html_paths = array( 'muryo/71340.html', 'muryo/71370.html', 'muryo/71376.html', 'muryo/error.html', 'muryo/error2.html' ); }
togusafish/app2641-_-AdultMidnight
src/Midnight/Crawler/Plugin/TestData/MuryoTestData.php
PHP
mit
397
14.88
44
0.546599
false
using System; using Argus.Extensions; namespace Argus.Data { /// <summary> /// Contains a string name/value pair seperated by an equals sign. The values can be set via the properties or by passing in a /// delimited string. E.g. FirstName=Blake. /// </summary> /// <remarks></remarks> public class Parameter { //********************************************************************************************************************* // // Class: Parameter // Organization: http://www.blakepell.com // Initial Date: 12/19/2012 // Last Updated: 04/07/2016 // Programmer(s): Blake Pell, blakepell@hotmail.com // //********************************************************************************************************************* /// <summary> /// Constructor /// </summary> /// <remarks></remarks> public Parameter() { } /// <summary> /// Constructor /// </summary> /// <param name="name">The name of the parameter.</param> /// <param name="value">The value of the parameter.</param> /// <remarks></remarks> public Parameter(string name, string value) { this.Name = name; this.Value = value; } /// <summary> /// Returns the name/value pair in string format. E.g. FirstName=Blake /// </summary> /// <returns></returns> /// <remarks></remarks> public override string ToString() { return $"{this.Name}={this.Value}"; } /// <summary> /// Sets the parameter based off of a passed in string via an operator. /// </summary> /// <param name="str"></param> /// <returns></returns> /// <remarks></remarks> public static implicit operator Parameter(string str) { if (string.IsNullOrWhiteSpace(str) == true) { throw new Exception("The a valid parameter string. A value parameter string includes a name/value pair seperated by an equals sign."); } if (str.Contains("=") == false) { throw new Exception("The a valid parameter string. A value parameter string includes a name/value pair seperated by an equals sign."); } // Since there was an equals sign, we will have a name/value pair. string[] items = str.SplitPcl("="); return new Parameter(items[0], items[1]); } /// <summary> /// Sets the string based off of the current value of the parameter. /// </summary> /// <param name="p"></param> /// <returns></returns> /// <remarks></remarks> public static implicit operator string(Parameter p) { return $"{p.Name}={p.Value}"; } public string Name { get; set; } public string Value { get; set; } } }
blakepell/Argus
Argus/Argus.Core/Data/Parameter.cs
C#
mit
3,083
31.442105
151
0.476793
false
__author__ = 'miko' from Tkinter import Frame class GameState(Frame): def __init__(self, *args, **kwargs): self.stateName = kwargs["stateName"] self.root = args[0] self.id = kwargs["id"] Frame.__init__(self, self.root.mainWindow) self.config( background="gold" ) self.place(relwidth=1, relheight=1)
FSI-HochschuleTrier/hacker-jeopardy
de/hochschuletrier/jpy/states/GameState.py
Python
mit
319
21.785714
44
0.658307
false
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_24) on Fri Feb 22 14:06:12 EET 2013 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> javalabra.chess.core.impl.state (Chess 0.0.1-SNAPSHOT API) </TITLE> <META NAME="date" CONTENT="2013-02-22"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="javalabra.chess.core.impl.state (Chess 0.0.1-SNAPSHOT API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../javalabra/chess/core/impl/move/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../javalabra/chess/domain/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?javalabra/chess/core/impl/state/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <H2> Package javalabra.chess.core.impl.state </H2> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../javalabra/chess/core/impl/state/AbstractGameState.html" title="class in javalabra.chess.core.impl.state">AbstractGameState</A></B></TD> <TD>Abstract game state.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../javalabra/chess/core/impl/state/SelectMoveState.html" title="class in javalabra.chess.core.impl.state">SelectMoveState</A></B></TD> <TD>State object representing state when piece on the board is selected and game is waiting for a move to be choosen.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../javalabra/chess/core/impl/state/SelectPieceState.html" title="class in javalabra.chess.core.impl.state">SelectPieceState</A></B></TD> <TD>State object representing state when game is waiting for piece of concrete color to be selected.</TD> </TR> </TABLE> &nbsp; <P> <DL> </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../javalabra/chess/core/impl/move/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../javalabra/chess/domain/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?javalabra/chess/core/impl/state/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2013. All Rights Reserved. </BODY> </HTML>
nfrolov/useless-chess
javadoc/javalabra/chess/core/impl/state/package-summary.html
HTML
mit
7,218
41.964286
178
0.625797
false
<!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="./4ac3f45b236dfce453c7b08f66748497144da944c805dd71a7d9c6d6ff5efcff.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/596deaa0ccc1e29ccba1a93b711a57943231695e12a907a1b27bc4e377c328de.html
HTML
mit
550
28
98
0.581818
false
from csacompendium.csa_practice.models import PracticeLevel from csacompendium.utils.pagination import APILimitOffsetPagination from csacompendium.utils.permissions import IsOwnerOrReadOnly from csacompendium.utils.viewsutils import DetailViewUpdateDelete, CreateAPIViewHook from rest_framework.filters import DjangoFilterBackend from rest_framework.generics import CreateAPIView, ListAPIView from rest_framework.permissions import IsAuthenticated, IsAdminUser from .filters import PracticeLevelListFilter from csacompendium.csa_practice.api.practicelevel.practicelevelserializers import practice_level_serializers def practice_level_views(): """ Practice level views :return: All practice level views :rtype: Object """ practice_level_serializer = practice_level_serializers() class PracticeLevelCreateAPIView(CreateAPIViewHook): """ Creates a single record. """ queryset = PracticeLevel.objects.all() serializer_class = practice_level_serializer['PracticeLevelDetailSerializer'] permission_classes = [IsAuthenticated] class PracticeLevelListAPIView(ListAPIView): """ API list view. Gets all records API. """ queryset = PracticeLevel.objects.all() serializer_class = practice_level_serializer['PracticeLevelListSerializer'] filter_backends = (DjangoFilterBackend,) filter_class = PracticeLevelListFilter pagination_class = APILimitOffsetPagination class PracticeLevelDetailAPIView(DetailViewUpdateDelete): """ Updates a record. """ queryset = PracticeLevel.objects.all() serializer_class = practice_level_serializer['PracticeLevelDetailSerializer'] permission_classes = [IsAuthenticated, IsAdminUser] lookup_field = 'slug' return { 'PracticeLevelListAPIView': PracticeLevelListAPIView, 'PracticeLevelDetailAPIView': PracticeLevelDetailAPIView, 'PracticeLevelCreateAPIView': PracticeLevelCreateAPIView }
nkoech/csacompendium
csacompendium/csa_practice/api/practicelevel/practicelevelviews.py
Python
mit
2,046
39.117647
108
0.744379
false
export const ADD_COCKTAIL = 'ADD_COCKTAIL'; export const LOAD_COCKTAILS = 'LOAD_COCKTAILS'; export const ADD_SPIRIT = 'ADD_SPIRIT'; export const REMOVE_SPIRIT = 'REMOVE_SPIRIT'; export const UPDATE_HUE = 'UPDATE_HUE';
Jack95uk/HappyHour
src/actions/types.js
JavaScript
mit
218
42.6
47
0.747706
false
#include <algorithm> #include <iostream> #include "RustyFist/DrawMe.h" #include "RustyFist/TouchSink.h" #include "OpenGLLayer.h" using namespace cocos2d; using namespace std; OpenGLLayer::OpenGLLayer() { } OpenGLLayer::~OpenGLLayer() { } bool OpenGLLayer::init() { return Layer::init(); } cocos2d::Scene* OpenGLLayer::scene(DrawMe* drawMe, TouchSink* ts) { auto scene = Scene::create(); OpenGLLayer *layer = OpenGLLayer::create(); layer->setDrawMe(drawMe); layer->setTouchSink(ts); scene->addChild(layer); return scene; } void OpenGLLayer::draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, uint32_t flags) { if (_drawMe) _drawMe->draw(); } void OpenGLLayer::setTouchSink(TouchSink* ts) { _ts = ts; auto mouseEvents = EventListenerMouse::create(); mouseEvents->onMouseDown = [this](Event* e) { if(auto me = dynamic_cast<EventMouse*>(e)) { if(_ts) _ts->mouse({me->getCursorX(), me->getCursorY()}); } }; mouseEvents->onMouseUp = [this](Event* e) { if(auto me = dynamic_cast<EventMouse*>(e)) { if(_ts) _ts->mouse({me->getCursorX(), me->getCursorY()}); } }; mouseEvents->onMouseMove = [this](Event* e) { if(auto me = dynamic_cast<EventMouse*>(e)) { if(_ts) _ts->mouse({me->getCursorX(), me->getCursorY()}); } }; _eventDispatcher->addEventListenerWithSceneGraphPriority(mouseEvents, this); } void OpenGLLayer::onTouchesBegan(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* unused_event) { sendTouch(touches); } void OpenGLLayer::onTouchesMoved(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* unused_event) { sendTouch(touches); } void OpenGLLayer::onTouchesEnded(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* unused_event) { sendTouch(touches); } void OpenGLLayer::onTouchesCancelled(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* unused_event) { sendTouch(touches); } void OpenGLLayer::sendTouch(const std::vector<cocos2d::Touch*>& touches) { std::vector<::Touch> tochs; std::transform(touches.begin(), touches.end(), back_inserter(tochs), [](cocos2d::Touch* t) { return ::Touch{t->getID(), t->getLocation().x, t->getLocation().y}; }); if(_ts) _ts->touch(tochs); }
Ingener74/Lost-Foot
RustyFist/src/OpenGLLayer.cpp
C++
mit
2,225
20.394231
111
0.687191
false
// // PASConnectionTransformation.h // ximber // // Created by Paul Samuels on 15/09/2014. // Copyright (c) 2014 Paul Samuels. All rights reserved. // @import Foundation; /** * The connection transformation is a basic data structure that holds a block that is * executed on each node found at the xpath */ @interface PASConnectionTransformation : NSObject @property (nonatomic, copy, readonly) NSString *xPath; @property (nonatomic, copy, readonly) NSString *(^keyTransformer)(NSString *key); + (instancetype)connectionTransformationWithXPath:(NSString *)xPath keyTransformer:(NSString *(^)(NSString *key))keyTransformer; @end
paulsamuels/ximber
ximber/Models/PASConnectionTransformation.h
C
mit
639
28.045455
128
0.751174
false
/* icon */ .ico-file{width: 32px;height: 32px;display: inline-block;vertical-align: middle;background: url(../img/spr-icon.png) -384px 0 no-repeat;} .ico-bt-file{background-position: 0 0} .ico-bt-link{background-position: -32px 0} .ico-chm{background-position: -64px 0} .ico-xls{background-position: -96px 0} .ico-link{background-position: -128px 0} .ico-pdf{background-position: -160px 0} .ico-doc{background-position: -192px 0} .ico-ppt{background-position: -224px 0} .ico-txt{background-position: -256px 0} .ico-word{background-position: -288px 0} .ico-install{background-position: -320px 0} .ico-music{background-position: -352px 0} .ico-unknow{background-position: -384px 0} .ico-pic{background-position: -416px 0} .ico-apk{background-position: -448px 0} .ico-exe{background-position: -480px 0} .ico-ipa{background-position: -512px 0} .ico-ipsw{background-position: -544px 0} .ico-iso{background-position: -576px 0} .ico-group{background-position: -608px 0} .ico-video{background-position: -832px 0} .ico-avi{background-position: -640px 0} .ico-flv{background-position: -672px 0} .ico-mkv{background-position: -704px 0} .ico-mov{background-position: -736px 0} .ico-mp4{background-position: -768px 0} .ico-mpg{background-position: -800px 0} .ico-rm{background-position: -864px 0} .ico-rmvb{background-position: -896px 0} .ico-wmv{background-position: -928px 0} .ico-rar{background-position: -960px 0} /* 会员图标 vip */ .icvip{display:inline-block;width:42px;height:12px;background:url(../img/ic_vip.png) no-repeat 0 999em;overflow:hidden;vertical-align:-1px;margin: 0 0 0 2px;} .icvip00{width: 36px;background-position: 0 0} .icvip01{background-position: -37px 0} .icvip02{background-position: -80px 0} .icvip03{background-position: -123px 0} .icvip04{background-position: -166px 0} .icvip05{background-position: -209px 0} .icvip06{background-position: -252px 0} .icvip00hui{background-position: 0 -18px} .icvip00hui{width: 35px;background-position: 0px -18px}.icvip01hui{background-position: -37px -18px} .icvip02hui{background-position: -80px -18px} .icvip03hui{background-position: -123px -18px} .icvip04hui{background-position: -166px -18px} .icvip05hui{background-position: -209px -18px} .icvip06hui{background-position: -252px -18px} /* gold vip */ .icgold00{width: 35px;background-position: 0 -36px} .icgold01{background-position: -37px -36px} .icgold02{background-position: -80px -36px} .icgold03{background-position: -123px -36px} .icgold04{background-position: -166px -36px} .icgold05{background-position: -209px -36px} .icgold06{background-position: -252px -36px} .icgold07{background-position: -295px -36px} .icgold00hui{background-position: 0 -54px} .icgold00hui{width: 35px;background-position: 0px -54px} .icgold01hui{background-position: -37px -54px} .icgold02hui{background-position: -80px -54px} .icgold03hui{background-position: -123px -54px} .icgold04hui{background-position: -166px -54px} .icgold05hui{background-position: -209px -54px} .icgold06hui{background-position: -252px -54px} .icgold07hui{background-position: -295px -54px} /* super vip */ .icsuper00{width: 35px;background-position: 0 -72px} .icsuper01{background-position: -37px -72px} .icsuper02{background-position: -80px -72px} .icsuper03{background-position: -123px -72px} .icsuper04{background-position: -166px -72px} .icsuper05{background-position: -209px -72px} .icsuper06{background-position: -252px -72px} .icsuper07{background-position: -295px -72px} .icsuper00hui{background-position: 0 -90px} .icsuper00hui{width: 35px;background-position: 0px -90px} .icsuper01hui{background-position: -37px -90px} .icsuper02hui{background-position: -80px -90px} .icsuper03hui{background-position: -123px -90px} .icsuper04hui{background-position: -166px -90px} .icsuper05hui{background-position: -209px -90px} /* another */ .icnian{width:12px;height:12px; background-position: 0px -108px;} .icnianhui{width:12px;height:12px; background-position: 0px -128px} .icdongjie{width:16px;height:16px; background-position: -19px -109px} .icdongjiehui{width:16px;height:16px; background-position: -19px -128px} .icshuai{width:16px;height:16px; background-position: -38px -108px} .icshuaihui{width:16px;height:16px; background-position: -38px -128px} .icqiye{width:16px;height:16px; background-position: -57px -109px} .icqiyehui{width:16px;height:16px; background-position: -57px -128px} .ichongren{width:16px;height:16px; background-position: -76px -109px} .ichongrenhui{width:16px;height:16px; background-position: -76px -128px} .icbao{width:16px;height:16px; background-position: -95px -109px} .icbaohui{width:16px;height:16px; background-position: -95px -128px} .icxun{width:15px;height:16px; background-position: -116px -109px} .icxunhui{width:15px;height:16px; background-position: -116px -128px} .icgold{width:15px;height:16px; background-position: -136px -109px} .icgoldhui{width:15px;height:14px; background-position: -136px -128px} .icgrow{width:12px;height:14px; background-position: -155px -109px;} .icdown{width:12px;height:14px; background-position: -155px -128px;} .ickuainiao{background-position: -338px 0;width: 36px;} .ickuainiaohui{background-position: -338px -18px} .icshangxing{background-position: -380px 0;width: 36px} .icshangxinghui{background-position: -380px -18px;}
xunleif2e/vue-lazy-component
demo/assets/css/icon.css
CSS
mit
5,332
89.793103
416
0.76127
false
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ #include "tcp_socket.h" using namespace easynet; //TCPSocket 已连接的服务器 TCPSocket::TCPSocket(EPOLLSvrPtr s) { socket_handler_ = nullptr; svr_ = s; msg_ = nullptr; step_ = READ_HEAD; } void TCPSocket::SetHandler(On_Socket_Handler h){ socket_handler_ = h; } void TCPSocket::OnNetMessage(){ if( nullptr == socket_handler_){ LOG(FATAL) << "tcpsocket handler is nullptr!"; return; } //char *buff = svr_.get()->buff_; //对数组操作一定要注意, 会有越界的可能 for(;;){ char *buff = svr_.get()->buff_; //一直读, 直到出错 int32_t ret = NetPackage::Read(peer_.fd_, buff, MAX_SOCK_BUFF); //LOG(INFO) << "read ok ret[" << ret << "]"; if(0 == ret ){ LOG(INFO) << "connection closed by peer fd[" << peer_.fd_ << "]"; this->KickOut(); return; } if( ret < 0 ){ if( EAGAIN == errno || EWOULDBLOCK == errno ){ //再次read, buff将从头开始填充 //buff = svr_.get()->buff_; //continue; return; }else{ LOG(INFO) << "read fail! fd[" << peer_.fd_ << "] errno[" << errno << "] msg[" << strerror(errno) << "]"; this->KickOut(); return; } } int32_t more_data = ret; while( more_data > 0){ if( nullptr == peer_.buff_ ){ peer_.buff_ = std::make_shared<DataBuffer>(peer_.fd_, HEADER_SZ); } auto data_buffer = peer_.buff_.get(); int32_t need_data = data_buffer->NeedData(); //读取包头 if( READ_HEAD == step_ ){ if( more_data < need_data ) { //包头没有读完整 data_buffer->AddData(more_data, buff); return; } data_buffer->AddData(need_data, buff); //指向body的头指针, 向前添加已经读过的内存 buff += need_data; more_data = (more_data - need_data) < 0 ? 0:(more_data - need_data); msg_ = (MSG* )data_buffer->GetBuffPtr(); if(VERSION != msg_->header.version_ || IDENTIFY != msg_->header.identify_){ LOG(ERROR) << "version or identify is not fit! kick out client fd[" << peer_.fd_ << "] version[" << (int)msg_->header.version_ << "] current version[" << (int)VERSION<<"]" << "identify[" << (int)msg_->header.identify_ << "] current identify[" << (int)IDENTIFY << "]"; this->KickOut(); LOG(INFO) << "receive msg count[" << m.GetRecvPack() << "]"; return; } msg_->header.length_ = ntohs(msg_->header.length_); msg_->header.type_ = ntohs(msg_->header.type_); //为body 申请内存 data_buffer->Resize(msg_->header.length_ + HEADER_SZ); //重新申请内存后, 以前的msg_指向的内容不能再使用了 msg_ = (MSG* )data_buffer->GetBuffPtr(); need_data = data_buffer->NeedData(); step_ = READ_BODY; } //现在的step 肯定是 READ_BODY if( more_data > 0 ) { //读取body if(more_data < need_data) { data_buffer->AddData(more_data, buff); return; } data_buffer->AddData(need_data, buff); more_data = (more_data - need_data) < 0 ? 0:(more_data - need_data); //buff读取后指针后移 buff += need_data; m.AddRecvPack(); //客户程序只需要截获到数据信息就行, 不用关心包头 char *pMsg = (char* )(data_buffer->GetBuffPtr()); pMsg += sizeof(HEADER); auto f = socket_handler_; try{ f(this->getID(), pMsg,msg_->header.length_, msg_->header.type_); }catch(...){ LOG(ERROR) << "tcpsocket handler run fail!"; } //自动删除已经用过的packet auto tmp = std::move(peer_.buff_); tmp = nullptr; peer_.buff_ = nullptr;//是不是多此一举, 就是多此一举, move 后peer_buff_ 会为nullptr //读取新的包头 step_ = READ_HEAD; } } } } void TCPSocket::KickOut() { IPlayer::KickOut(); //TODO 需要再 EPOLLSvr 的map 中删除事件events_map_ 和连接信息 player_map_ }
PickMio/NetEase
olds/network/src/tcp_socket.cc
C++
mit
5,843
39.080292
124
0.386086
false
{% extends 'base.html' %} {% block content %} <div class="row"> <div class="col-md-12"> <form action="/login" method="post"> {{ form.csrf_token }} {{ form.next(value=next) }} <div class="form-group"> {{ form.username.label }} {{ form.username(class='form-control') }} </div> <div class="form-group"> {{ form.password.label }} {{ form.password(class='form-control') }} </div> <div class="form-group"> <input type="submit" class="form-control" value="Login"> </div> </form> </div> </div> <div class="row"> <div class="col-md-12"> {% with messages = get_flashed_messages() %} {% for message in messages %} <div class="alert alert-info">{{ message }}</div> {% endfor %} {% endwith %} </div> </div> {% endblock %}
douglasstarnes/vfcake2015-complete
vfcake2015app/templates/login.html
HTML
mit
971
29.375
72
0.457261
false
using Android.OS; using Android.Text; using Android.Util; using REKT.Graphics; using REKT.Graphics.Unsafe; using REKT.DI; using SkiaSharp; using System; using System.Text; using D = System.Diagnostics.Debug; using NativeActivity = Android.App.Activity; using NativeBitmap = Android.Graphics.Bitmap; using NativeBitmapFactory = Android.Graphics.BitmapFactory; using NativeContext = Android.Content.Context; using NativeRect = Android.Graphics.Rect; using NativeDialog = Android.Support.V7.App.AlertDialog; using NativeProgressDialog = Android.App.ProgressDialog; using NativeColour = Android.Graphics.Color; using NativeArrayAdapter = Android.Widget.ArrayAdapter; using NativeView = Android.Views.View; using System.Collections; using NativeThread = System.Threading.Thread; namespace REKT { public static class AndroidExtensions { ///////////////////////////////////////////////////////////////////// // STRINGS ///////////////////////////////////////////////////////////////////// public static ISpanned ToSpannedHTML(this string rawHtml) { ISpanned html; if (AndroidPlatform.Version >= BuildVersionCodes.N) html = Html.FromHtml(rawHtml, FromHtmlOptions.ModeLegacy); else { #pragma warning disable CS0618 //deprecation html = Html.FromHtml(rawHtml); #pragma warning restore CS0618 } return html; } ///////////////////////////////////////////////////////////////////// // CONTEXTS ///////////////////////////////////////////////////////////////////// public static SKColor ThemeColour(this NativeContext context, int themeColourID) { if (context == null) throw new ArgumentNullException("context"); using (var typedValue = new TypedValue()) { var theme = context.Theme; theme.ResolveAttribute(themeColourID, typedValue, true); var data = typedValue.Data; return new SKColor( (byte)NativeColour.GetRedComponent(data), (byte)NativeColour.GetGreenComponent(data), (byte)NativeColour.GetBlueComponent(data), (byte)NativeColour.GetAlphaComponent(data)); } } public static NativeBitmap BitmapResource(this NativeContext context, int bitmapResourceID) { using (var opts = new NativeBitmapFactory.Options()) { opts.InPreferQualityOverSpeed = true; return NativeBitmapFactory.DecodeResource(context.Resources, bitmapResourceID, opts); } } public static SKBitmap BitmapResourceSkia(this NativeContext context, int bitmapResourceID) { using (var nativeBmp = context.BitmapResource(bitmapResourceID)) return nativeBmp.ToSkia(); } private static void RunOnUIThreadIfPossible(this NativeContext context, Action action) { if (context is NativeActivity activity) activity.RunOnUiThread(action); else action(); } public static void ShowYesNoDialog(this NativeContext context, string title, string text, Action yesAction = null, Action noAction = null) { if (context == null) throw new ArgumentNullException("context"); context.RunOnUIThreadIfPossible(() => { using (var builder = new NativeDialog.Builder(context)) { builder.SetTitle((title ?? "").Trim()); builder.SetMessage((text ?? "").Trim()); builder.SetCancelable(false); builder.SetPositiveButton("Yes", (s, e) => { yesAction?.Invoke(); }); builder.SetNegativeButton("No", (s, e) => { noAction?.Invoke(); }); using (var dialog = builder.Create()) dialog.Show(); } }); } public static void ShowOKDialog(this NativeContext context, string title, string text, Action okAction = null) { if (context == null) throw new ArgumentNullException("context"); context.RunOnUIThreadIfPossible(() => { using (var builder = new NativeDialog.Builder(context)) { builder.SetTitle((title ?? "").Trim()); builder.SetMessage((text ?? "").Trim()); builder.SetCancelable(false); builder.SetPositiveButton(Android.Resource.String.Ok, (s, e) => { okAction?.Invoke(); }); using (var dialog = builder.Create()) dialog.Show(); } }); } public static void ShowWaitDialog(this NativeContext context, string title, string text, Action asyncTask) { if (context == null) throw new ArgumentNullException("context"); if (asyncTask == null) throw new ArgumentNullException("asyncTask"); context.RunOnUIThreadIfPossible(() => { var dialog = NativeProgressDialog.Show(context, (title ?? "").Trim(), (text ?? "").Trim(), true, false); new NativeThread(() => { asyncTask?.Invoke(); dialog.Dismiss(); dialog.Dispose(); }).Start(); }); } public static void ShowListDialog(this NativeContext context, string title, IList data, Action<int> selectionAction, Action cancelAction = null) { if (context == null) throw new ArgumentNullException("context"); if (selectionAction == null) throw new ArgumentNullException("selectionAction"); if (data == null) throw new ArgumentNullException("data"); context.RunOnUIThreadIfPossible(() => { using (var builder = new NativeDialog.Builder(context)) { var adapter = new NativeArrayAdapter(context, Android.Resource.Layout.SimpleListItem1, data); builder.SetTitle((title ?? "").Trim()) .SetAdapter(adapter, (s, e) => { selectionAction.Invoke(e.Which); }); if (cancelAction != null) builder.SetCancelable(true).SetNegativeButton(Android.Resource.String.Cancel, (s, e) => { cancelAction.Invoke(); }); else builder.SetCancelable(false); using (var dialog = builder.Create()) dialog.Show(); } }); } public static void ShowCustomDialog(this Activity activity, string title, int viewResID, Action<NativeView> initAction = null, Action<NativeView> okAction = null, Action<NativeView> cancelAction = null) { if (activity == null) throw new ArgumentNullException("context"); activity.RunOnUIThreadIfPossible(() => { using (var builder = new NativeDialog.Builder(activity)) { builder.SetTitle((title ?? "").Trim()); var view = activity.LayoutInflater.Inflate(viewResID, null); initAction?.Invoke(view); builder.SetView(view); builder.SetPositiveButton(Android.Resource.String.Ok, (s, e) => { okAction?.Invoke(view); }); if (cancelAction != null) builder.SetCancelable(true).SetNegativeButton(Android.Resource.String.Cancel, (s, e) => { cancelAction.Invoke(view); }); else builder.SetCancelable(false); using (var dialog = builder.Create()) dialog.Show(); } }); } public static void Toast(this NativeContext context, string text) { Android.Widget.Toast.MakeText(context, text, Android.Widget.ToastLength.Long).Show(); } public static void LaunchWebsite(this NativeContext context, string uri) { using (var _uri = Android.Net.Uri.Parse(uri)) using (var intent = new Android.Content.Intent(Android.Content.Intent.ActionView, _uri)) { intent.AddFlags(Android.Content.ActivityFlags.NewTask); intent.AddFlags(Android.Content.ActivityFlags.NoHistory); intent.AddFlags(Android.Content.ActivityFlags.ExcludeFromRecents); context.StartActivity(intent); } } public static ISpanned GetSpannedHTML(this NativeContext context, int resid) { return context.GetString(resid).ToSpannedHTML(); } public static void LaunchAppSettings(this NativeContext context) { using (var _uri = Android.Net.Uri.Parse("package:" + context.PackageName)) using (var intent = new Android.Content.Intent("android.settings.APPLICATION_DETAILS_SETTINGS", _uri)) { intent.AddFlags(Android.Content.ActivityFlags.NewTask); intent.AddFlags(Android.Content.ActivityFlags.NoHistory); intent.AddFlags(Android.Content.ActivityFlags.ExcludeFromRecents); context.StartActivity(intent); } } ///////////////////////////////////////////////////////////////////// // ACTIVITIES ///////////////////////////////////////////////////////////////////// public static float CanvasScaleHint(this NativeActivity activity) { using (var displayMetrics = new DisplayMetrics()) { activity.WindowManager.DefaultDisplay.GetMetrics(displayMetrics); if (displayMetrics.ScaledDensity.IsZero()) //can this even happen?? return 1.0f; return (displayMetrics.ScaledDensity / 3.0f).Clamp(0.4f, 1.5f); } } public static void With<T>(this NativeActivity activity, int id, Action<T> viewAction) where T : Android.Views.View { using (var view = activity.FindViewById<T>(id)) viewAction(view); } ///////////////////////////////////////////////////////////////////// // SKIA ///////////////////////////////////////////////////////////////////// public static NativeRect ToREKT(this SKRect rect) { return new NativeRect((int)rect.Left, (int)rect.Top, (int)rect.Right, (int)rect.Bottom); } public static NativeColour ToNative(this SKColor col) { return new NativeColour(col.Red, col.Green, col.Blue, col.Alpha); } public static SKColor ToREKT(this NativeColour col) { return new SKColor(col.R, col.G, col.B, col.A); } ///////////////////////////////////////////////////////////////////// // BITMAPS ///////////////////////////////////////////////////////////////////// public static SKBitmap ToSkia(this NativeBitmap source) { if (source == null) throw new ArgumentNullException("source"); //init destination bitmap var output = new SKBitmap( source.Width, source.Height, SKColorType.Rgba8888, SKAlphaType.Unpremul ); //get source pixels //"The returned colors are non-premultiplied ARGB values in the sRGB color space.", //per https://developer.android.com/reference/android/graphics/Bitmap.html int[] sourcePixels = new int[source.Width * source.Height]; source.GetPixels(sourcePixels, 0, source.Width, 0, 0, source.Width, source.Height); //copy into destination try { output.LockPixels(); var buffer = output.GetPixels(); unsafe { int* firstPixelAddr = (int*)buffer.ToPointer(); System.Threading.Tasks.Parallel.For(0, output.Height, (y) => { int p = y * output.Width; int* pixel = firstPixelAddr + p; for (int x = 0; x < output.Width; x++, p++, pixel++) *pixel = sourcePixels[p].SwapBytes02(); }); } output.UnlockPixels(); } catch (Exception e) { e.WriteToLog(); output.Dispose(); throw; } return output; } public static Bitmap ToREKT(this NativeBitmap source) { if (source == null) throw new ArgumentNullException("source"); #if DEBUG StringBuilder sb = new StringBuilder("Bitmap: constructing from Android.Graphics.Bitmap:"); sb.AppendLine(); sb.AppendFormattedLine("Dimensions: {0} x {1}", source.Width, source.Height); sb.AppendFormattedLine("AllocationByteCount: {0}", source.AllocationByteCount); sb.AppendFormattedLine("ByteCount: {0}", source.ByteCount); sb.AppendFormattedLine("RowBytes: {0}", source.RowBytes); sb.AppendFormattedLine("Density: {0}", source.Density); sb.AppendFormattedLine("HasAlpha: {0}", source.HasAlpha); sb.AppendFormattedLine("IsPremultiplied: {0}", source.IsPremultiplied); D.WriteLine(sb); #endif //init destination bitmap var output = new Bitmap(source.Width, source.Height, SKColorType.Rgba8888); //get source pixels //"The returned colors are non-premultiplied ARGB values in the sRGB color space.", //per https://developer.android.com/reference/android/graphics/Bitmap.html int[] sourcePixels = new int[source.Width * source.Height]; source.GetPixels(sourcePixels, 0, source.Width, 0, 0, source.Width, source.Height); //copy into destination try { output.Lock((buffer) => { unsafe { byte* firstPixelAddr = (byte*)buffer.ToPointer(); Thread.Distribute((threadIndex, threadCount) => { for (long y = threadIndex; y < output.Height; y += threadCount) { long p = y * output.Width; for (long x = 0; x < output.Width; x++, p++) output.SetPixel(firstPixelAddr, x, y, ((uint)sourcePixels[p])); } }); } }); } catch (Exception e) { e.WriteToLog(); output.Dispose(); throw; } return output; } ///////////////////////////////////////////////////////////////////// // UUIDs ///////////////////////////////////////////////////////////////////// public static bool Equals(this Java.Util.UUID uuid, string uuidString) { if (uuid == null) throw new ArgumentNullException("uuid"); if (uuidString == null) throw new ArgumentNullException("uuidString"); return uuid.ToString().ToUpper() == uuidString.ToUpper(); } } }
marzer/REKT
REKT.Droid/Extensions.cs
C#
mit
16,165
39.415
140
0.506403
false
// animating the scroll effect $('.screenshots').on('click', function(e){ e.preventDefault(); $("html, body").animate({ scrollTop: "950px", duration: 500 }); });
PersonifyJS/PersonifyApp
app/public/javascripts/application.js
JavaScript
mit
167
32.4
65
0.634731
false
#include "strm.h" #include <math.h> static int num_plus(strm_stream* strm, int argc, strm_value* args, strm_value* ret) { strm_value x, y; strm_get_args(strm, argc, args, "NN", &x, &y); if (strm_int_p(x) && strm_int_p(y)) { *ret = strm_int_value(strm_value_int(x)+strm_value_int(y)); return STRM_OK; } if (strm_number_p(x) && strm_number_p(y)) { *ret = strm_float_value(strm_value_float(x)+strm_value_float(y)); return STRM_OK; } return STRM_NG; } static int num_minus(strm_stream* strm, int argc, strm_value* args, strm_value* ret) { if (argc == 1) { if (strm_int_p(args[0])) { *ret = strm_int_value(-strm_value_int(args[0])); return STRM_OK; } if (strm_float_p(args[0])) { *ret = strm_float_value(-strm_value_float(args[0])); return STRM_OK; } } else { strm_value x, y; strm_get_args(strm, argc, args, "NN", &x, &y); if (strm_int_p(x) && strm_int_p(y)) { *ret = strm_int_value(strm_value_int(x)-strm_value_int(y)); return STRM_OK; } if (strm_number_p(x) && strm_number_p(y)) { *ret = strm_float_value(strm_value_float(x)-strm_value_float(y)); return STRM_OK; } } return STRM_NG; } static int num_mult(strm_stream* strm, int argc, strm_value* args, strm_value* ret) { strm_value x, y; strm_get_args(strm, argc, args, "NN", &x, &y); if (strm_int_p(x) && strm_int_p(y)) { *ret = strm_int_value(strm_value_int(x)*strm_value_int(y)); return STRM_OK; } *ret = strm_float_value(strm_value_float(x)*strm_value_float(y)); return STRM_OK; } static int num_div(strm_stream* strm, int argc, strm_value* args, strm_value* ret) { double x, y; strm_get_args(strm, argc, args, "ff", &x, &y); *ret = strm_float_value(x/y); return STRM_OK; } static int num_bar(strm_stream* strm, int argc, strm_value* args, strm_value* ret) { strm_value x, y; strm_get_args(strm, argc, args, "ii", &x, &y); *ret = strm_int_value(strm_value_int(x)|strm_value_int(y)); return STRM_OK; } static int num_mod(strm_stream* strm, int argc, strm_value* args, strm_value* ret) { strm_value x; strm_int y; strm_get_args(strm, argc, args, "Ni", &x, &y); if (strm_int_p(x)) { *ret = strm_int_value(strm_value_int(x)%y); return STRM_OK; } if (strm_float_p(x)) { *ret = strm_float_value(fmod(strm_value_float(x), y)); return STRM_OK; } return STRM_NG; } static int num_gt(strm_stream* strm, int argc, strm_value* args, strm_value* ret) { double x, y; strm_get_args(strm, argc, args, "ff", &x, &y); *ret = strm_bool_value(x>y); return STRM_OK; } static int num_ge(strm_stream* strm, int argc, strm_value* args, strm_value* ret) { double x, y; strm_get_args(strm, argc, args, "ff", &x, &y); *ret = strm_bool_value(x>=y); return STRM_OK; } static int num_lt(strm_stream* strm, int argc, strm_value* args, strm_value* ret) { double x, y; strm_get_args(strm, argc, args, "ff", &x, &y); *ret = strm_bool_value(x<y); return STRM_OK; } static int num_le(strm_stream* strm, int argc, strm_value* args, strm_value* ret) { double x, y; strm_get_args(strm, argc, args, "ff", &x, &y); *ret = strm_bool_value(x<=y); return STRM_OK; } static int num_number(strm_stream* strm, int argc, strm_value* args, strm_value* ret) { strm_get_args(strm, argc, args, "N", ret); return STRM_OK; } strm_state* strm_ns_number; void strm_number_init(strm_state* state) { strm_ns_number = strm_ns_new(NULL, "number"); strm_var_def(strm_ns_number, "+", strm_cfunc_value(num_plus)); strm_var_def(strm_ns_number, "-", strm_cfunc_value(num_minus)); strm_var_def(strm_ns_number, "*", strm_cfunc_value(num_mult)); strm_var_def(strm_ns_number, "/", strm_cfunc_value(num_div)); strm_var_def(strm_ns_number, "%", strm_cfunc_value(num_mod)); strm_var_def(strm_ns_number, "|", strm_cfunc_value(num_bar)); strm_var_def(strm_ns_number, "<", strm_cfunc_value(num_lt)); strm_var_def(strm_ns_number, "<=", strm_cfunc_value(num_le)); strm_var_def(strm_ns_number, ">", strm_cfunc_value(num_gt)); strm_var_def(strm_ns_number, ">=", strm_cfunc_value(num_ge)); strm_var_def(state, "number", strm_cfunc_value(num_number)); }
matz/streem
src/number.c
C
mit
4,205
24.179641
74
0.616885
false
<html> <head> </head> <body> <h2> Their Antiquity </h2> <span class="oldenglish"> Who </span> <span class="oldenglish"> were </span> <span class="oldenglish"> the </span> originall <span class="oldenglish"> writers </span> <span class="oldenglish"> of </span> <span class="oldenglish"> the </span> severall <span class="oldenglish"> Books </span> <span class="oldenglish"> of </span> <span class="oldenglish"> Holy </span> Scripture, has <span class="english"> not </span> been <span class="oldenglish"> made </span> <span class="oldfrench"> evident </span> <span class="oldenglish"> by </span> <span class="oldenglish"> any </span> <span class="oldfrench"> sufficient </span> <span class="oldfrench"> testimony </span> <span class="oldenglish"> of </span> <span class="oldenglish"> other </span> History, (which <span class="oldenglish"> is </span> <span class="oldenglish"> the </span> <span class="oldenglish"> only </span> <span class="oldfrench"> proof </span> <span class="oldenglish"> of </span> <span class="oldfrench"> matter </span> <span class="oldenglish"> of </span> fact); <span class="english"> nor </span> <span class="oldenglish"> can </span> <span class="oldenglish"> be </span> <span class="oldenglish"> by </span> <span class="oldenglish"> any </span> <span class="oldfrench"> arguments </span> <span class="oldenglish"> of </span> naturall Reason; <span class="oldenglish"> for </span> <span class="oldfrench"> Reason </span> serves <span class="oldenglish"> only </span> <span class="oldenglish"> to </span> <span class="latin"> convince </span> <span class="oldenglish"> the </span> <span class="oldenglish"> truth </span> (not <span class="oldenglish"> of </span> fact, but) <span class="oldenglish"> of </span> consequence. <span class="oldenglish"> The </span> <span class="oldenglish"> light </span> <span class="oldenglish"> therefore </span> <span class="oldenglish"> that </span> <span class="oldenglish"> must </span> <span class="oldfrench"> guide </span> <span class="oldenglish"> us </span> <span class="oldenglish"> in </span> <span class="oldenglish"> this </span> question, <span class="oldenglish"> must </span> <span class="oldenglish"> be </span> <span class="oldenglish"> that </span> <span class="oldenglish"> which </span> <span class="oldenglish"> is </span> <span class="oldenglish"> held </span> <span class="oldenglish"> out </span> <span class="oldenglish"> unto </span> <span class="oldenglish"> us </span> <span class="oldenglish"> from </span> <span class="oldenglish"> the </span> <span class="oldenglish"> Bookes </span> themselves: <span class="oldenglish"> And </span> <span class="oldenglish"> this </span> light, <span class="oldenglish"> though </span> <span class="oldenglish"> it </span> <span class="americanenglish"> show </span> <span class="oldenglish"> us </span> <span class="english"> not </span> <span class="oldenglish"> the </span> <span class="oldenglish"> writer </span> <span class="oldenglish"> of </span> <span class="oldenglish"> every </span> book, <span class="oldenglish"> yet </span> <span class="oldenglish"> it </span> <span class="oldenglish"> is </span> <span class="english"> not </span> unusefull <span class="oldenglish"> to </span> <span class="oldenglish"> give </span> <span class="oldenglish"> us </span> <span class="english"> knowledge </span> <span class="oldenglish"> of </span> <span class="oldenglish"> the </span> time, <span class="dutch"> wherein </span> <span class="oldnorse"> they </span> <span class="oldenglish"> were </span> written. </body> </html>
charlesreid1/wordswordswords
etymology/html/leviathan465.html
HTML
mit
4,204
13.754386
32
0.584206
false
'use strict'; var path = require('path'); module.exports = path.join.bind(path, __dirname, '..');
stackjie/vue-pull-to
build/index.js
JavaScript
mit
99
23.75
55
0.636364
false
--- title: Svett tag: svett active: false url: https://www.facebook.com/svettifi/ template: association.pug --- Navnet Svett spiller på den populært utbredte stereotypen av informatikere. Mange ser på informatikere som svette «nerder». Vi velger å spille videre på dette med et glimt i øyet. **Formål:** Foreningens formål å fremme studenters interesse for spesielle informatiske fagområder. Fokuset vil ligge på å dele dybdekunnskap om fagrelaterte emner i sosiale omgivelser. **Aktiviteter:** Vi arrangerer foredrag, workshops og konkurranser. Ved å fokusere på dybdekunnskap håper vi å kunne åpne flere studenters øyne for mer spesialiserte deler av pensum. Vi vil forsøke å introdusere medstudenter til dypere og mer tekniske aspekter ved den informatiske verden mens vi har det gøy.
megoth/ifi-ordenen
contents/association/svett/index.md
Markdown
mit
813
59.846154
309
0.805063
false
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Master thesis presentation &#8211; OpenLaws</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Presentation of Master thesis @CEID"> <meta name="author" content="Kostas Plessas"> <meta name="keywords" content="publications"> <link rel="canonical" href="http://www.openlaws.gr/publications/2016/10/19/master-thesis-presentation/"> <!-- Custom CSS --> <link rel="stylesheet" href="/css/pixyll.css" 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'> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <!-- 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="Master thesis presentation"> <meta property="og:description" content="A Project Opening Greek Legislation to Citizens"> <meta property="og:url" content="http://www.openlaws.gr/publications/2016/10/19/master-thesis-presentation/"> <meta property="og:site_name" content="OpenLaws"> <!-- 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-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"> <link rel="icon" type="image/png" href="/android-chrome-192x192.png" sizes="192x192"> </head> <body class=""> <div class="site-wrap"> <header class="site-header px2 px-responsive"> <div class="mt2 wrap"> <div class="measure"> <div><a href="http://www.openlaws.gr"><img src="/images/logo.png" alt="logo"/></a></div> <nav class="site-nav right"> <a href="/about/">About</a> <a href="/roadmap/">Roadmap</a> <!--<a href="/contact/">Contact</a>--> </nav> <div class="clearfix"></div> <div class="social-icons"> <div class="right"> <a class="fa fa-github" href="https://github.com/OpenLawsGR"></a> <a class="fa fa-rss" href="/feed.xml"></a> <a class="fa fa-twitter" href="https://twitter.com/OpenLawsGR"></a> <a class="fa fa-envelope" href="mailto:kplessas@ceid.upatras.gr"></a> </div> <div class="right"> </div> </div> <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>Master thesis presentation</h1> <span class="post-meta">Oct 19, 2016</span><br> <span class="post-meta small">1 minute read</span> </div> <article class="post-content"> <p>This project is implemented in the framework of a Master thesis for the postgraduate program Computer Science and Technology at the <a href="https://www.ceid.upatras.gr/en">Department of Computer Engineering and Informatics</a> of the <a href="http://www.upatras.gr/en">University of Patras</a>, which is supervised by <a href="http://athos.cti.gr/garofalakis/index_en.htm">Prof. John Garofalakis</a> and postdoctoral researcher <a href="http://www.plessas.info/index.php/home-en/">Athanasios Plessas</a>.</p> <p>Last week, the defense presentation of the thesis took place successfully.</p> <p><img src="/images/master_thesis_presentation.jpg" alt="Master thesis presentation"></p> <p>The text of the thesis (in Greek) can be found <a href="https://dl.dropboxusercontent.com/u/104921582/K.Plessas_Master_Thesis.pdf">here</a>.</p> <p>The presentation (also in Greek) can be found <a href="https://dl.dropboxusercontent.com/u/104921582/K.Plessas_Master_Thesis_Presentation.pdf">here</a>. </p> </article> <div class="share-page"> Share this post! <div class="share-links"> <a class = "fa fa-facebook" href="https://facebook.com/sharer.php?u=http://www.openlaws.gr/publications/2016/10/19/master-thesis-presentation/" rel="nofollow" target="_blank" title="Share on Facebook"></a> <a class="fa fa-twitter" href="https://twitter.com/intent/tweet?text=Master thesis presentation&url=http://www.openlaws.gr/publications/2016/10/19/master-thesis-presentation/" rel="nofollow" target="_blank" title="Share on Twitter"></a> <a class="fa fa-google-plus" href="https://plus.google.com/share?url=http://www.openlaws.gr/publications/2016/10/19/master-thesis-presentation/" rel="nofollow" target="_blank" title="Share on Google+"></a> <a class="fa fa-linkedin" href="http://www.linkedin.com/shareArticle?url=http://www.openlaws.gr/publications/2016/10/19/master-thesis-presentation/&title=Master thesis presentation" rel="nofollow" target="_blank" title="Share on LinkedIn"></a> <a class = "fa fa-hacker-news" onclick="parent.postMessage('submit','*')" href="https://news.ycombinator.com/submitlink?u=http://www.openlaws.gr/publications/2016/10/19/master-thesis-presentation/&t=Master thesis presentation" rel="nofollow" target="_blank" title="Share on Hacker News"></a> </div> </div> <div id="disqus_thread"></div> <script type="text/javascript"> var disqus_shortname = 'OpenLawsGR'; var disqus_identifier = '/publications/2016/10/19/master-thesis-presentation'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> </div> </div> <footer class="footer"> <div class="p2 wrap"> <div class="measure mt1 center"> <small> Based on <a href="https://github.com/johnotander/pixyll">Pixyll</a> theme for <a href="http://jekyllrb.com/">Jekyll</a>. This site is not affiliated in any way to <a href="http://www.openlaws.eu">openlaws.eu</a>. </small> </div> </div> </footer> </body> </html>
OpenLawsGR/OpenLawsGR.github.io
publications/2016/10/19/master-thesis-presentation/index.html
HTML
mit
7,403
36.770408
514
0.661489
false
<?php /* * This file is part of the Asset Injection package, an RunOpenCode project. * * (c) 2015 RunOpenCode * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace RunOpenCode\AssetsInjection\Tests\Mockup; use RunOpenCode\AssetsInjection\Contract\Compiler\CompilerPassInterface; use RunOpenCode\AssetsInjection\Contract\ContainerInterface; use RunOpenCode\AssetsInjection\Library\LibraryDefinition; use RunOpenCode\AssetsInjection\Value\CompilerPassResult; /** * Class DummyCompilerPass * * Dummy compiler pass which will add definition with given name to container in order to check validity of executed test. * * @package RunOpenCode\AssetsInjection\Tests\Mockup */ final class DummyCompilerPass implements CompilerPassInterface { /** * @var string */ private $definitionTestNameMarker; /** * @var bool */ private $stopProcessing; /** * A constructor. * * @param string $definitionTestNameMarker LibraryDefinition marker name to add to container. * @param bool|false $stopProcessing Should compilation be stopped. */ public function __construct($definitionTestNameMarker, $stopProcessing = false) { $this->definitionTestNameMarker = $definitionTestNameMarker; $this->stopProcessing = $stopProcessing; } /** * {@inheritdoc} */ public function process(ContainerInterface $container) { $container->getLibraries()->addDefinition(new LibraryDefinition($this->definitionTestNameMarker)); return new CompilerPassResult($container, $this->stopProcessing); } }
RunOpenCode/assets-injection
test/Mockup/DummyCompilerPass.php
PHP
mit
1,708
29.517857
122
0.720141
false
--- layout: default title: Pegmatite github: CompilerTeaching/Pegmatite --- Pegmatite design overview ------------------------- This is a fork and extensive rewrite of Achilleas Margaritis's ParserLib. It has the following goals: - Idiomatic C++11 - Simple use - Reuseable, reentrant grammars with multiple action delegates - No dependency on RTTI / exceptions (usable in embedded contexts) It has the following explicit non-goals: - High performance (ease of use or modification should not be sacrificed in the name of performance) - Compatibility with the old ParserLib Design outline -------------- All rules should be immutable after creation. Ideally they'd be constexpr, but this is likely not to be possible. They should have no state associated with them, however, and so parsing should be entirely reentrant. State, for a grammar, is in two categories: - The current parsing state - The actions to be performed when parsing The actions can also be immutable (they don't change over a parse, at least), but should not be tied to the grammar. It should be possible to write one singleton class encapsulating the grammar, with members for the rules, and singleton subclasses (or, ideally, delegates) providing parser actions. The parsing state should be entirely contained within a context object and so the same grammar can be used from multiple threads and can be used for compilation, syntax highlighting, and so on. RTTI Usage ---------- ParserLib requires RTTI for one specific purpose: down-casting from `ast_node` to a subclass (and checking that the result really is of that class). If you are using RTTI in the rest of your application, then you can instruct ParserLib to use RTTI for these casts by defining the `USE_RTTI` macro before including the ParserLib headers and when building ParserLib. If you do not wish to depend on RTTI, then ParserLib provides a macro that you can use in your own AST classes that will provide the required virtual functions to implement ad-hoc RTTI for this specific use. You use them like this: {% highlight c++ %} class MyASTClass : parserlib::ast_node { /* Your methods go here. */ PARSELIB_RTTI(MyASTClass, parserlib::ast_node) }; {% endhighlight %} This macro will be compiled away if you do define `USE_RTTI`, so you can provide grammars built with ParserLib that don't force consumers to use or not-use RTTI. It is also completely safe to build without `USE_RTTI`, but still compile with RTTI. What is Pegmatite ----------------- Pegmatite is a very crystalline, intrusive igneous rock composed of interlocking crystals usually larger than 2.5 cm in size. It is also, in the Computer Lab's tradition of using bad puns for naming, a Parsing Expression Grammar library that rocks!
CompilerTeaching/CompilerTeaching.github.io
pegmatite/index.markdown
Markdown
mit
2,771
34.987013
122
0.762541
false
var markdown = window.markdownit(); $(document).ready(function() { var $wish = $('#wish'); var todoNotificationArea = $('#todos .notification-area'); var todoNotificationIcon = $('#todos .notification-area > i'); var todoNotificationText = $('#todos .notification-area > span'); $('#news-stream .menu .item').tab({history:false}); $('.todo.menu .item').tab({history:false}); $('.top.menu .item').tab({history:false}); $('body').on('click', '.button', function() { $(this).transition('pulse'); }) $('#todos').ready(function() { $.each($('#todos .segment'), function(index, $element){ var $html, $md; $element = $($element); $md = $element.find('.md-content-name'); $html = $element.find('.html-content-name'); $html.html(markdown.render($md.val())); $md = $element.find('.md-content'); $html = $element.find('.html-content'); $html.html(markdown.render($md.val())); }); }); $('#todos').on('click', '.edit.button', function() { var $button = $(this); var $html = $button.parent().siblings('.html-content'); var $md = $button.parent().siblings('.md-content'); var $htmlname = $button.parent().siblings('.html-content-name'); var $mdname = $button.parent().siblings('.md-content-name'); if($html.css('display') == 'none') { var result = markdown.render($md.val()); $html.html(result); result = markdown.render($mdname.val()); $htmlname.html(result); $button.text('Edit'); } else { $button.text('Preview'); } $md.toggle(); $html.toggle(); $mdname.toggle(); $htmlname.toggle(); }); $('#todos').on('click', '.save.button', function() { var $button = $(this); var $mdname = $button.parent().parent().find('input'); var $md = $button.parent().parent().find('textarea'); var id = $button.parent().parent().attr('data-tab'); $.post('/todos/save', {id:id, name: $mdname.val(), content: $md.val()}, function(resp){ console.log('Saved'); }); }); $('#todos').on('click', '.delete.button', function() { var $button = $(this); var id = $button.parent().parent().attr('data-tab'); $.post('/todos/delete', {id:id}, function(resp){ $('*[data-tab="'+id+'"]').remove(); }); }); $('#new-todo').click(function(e) { $button = $(this); $.post('/todos/create', function(resp) { var $menuItem = $('<a>').addClass('item').attr('data-tab', resp.id) .html(resp.name); var $todoContent = $('<div>').addClass('ui tab basic segment basic') .attr('data-tab', resp.id) .append( $('<div>').addClass('ui text menu right floated') .append($('<div>').addClass('ui edit basic button item').text('Edit')) .append($('<div>').addClass('ui save basic button item').text('Save')) .append($('<div>').addClass('ui download basic button item').text('Download')) .append($('<div>').addClass('ui delete basic button item').text('Delete')) ) .append( $('<div>').addClass('ui section divider') ) .append( $('<input>').addClass('ui fluid md-content-name') .attr('style', 'display:none;').val(resp.name) ) .append( $('<div>').addClass('html-content-name').html(markdown.render(resp.name)) ) .append( $('<div>').addClass('ui horizontal divider') ) .append( $('<textarea>').addClass('md-content') .attr('style', 'display:none;').html(resp.content) ) .append( $('<div>').addClass('html-content') ); $button.parent().append($menuItem); $button.parent().parent().next().prepend($todoContent); $button.parent().children().last().tab({history:false}); }) .fail(function() { uiModules.showError('Something went wrong while creating a Todo'); }); }) $('#reminders').on('click', 'i.delete', function(e){ var $parentTr = $(this).parents("tr"); $.post('/reminders/' + $parentTr.attr('id') + '/delete', function(resp) { $parentTr.remove(); }) }); $('#wish-form').submit(function(e){ e.preventDefault(); var wish = $wish.val(); $.get('/wish', {wish: wish}, function(resp) { var targetType = resp.type; if(targetType === 'remind') { var value = resp.response; var error = resp.error if (error) { uiModules.showError(error); return; } $('#reminders table tbody').append( $('<tr>').attr('id', value.id) .append($('<td>').html(value.m)) .append($('<td>').html(value.t)) .append($('<td>').html(value.d)) .append($('<td>').append($('<i>').addClass('ui delete red icon'))) ); } else if(targetType === 'comic') { var link = resp.response; var error = resp.error if (error) { uiModules.showError(error); return; } var $webcomicmodal = $('#webcomic-modal'); $webcomicmodal.find('.header').html(link.title); $webcomicmodal.find('a').attr('href', link.url); var showModal = true; if (link.content_type == 'image') { $webcomicmodal.find('img').attr('src', link.content_url); } else if (link.content_type == 'page') { alert('Page found'); } else { showModal = false; uiModules.showError('Unsuported content_type ' + link.content_type); } if( showModal ) { $webcomicmodal.modal({ context: 'html', observeChanges: true, onVisible: function () { $webcomicmodal.modal("refresh"); } }).modal('show'); } } else if(targetType === 'astro') { var url = resp.response; var error = resp.error if (error) { uiModules.showError(error); return; } $('#astro-modal iframe').attr('src', url); $('#astro-modal').modal({ onVisible: function () { $("#astro-modal").modal("refresh"); } }).modal('show'); } else { uiModules.showError('Invalid type ' + resp.type); } // $('#reply').addClass('animated slideInDown').html(resp.response.message); // setTimeout(function() { // $('#reply').removeClass('animated slideInDown'); // }, 1000); }); $wish.val(null); }); $.get('/commands', function(resp) { $('#commands').html(resp); }); $('#webcomics .button').click(function(e) { var $comic = $(this).parent() var comic_id = $comic.attr('id'); var $button = $comic.find('.button'); $button.addClass('disabled'); $.post('/webcomics/' + comic_id + '/sync', function(response) { $comic.find('p').text(response.resp.links_count); $comic.find('label').text(response.resp.last_sync); }). always(function() { $button.removeClass('disabled'); }); }); $('#astros .button').click(function(e) { var $astro = $(this).parent() var astro_id = $astro.attr('id'); var $button = $astro.find('.button'); $button.addClass('disabled'); $.post('/astros/' + astro_id + '/sync', function(response) { $astro.find('p').text(response.resp.links_count); $astro.find('label').text(response.resp.last_sync); }). always(function() { $button.removeClass('disabled'); }); }); $('#create-playlist-button').click(function(e) { var $playlist_name = $('#playlist-name'); var name = $playlist_name.val(); if(!name) { uiModules.showError('Playlist name cannot be empty'); return; } name = name.trim(); $.post('/music/playlist/create', {name:name}, function(resp) { if(resp.error) { uiModules.showError(resp.error); return; } $('#music .playlists').append(resp.html); $playlist_name.val(null); }); }); $('#music').on('click', 'i.delete-playlist', function(e) { var $playlist_element = $(this).parents('div'); var playlist_id = $playlist_element.attr('id'); $.post('/music/playlist/delete', {id:playlist_id}, function(resp) { if(resp.error) { uiModules.showError(resp.error); return; } if(resp.resp) { $('#' + playlist_id).remove(); uiModules.notify('Playlist deleted successfully'); } else { uiModules.showError('Playlist not deleted'); } }) }); $('#music').on('click', '.youtube-link button', function(e) { var $button = $(this); var $link_input = $(this).siblings('input'); var link = $link_input.val(); if(!link) { $link_input.parent().addClass('error'); uiModules.showError('No link found'); return; } var playlist_id = $button.parents('div.playlist').attr('id'); var $playlist_element = $('#' + playlist_id); $button.addClass('loading'); $.post('/music/playlist/'+ playlist_id +'/add', {link: link, site: 'youtube'}, function(resp) { if(resp.error) { uiModules.showError(resp.error); return; } $playlist_element.find('.update-field').text(resp.resp.updated_at); $playlist_element.find('.links-count').text(resp.resp.links_count) }).always(function(){ $link_input.val(null); $button.removeClass('loading'); }); }); $('#music').on('click', '.random-music', function(e) { var $button = $(this); var playlist_id = $button.parents('div.playlist').attr('id'); var $playlist_element = $('#' + playlist_id); $.get('/music/playlist/'+ playlist_id +'/random', function(resp) { var video_id = resp.resp.video_id; var $musicmodal = $('#music-modal'); $musicmodal.find('.header').html(resp.resp.title); $musicmodal.modal({ context: 'html', observeChanges: true, onVisible: function () { $musicmodal.modal("refresh"); music_player.loadVideoById(video_id, 0, "large") }, onHidden: function() { music_player.stopVideo(); } }).modal('show'); }).fail(function(response) { uiModules.showError(response.responseText); }) }); $('#music').on('click', '.full-playlist', function(e) { var $button = $(this); var playlist_id = $button.parents('div.playlist').attr('id'); var $playlist_element = $('#' + playlist_id); var playlist_name = $playlist_element.find('a.header').text(); $.get('/music/playlist/'+ playlist_id +'/all', function(resp) { var $musicmodal = $('#music-modal'); $musicmodal.find('.header').html(resp.resp.title); $musicmodal.modal({ context: 'html', observeChanges: true, onVisible: function () { $musicmodal.modal("refresh"); var ids = []; for( var i = 0; i < 100 && i < resp.resp.length ; i++ ) { var video = resp.resp[i]; ids.push(video.video_id); } music_player.loadPlaylist(ids); }, onHidden: function() { music_player.stopVideo(); } }).modal('show'); }).fail(function(response) { uiModules.showError(response.responseText); }) }); });
arpitbbhayani/penny
app/static/js/index.js
JavaScript
mit
13,851
34.065823
118
0.442206
false
// // AWSAppDelegate.h // TAWS // // Created by CocoaPods on 05/27/2015. // Copyright (c) 2014 suwa.yuki. All rights reserved. // @import UIKit; @interface AWSAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
classmethod/TAWS-iOS
Example/TAWS/AWSAppDelegate.h
C
mit
270
17
63
0.711111
false
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>metacoq-erasure: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">8.10.dev / metacoq-erasure - 1.0~alpha+8.8</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> metacoq-erasure <small> 1.0~alpha+8.8 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2020-07-17 06:06:32 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-17 06:06:32 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.10.dev Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.08.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.08.1 Official release 4.08.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;matthieu.sozeau@inria.fr&quot; homepage: &quot;https://metacoq.github.io/metacoq&quot; dev-repo: &quot;git+https://github.com/MetaCoq/metacoq.git#coq-8.8&quot; bug-reports: &quot;https://github.com/MetaCoq/metacoq/issues&quot; authors: [&quot;Abhishek Anand &lt;aa755@cs.cornell.edu&gt;&quot; &quot;Simon Boulier &lt;simon.boulier@inria.fr&gt;&quot; &quot;Cyril Cohen &lt;cyril.cohen@inria.fr&gt;&quot; &quot;Yannick Forster &lt;forster@ps.uni-saarland.de&gt;&quot; &quot;Fabian Kunze &lt;fkunze@fakusb.de&gt;&quot; &quot;Gregory Malecha &lt;gmalecha@gmail.com&gt;&quot; &quot;Matthieu Sozeau &lt;matthieu.sozeau@inria.fr&gt;&quot; &quot;Nicolas Tabareau &lt;nicolas.tabareau@inria.fr&gt;&quot; &quot;Théo Winterhalter &lt;theo.winterhalter@inria.fr&gt;&quot; ] license: &quot;MIT&quot; build: [ [&quot;sh&quot; &quot;./configure.sh&quot;] [make &quot;-j%{jobs}%&quot; &quot;-C&quot; &quot;erasure&quot;] [make &quot;test-suite&quot;] {with-test} ] install: [ [make &quot;-C&quot; &quot;erasure&quot; &quot;install&quot;] ] depends: [ &quot;ocaml&quot; {&gt; &quot;4.02.3&quot;} &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} &quot;coq-metacoq-template&quot; {= version} &quot;coq-metacoq-checker&quot; {= version} &quot;coq-metacoq-pcuic&quot; {= version} &quot;coq-metacoq-safechecker&quot; {= version} ] synopsis: &quot;Implementation and verification of an erasure procedure for Coq&quot; description: &quot;&quot;&quot; MetaCoq is a meta-programming framework for Coq. The Erasure module provides a complete specification of Coq&#39;s so-called \&quot;extraction\&quot; procedure, starting from the PCUIC calculus and targeting untyped call-by-value lambda-calculus. The `erasure` function translates types and proofs in well-typed terms into a dummy `tBox` constructor, following closely P. Letouzey&#39;s PhD thesis. &quot;&quot;&quot; url { src: &quot;https://github.com/MetaCoq/metacoq/archive/1.0-alpha+8.8.tar.gz&quot; checksum: &quot;sha256=c2fe122ad30849e99c1e5c100af5490cef0e94246f8eb83f6df3f2ccf9edfc04&quot; }</pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-metacoq-erasure.1.0~alpha+8.8 coq.8.10.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.10.dev). The following dependencies couldn&#39;t be met: - coq-metacoq-erasure -&gt; coq &lt; 8.9~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-metacoq-erasure.1.0~alpha+8.8</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.08.1-2.0.5/extra-dev/8.10.dev/metacoq-erasure/1.0~alpha+8.8.html
HTML
mit
7,992
41.827957
159
0.562892
false
# This file is part of beets. # Copyright 2016, Adrian Sampson. # # 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 Query type hierarchy for DBCore. """ import re from operator import mul from beets import util from datetime import datetime, timedelta import unicodedata from functools import reduce class ParsingError(ValueError): """Abstract class for any unparseable user-requested album/query specification. """ class InvalidQueryError(ParsingError): """Represent any kind of invalid query. The query should be a unicode string or a list, which will be space-joined. """ def __init__(self, query, explanation): if isinstance(query, list): query = " ".join(query) message = f"'{query}': {explanation}" super().__init__(message) class InvalidQueryArgumentValueError(ParsingError): """Represent a query argument that could not be converted as expected. It exists to be caught in upper stack levels so a meaningful (i.e. with the query) InvalidQueryError can be raised. """ def __init__(self, what, expected, detail=None): message = f"'{what}' is not {expected}" if detail: message = f"{message}: {detail}" super().__init__(message) class Query: """An abstract class representing a query into the item database. """ def clause(self): """Generate an SQLite expression implementing the query. Return (clause, subvals) where clause is a valid sqlite WHERE clause implementing the query and subvals is a list of items to be substituted for ?s in the clause. """ return None, () def match(self, item): """Check whether this query matches a given Item. Can be used to perform queries on arbitrary sets of Items. """ raise NotImplementedError def __repr__(self): return f"{self.__class__.__name__}()" def __eq__(self, other): return type(self) == type(other) def __hash__(self): return 0 class FieldQuery(Query): """An abstract query that searches in a specific field for a pattern. Subclasses must provide a `value_match` class method, which determines whether a certain pattern string matches a certain value string. Subclasses may also provide `col_clause` to implement the same matching functionality in SQLite. """ def __init__(self, field, pattern, fast=True): self.field = field self.pattern = pattern self.fast = fast def col_clause(self): return None, () def clause(self): if self.fast: return self.col_clause() else: # Matching a flexattr. This is a slow query. return None, () @classmethod def value_match(cls, pattern, value): """Determine whether the value matches the pattern. Both arguments are strings. """ raise NotImplementedError() def match(self, item): return self.value_match(self.pattern, item.get(self.field)) def __repr__(self): return ("{0.__class__.__name__}({0.field!r}, {0.pattern!r}, " "{0.fast})".format(self)) def __eq__(self, other): return super().__eq__(other) and \ self.field == other.field and self.pattern == other.pattern def __hash__(self): return hash((self.field, hash(self.pattern))) class MatchQuery(FieldQuery): """A query that looks for exact matches in an item field.""" def col_clause(self): return self.field + " = ?", [self.pattern] @classmethod def value_match(cls, pattern, value): return pattern == value class NoneQuery(FieldQuery): """A query that checks whether a field is null.""" def __init__(self, field, fast=True): super().__init__(field, None, fast) def col_clause(self): return self.field + " IS NULL", () def match(self, item): return item.get(self.field) is None def __repr__(self): return "{0.__class__.__name__}({0.field!r}, {0.fast})".format(self) class StringFieldQuery(FieldQuery): """A FieldQuery that converts values to strings before matching them. """ @classmethod def value_match(cls, pattern, value): """Determine whether the value matches the pattern. The value may have any type. """ return cls.string_match(pattern, util.as_string(value)) @classmethod def string_match(cls, pattern, value): """Determine whether the value matches the pattern. Both arguments are strings. Subclasses implement this method. """ raise NotImplementedError() class StringQuery(StringFieldQuery): """A query that matches a whole string in a specific item field.""" def col_clause(self): search = (self.pattern .replace('\\', '\\\\') .replace('%', '\\%') .replace('_', '\\_')) clause = self.field + " like ? escape '\\'" subvals = [search] return clause, subvals @classmethod def string_match(cls, pattern, value): return pattern.lower() == value.lower() class SubstringQuery(StringFieldQuery): """A query that matches a substring in a specific item field.""" def col_clause(self): pattern = (self.pattern .replace('\\', '\\\\') .replace('%', '\\%') .replace('_', '\\_')) search = '%' + pattern + '%' clause = self.field + " like ? escape '\\'" subvals = [search] return clause, subvals @classmethod def string_match(cls, pattern, value): return pattern.lower() in value.lower() class RegexpQuery(StringFieldQuery): """A query that matches a regular expression in a specific item field. Raises InvalidQueryError when the pattern is not a valid regular expression. """ def __init__(self, field, pattern, fast=True): super().__init__(field, pattern, fast) pattern = self._normalize(pattern) try: self.pattern = re.compile(self.pattern) except re.error as exc: # Invalid regular expression. raise InvalidQueryArgumentValueError(pattern, "a regular expression", format(exc)) @staticmethod def _normalize(s): """Normalize a Unicode string's representation (used on both patterns and matched values). """ return unicodedata.normalize('NFC', s) @classmethod def string_match(cls, pattern, value): return pattern.search(cls._normalize(value)) is not None class BooleanQuery(MatchQuery): """Matches a boolean field. Pattern should either be a boolean or a string reflecting a boolean. """ def __init__(self, field, pattern, fast=True): super().__init__(field, pattern, fast) if isinstance(pattern, str): self.pattern = util.str2bool(pattern) self.pattern = int(self.pattern) class BytesQuery(MatchQuery): """Match a raw bytes field (i.e., a path). This is a necessary hack to work around the `sqlite3` module's desire to treat `bytes` and `unicode` equivalently in Python 2. Always use this query instead of `MatchQuery` when matching on BLOB values. """ def __init__(self, field, pattern): super().__init__(field, pattern) # Use a buffer/memoryview representation of the pattern for SQLite # matching. This instructs SQLite to treat the blob as binary # rather than encoded Unicode. if isinstance(self.pattern, (str, bytes)): if isinstance(self.pattern, str): self.pattern = self.pattern.encode('utf-8') self.buf_pattern = memoryview(self.pattern) elif isinstance(self.pattern, memoryview): self.buf_pattern = self.pattern self.pattern = bytes(self.pattern) def col_clause(self): return self.field + " = ?", [self.buf_pattern] class NumericQuery(FieldQuery): """Matches numeric fields. A syntax using Ruby-style range ellipses (``..``) lets users specify one- or two-sided ranges. For example, ``year:2001..`` finds music released since the turn of the century. Raises InvalidQueryError when the pattern does not represent an int or a float. """ def _convert(self, s): """Convert a string to a numeric type (float or int). Return None if `s` is empty. Raise an InvalidQueryError if the string cannot be converted. """ # This is really just a bit of fun premature optimization. if not s: return None try: return int(s) except ValueError: try: return float(s) except ValueError: raise InvalidQueryArgumentValueError(s, "an int or a float") def __init__(self, field, pattern, fast=True): super().__init__(field, pattern, fast) parts = pattern.split('..', 1) if len(parts) == 1: # No range. self.point = self._convert(parts[0]) self.rangemin = None self.rangemax = None else: # One- or two-sided range. self.point = None self.rangemin = self._convert(parts[0]) self.rangemax = self._convert(parts[1]) def match(self, item): if self.field not in item: return False value = item[self.field] if isinstance(value, str): value = self._convert(value) if self.point is not None: return value == self.point else: if self.rangemin is not None and value < self.rangemin: return False if self.rangemax is not None and value > self.rangemax: return False return True def col_clause(self): if self.point is not None: return self.field + '=?', (self.point,) else: if self.rangemin is not None and self.rangemax is not None: return ('{0} >= ? AND {0} <= ?'.format(self.field), (self.rangemin, self.rangemax)) elif self.rangemin is not None: return f'{self.field} >= ?', (self.rangemin,) elif self.rangemax is not None: return f'{self.field} <= ?', (self.rangemax,) else: return '1', () class CollectionQuery(Query): """An abstract query class that aggregates other queries. Can be indexed like a list to access the sub-queries. """ def __init__(self, subqueries=()): self.subqueries = subqueries # Act like a sequence. def __len__(self): return len(self.subqueries) def __getitem__(self, key): return self.subqueries[key] def __iter__(self): return iter(self.subqueries) def __contains__(self, item): return item in self.subqueries def clause_with_joiner(self, joiner): """Return a clause created by joining together the clauses of all subqueries with the string joiner (padded by spaces). """ clause_parts = [] subvals = [] for subq in self.subqueries: subq_clause, subq_subvals = subq.clause() if not subq_clause: # Fall back to slow query. return None, () clause_parts.append('(' + subq_clause + ')') subvals += subq_subvals clause = (' ' + joiner + ' ').join(clause_parts) return clause, subvals def __repr__(self): return "{0.__class__.__name__}({0.subqueries!r})".format(self) def __eq__(self, other): return super().__eq__(other) and \ self.subqueries == other.subqueries def __hash__(self): """Since subqueries are mutable, this object should not be hashable. However and for conveniences purposes, it can be hashed. """ return reduce(mul, map(hash, self.subqueries), 1) class AnyFieldQuery(CollectionQuery): """A query that matches if a given FieldQuery subclass matches in any field. The individual field query class is provided to the constructor. """ def __init__(self, pattern, fields, cls): self.pattern = pattern self.fields = fields self.query_class = cls subqueries = [] for field in self.fields: subqueries.append(cls(field, pattern, True)) super().__init__(subqueries) def clause(self): return self.clause_with_joiner('or') def match(self, item): for subq in self.subqueries: if subq.match(item): return True return False def __repr__(self): return ("{0.__class__.__name__}({0.pattern!r}, {0.fields!r}, " "{0.query_class.__name__})".format(self)) def __eq__(self, other): return super().__eq__(other) and \ self.query_class == other.query_class def __hash__(self): return hash((self.pattern, tuple(self.fields), self.query_class)) class MutableCollectionQuery(CollectionQuery): """A collection query whose subqueries may be modified after the query is initialized. """ def __setitem__(self, key, value): self.subqueries[key] = value def __delitem__(self, key): del self.subqueries[key] class AndQuery(MutableCollectionQuery): """A conjunction of a list of other queries.""" def clause(self): return self.clause_with_joiner('and') def match(self, item): return all(q.match(item) for q in self.subqueries) class OrQuery(MutableCollectionQuery): """A conjunction of a list of other queries.""" def clause(self): return self.clause_with_joiner('or') def match(self, item): return any(q.match(item) for q in self.subqueries) class NotQuery(Query): """A query that matches the negation of its `subquery`, as a shorcut for performing `not(subquery)` without using regular expressions. """ def __init__(self, subquery): self.subquery = subquery def clause(self): clause, subvals = self.subquery.clause() if clause: return f'not ({clause})', subvals else: # If there is no clause, there is nothing to negate. All the logic # is handled by match() for slow queries. return clause, subvals def match(self, item): return not self.subquery.match(item) def __repr__(self): return "{0.__class__.__name__}({0.subquery!r})".format(self) def __eq__(self, other): return super().__eq__(other) and \ self.subquery == other.subquery def __hash__(self): return hash(('not', hash(self.subquery))) class TrueQuery(Query): """A query that always matches.""" def clause(self): return '1', () def match(self, item): return True class FalseQuery(Query): """A query that never matches.""" def clause(self): return '0', () def match(self, item): return False # Time/date queries. def _to_epoch_time(date): """Convert a `datetime` object to an integer number of seconds since the (local) Unix epoch. """ if hasattr(date, 'timestamp'): # The `timestamp` method exists on Python 3.3+. return int(date.timestamp()) else: epoch = datetime.fromtimestamp(0) delta = date - epoch return int(delta.total_seconds()) def _parse_periods(pattern): """Parse a string containing two dates separated by two dots (..). Return a pair of `Period` objects. """ parts = pattern.split('..', 1) if len(parts) == 1: instant = Period.parse(parts[0]) return (instant, instant) else: start = Period.parse(parts[0]) end = Period.parse(parts[1]) return (start, end) class Period: """A period of time given by a date, time and precision. Example: 2014-01-01 10:50:30 with precision 'month' represents all instants of time during January 2014. """ precisions = ('year', 'month', 'day', 'hour', 'minute', 'second') date_formats = ( ('%Y',), # year ('%Y-%m',), # month ('%Y-%m-%d',), # day ('%Y-%m-%dT%H', '%Y-%m-%d %H'), # hour ('%Y-%m-%dT%H:%M', '%Y-%m-%d %H:%M'), # minute ('%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S') # second ) relative_units = {'y': 365, 'm': 30, 'w': 7, 'd': 1} relative_re = '(?P<sign>[+|-]?)(?P<quantity>[0-9]+)' + \ '(?P<timespan>[y|m|w|d])' def __init__(self, date, precision): """Create a period with the given date (a `datetime` object) and precision (a string, one of "year", "month", "day", "hour", "minute", or "second"). """ if precision not in Period.precisions: raise ValueError(f'Invalid precision {precision}') self.date = date self.precision = precision @classmethod def parse(cls, string): """Parse a date and return a `Period` object or `None` if the string is empty, or raise an InvalidQueryArgumentValueError if the string cannot be parsed to a date. The date may be absolute or relative. Absolute dates look like `YYYY`, or `YYYY-MM-DD`, or `YYYY-MM-DD HH:MM:SS`, etc. Relative dates have three parts: - Optionally, a ``+`` or ``-`` sign indicating the future or the past. The default is the future. - A number: how much to add or subtract. - A letter indicating the unit: days, weeks, months or years (``d``, ``w``, ``m`` or ``y``). A "month" is exactly 30 days and a "year" is exactly 365 days. """ def find_date_and_format(string): for ord, format in enumerate(cls.date_formats): for format_option in format: try: date = datetime.strptime(string, format_option) return date, ord except ValueError: # Parsing failed. pass return (None, None) if not string: return None # Check for a relative date. match_dq = re.match(cls.relative_re, string) if match_dq: sign = match_dq.group('sign') quantity = match_dq.group('quantity') timespan = match_dq.group('timespan') # Add or subtract the given amount of time from the current # date. multiplier = -1 if sign == '-' else 1 days = cls.relative_units[timespan] date = datetime.now() + \ timedelta(days=int(quantity) * days) * multiplier return cls(date, cls.precisions[5]) # Check for an absolute date. date, ordinal = find_date_and_format(string) if date is None: raise InvalidQueryArgumentValueError(string, 'a valid date/time string') precision = cls.precisions[ordinal] return cls(date, precision) def open_right_endpoint(self): """Based on the precision, convert the period to a precise `datetime` for use as a right endpoint in a right-open interval. """ precision = self.precision date = self.date if 'year' == self.precision: return date.replace(year=date.year + 1, month=1) elif 'month' == precision: if (date.month < 12): return date.replace(month=date.month + 1) else: return date.replace(year=date.year + 1, month=1) elif 'day' == precision: return date + timedelta(days=1) elif 'hour' == precision: return date + timedelta(hours=1) elif 'minute' == precision: return date + timedelta(minutes=1) elif 'second' == precision: return date + timedelta(seconds=1) else: raise ValueError(f'unhandled precision {precision}') class DateInterval: """A closed-open interval of dates. A left endpoint of None means since the beginning of time. A right endpoint of None means towards infinity. """ def __init__(self, start, end): if start is not None and end is not None and not start < end: raise ValueError("start date {} is not before end date {}" .format(start, end)) self.start = start self.end = end @classmethod def from_periods(cls, start, end): """Create an interval with two Periods as the endpoints. """ end_date = end.open_right_endpoint() if end is not None else None start_date = start.date if start is not None else None return cls(start_date, end_date) def contains(self, date): if self.start is not None and date < self.start: return False if self.end is not None and date >= self.end: return False return True def __str__(self): return f'[{self.start}, {self.end})' class DateQuery(FieldQuery): """Matches date fields stored as seconds since Unix epoch time. Dates can be specified as ``year-month-day`` strings where only year is mandatory. The value of a date field can be matched against a date interval by using an ellipsis interval syntax similar to that of NumericQuery. """ def __init__(self, field, pattern, fast=True): super().__init__(field, pattern, fast) start, end = _parse_periods(pattern) self.interval = DateInterval.from_periods(start, end) def match(self, item): if self.field not in item: return False timestamp = float(item[self.field]) date = datetime.fromtimestamp(timestamp) return self.interval.contains(date) _clause_tmpl = "{0} {1} ?" def col_clause(self): clause_parts = [] subvals = [] if self.interval.start: clause_parts.append(self._clause_tmpl.format(self.field, ">=")) subvals.append(_to_epoch_time(self.interval.start)) if self.interval.end: clause_parts.append(self._clause_tmpl.format(self.field, "<")) subvals.append(_to_epoch_time(self.interval.end)) if clause_parts: # One- or two-sided interval. clause = ' AND '.join(clause_parts) else: # Match any date. clause = '1' return clause, subvals class DurationQuery(NumericQuery): """NumericQuery that allow human-friendly (M:SS) time interval formats. Converts the range(s) to a float value, and delegates on NumericQuery. Raises InvalidQueryError when the pattern does not represent an int, float or M:SS time interval. """ def _convert(self, s): """Convert a M:SS or numeric string to a float. Return None if `s` is empty. Raise an InvalidQueryError if the string cannot be converted. """ if not s: return None try: return util.raw_seconds_short(s) except ValueError: try: return float(s) except ValueError: raise InvalidQueryArgumentValueError( s, "a M:SS string or a float") # Sorting. class Sort: """An abstract class representing a sort operation for a query into the item database. """ def order_clause(self): """Generates a SQL fragment to be used in a ORDER BY clause, or None if no fragment is used (i.e., this is a slow sort). """ return None def sort(self, items): """Sort the list of objects and return a list. """ return sorted(items) def is_slow(self): """Indicate whether this query is *slow*, meaning that it cannot be executed in SQL and must be executed in Python. """ return False def __hash__(self): return 0 def __eq__(self, other): return type(self) == type(other) class MultipleSort(Sort): """Sort that encapsulates multiple sub-sorts. """ def __init__(self, sorts=None): self.sorts = sorts or [] def add_sort(self, sort): self.sorts.append(sort) def _sql_sorts(self): """Return the list of sub-sorts for which we can be (at least partially) fast. A contiguous suffix of fast (SQL-capable) sub-sorts are executable in SQL. The remaining, even if they are fast independently, must be executed slowly. """ sql_sorts = [] for sort in reversed(self.sorts): if not sort.order_clause() is None: sql_sorts.append(sort) else: break sql_sorts.reverse() return sql_sorts def order_clause(self): order_strings = [] for sort in self._sql_sorts(): order = sort.order_clause() order_strings.append(order) return ", ".join(order_strings) def is_slow(self): for sort in self.sorts: if sort.is_slow(): return True return False def sort(self, items): slow_sorts = [] switch_slow = False for sort in reversed(self.sorts): if switch_slow: slow_sorts.append(sort) elif sort.order_clause() is None: switch_slow = True slow_sorts.append(sort) else: pass for sort in slow_sorts: items = sort.sort(items) return items def __repr__(self): return f'MultipleSort({self.sorts!r})' def __hash__(self): return hash(tuple(self.sorts)) def __eq__(self, other): return super().__eq__(other) and \ self.sorts == other.sorts class FieldSort(Sort): """An abstract sort criterion that orders by a specific field (of any kind). """ def __init__(self, field, ascending=True, case_insensitive=True): self.field = field self.ascending = ascending self.case_insensitive = case_insensitive def sort(self, objs): # TODO: Conversion and null-detection here. In Python 3, # comparisons with None fail. We should also support flexible # attributes with different types without falling over. def key(item): field_val = item.get(self.field, '') if self.case_insensitive and isinstance(field_val, str): field_val = field_val.lower() return field_val return sorted(objs, key=key, reverse=not self.ascending) def __repr__(self): return '<{}: {}{}>'.format( type(self).__name__, self.field, '+' if self.ascending else '-', ) def __hash__(self): return hash((self.field, self.ascending)) def __eq__(self, other): return super().__eq__(other) and \ self.field == other.field and \ self.ascending == other.ascending class FixedFieldSort(FieldSort): """Sort object to sort on a fixed field. """ def order_clause(self): order = "ASC" if self.ascending else "DESC" if self.case_insensitive: field = '(CASE ' \ 'WHEN TYPEOF({0})="text" THEN LOWER({0}) ' \ 'WHEN TYPEOF({0})="blob" THEN LOWER({0}) ' \ 'ELSE {0} END)'.format(self.field) else: field = self.field return f"{field} {order}" class SlowFieldSort(FieldSort): """A sort criterion by some model field other than a fixed field: i.e., a computed or flexible field. """ def is_slow(self): return True class NullSort(Sort): """No sorting. Leave results unsorted.""" def sort(self, items): return items def __nonzero__(self): return self.__bool__() def __bool__(self): return False def __eq__(self, other): return type(self) == type(other) or other is None def __hash__(self): return 0
beetbox/beets
beets/dbcore/query.py
Python
mit
29,107
29.60673
79
0.577593
false
require_relative '../animation' module NixonPi module Animations class CountFromToAnimation < Animation register :count_from_to, self accepted_commands :start_value, :single_digit? # TODO: unfinished and untested def initialize(options = {}) super(options) @options[:single_digit?] ||= true from = @options[:start_value] to = from if @options[:single_digit?] from.each_char { |f| to[i] = (f.to_i += 1).to_s } from.reverse.each_char.with_index do |number| @output << number end end end def write handle_output_on_tick(@output.shift) end end end end
danielkummer/nixon-pi
lib/nixonpi/animations/tube/count_up_all_animation.rb
Ruby
mit
704
23.275862
59
0.572443
false
FROM python:3 ADD ./simplesocial /simplesocial WORKDIR /simplesocial RUN pip install -r requirements.txt EXPOSE 8000 CMD [ "python", "manage.py", "runserver", "0.0.0.0:8000"]
srijannnd/Login-and-Register-App-in-Django
Dockerfile
Dockerfile
mit
179
15.363636
57
0.726257
false
--- layout: post title: "Class Based Views" date: 2013-05-13 07:04 tags: [python, django, yakindanegitim] icons: [python] --- Web development is a bit repetitive and web frameworks try to reduce this burden. One of the best features of Django for making object manipulation easier is class based views(CBV). We are usually good to go by only setting model in class based views and in the background, it handles all form processing. There is also function based views(FBV) which have the same power and some more. I think, difference between them can be best explained by the analogy of C vs Python. Python is compact and writing Python is more fun. That's why it enables to do lots of work in a few lines. On the other hand, C is verbose and fast since there is no boilerplate and you directly do what you want but whenever you go off the standard lines and need some more control, you have to use C. Even if CBVs get attention recently, FBVs aren't deprecated. Python gets traction but C is always [there](http://www.tiobe.com/content/paperinfo/tpci/index.html) so which one should we use? CBVs enables to write more compact code as a result of more enjoyable reading, that is quite important for maintenance. Moreover, CBVs are better to write tests for. Therefore, we should stick to them when possible. Mainly, CBVs have two disadvantages; namely, a very steep learning curve and the difficulty of handling multiple forms. 1- How is context data created? How is object retrieved? How is form validated? In FBVs, most of the time, we write these logic ourselves explicitly but in CBVs, we should aware of how and when our methods are called. Getting used to it takes some time but later, I think, CBV makes us more productive. 2- Even if inline formsets makes possible multi model form handling in CBVs, it is hard. It seems this is the only reason to use FBVs. Now, I would like to show inline formset usage via CBVs with an example(adding album with songs): Our models: ``` python # models.py from django.db import models class Album(models.Model): name = models.CharField(max_length=255) class Song(models.Model): name = models.CharField(max_length=255) lyrics = models.TextField(blank=True, null=True) album = models.ForeignKey(Album) ``` Our forms: ``` python # forms.py from django.forms import ModelForm from django.forms.models import inlineformset_factory from .models import Album, Song class AlbumForm(ModelForm): class Meta: model = Album AlbumSongFormSet = inlineformset_factory(Album, Song, form=AlbumForm, extra=3) ``` Our create view: ``` python # views.py from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.views.generic import CreateView from django.utils.text import slugify from django.utils.translation import ugettext as _ from braces.views import LoginRequiredMixin from core.mixins import ActionMixin from .models import Album, Song from .forms import AlbumForm class AlbumCreateView(LoginRequiredMixin, ActionMixin, CreateView): model = Album form_class = AlbumForm template_name = 'music/album_add.html' action = _("Album is successfully added") # ActionMixin is written in an earlier post def form_valid(self, form): context = self.get_context_data() albumsong_form = context['albumsong_formset'] if albumsong_form.is_valid(): self.object = form.save(commit=False) # to set extra attributes that doesn't come from form self.object.artist = Artist.objects.get(profile__username__exact=self.kwargs.get("username")) self.object.slug = slugify(self.object.name) self.object.save() for song_form in albumsong_form: song = song_form.save(commit=False) song.slug = slugify(song.name) song.album = self.object song.save() return HttpResponseRedirect(self.get_success_url()) else: return self.render_to_response(self.get_context_data(form=form)) def form_invalid(self, form): return self.render_to_response(self.get_context_data(form=form)) def get_context_data(self, **kwargs): context = super(AlbumCreateView, self).get_context_data(**kwargs) if self.request.POST: context['albumsong_formset'] = AlbumSongFormSet(self.request.POST) else: context['albumsong_formset'] = AlbumSongFormSet() return context def get_success_url(self): return reverse('artist_detail', kwargs=self.kwargs) ``` And finally, our urlconf: ``` python # urls.py from django.conf.urls import patterns, url from .views import * urlpatterns = patterns('', url(r'^(?P<username>[-_\.\w]+)/add/$', AlbumCreateView.as_view(), name="album_add"), ) ``` That's it!
ferhatelmas/ferhatelmas.github.com
hack/yakindanegitim/_posts/2013-05-13-class-based-views.markdown
Markdown
mit
4,908
38.580645
469
0.720253
false
local Swapout = require('sconce.Swapout') return function(tester) local suite = torch.TestSuite() function suite.test_swapout_always_add() local swapout = Swapout.new(1.0) local actual = swapout:forward({torch.Tensor{1, 2}, torch.Tensor{3, 2}}) local expected = torch.Tensor{4, 4} tester:eq(actual, expected) end function suite.test_swapout_never_add() local swapout = Swapout.new(0.0) local actual = swapout:forward({torch.Tensor{1, 2}, torch.Tensor{3, 2}}) local expected = torch.Tensor{0, 0} tester:eq(actual, expected) end function suite.test_swapout_sometimes_add() torch.manualSeed(1234) local swapout = Swapout.new(0.5) local actual = swapout:forward({ torch.Tensor(4):fill(1), torch.Tensor(4):fill(2) }) local expected = torch.Tensor{3, 1, 0, 0} tester:eq(actual, expected) end tester:add(suite) return suite end
anibali/sconce
test/test_swapout.lua
Lua
mit
907
26.484848
76
0.674752
false
"use strict"; var http_1 = require("@angular/http"); var AppSettings = (function () { function AppSettings() { } Object.defineProperty(AppSettings, "API_OPTIONS", { get: function () { var headers = new http_1.Headers({ 'Content-Type': 'application/json' }), options = new http_1.RequestOptions({ headers: headers }); return options; }, enumerable: true, configurable: true }); Object.defineProperty(AppSettings, "API_URL", { get: function () { var devMode = true, prodPath = "http://cristi.red:8080/api", apiSecured = false, apiHost = "localhost", apiPort = "8080/api"; return (devMode) ? ("http" + ((apiSecured) ? "s" : "") + "://" + apiHost + ":" + apiPort) : prodPath; }, enumerable: true, configurable: true }); Object.defineProperty(AppSettings, "SOCKETG_URL", { get: function () { var devMode = true, prodPath = "http://cristi.red:8080/gs-guide-websocket", local = "http://localhost:8080/gs-guide-websocket"; return (devMode) ? local : prodPath; }, enumerable: true, configurable: true }); return AppSettings; }()); exports.AppSettings = AppSettings; //# sourceMappingURL=app.settings.js.map
cristirosu/rpg-scheduler-front
src/app/shared/services/app.settings.js
JavaScript
mit
1,301
38.454545
144
0.583397
false
const fs = require('fs') const path = require('path') const {generateBabelEnvLoader, getConfig} = require('./common') const buildCache = {} module.exports = (params) => { const baseConfig = getConfig(params) const config = Object.assign({}, baseConfig) config.outputPath = path.join(__dirname, '../dist-' + config.app) return { entry: config.sourcePath + '/tools/initdb.js', context: config.sourcePath, target: 'node', output: { path: config.outputPath, filename: 'initdb.js' }, stats: { colors: true, reasons: true, chunks: false }, cache: buildCache, module: { rules: [generateBabelEnvLoader({node: 'current'}, config)] }, resolve: { extensions: ['.js', '.jsx'], alias: baseConfig.aliases }, devServer: { contentBase: config.sourcePath } } }
bourbest/keeptrack
client/tasks/tool-initdb.js
JavaScript
mit
868
21.842105
67
0.602535
false
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using tomware.Microwf.Domain; using tomware.Microwf.Infrastructure; namespace tomware.Microwf.Engine { public interface IJobQueueControllerService { Task<IEnumerable<WorkItemViewModel>> GetSnapshotAsync(); Task<PaginatedList<WorkItemViewModel>> GetUpCommingsAsync(PagingParameters parameters); Task<PaginatedList<WorkItemViewModel>> GetFailedAsync(PagingParameters parameters); Task Reschedule(WorkItemViewModel model); } public class JobQueueControllerService : IJobQueueControllerService { private readonly IJobQueueService service; private readonly IWorkItemService workItemService; public JobQueueControllerService( IJobQueueService service, IWorkItemService workItemService ) { this.service = service; this.workItemService = workItemService; } public async Task<IEnumerable<WorkItemViewModel>> GetSnapshotAsync() { var result = this.service.GetSnapshot(); return await Task.FromResult(result.Select(x => ToViewModel(x))); } public async Task<PaginatedList<WorkItemViewModel>> GetUpCommingsAsync( PagingParameters parameters ) { var result = await this.workItemService.GetUpCommingsAsync(parameters); return new PaginatedList<WorkItemViewModel>( result.Select(x => ToViewModel(x)), result.AllItemsCount, parameters.PageIndex, parameters.PageSize ); } public async Task<PaginatedList<WorkItemViewModel>> GetFailedAsync( PagingParameters parameters ) { var result = await this.workItemService.GetFailedAsync(parameters); return new PaginatedList<WorkItemViewModel>( result.Select(x => ToViewModel(x)), result.AllItemsCount, parameters.PageIndex, parameters.PageSize ); } public async Task Reschedule(WorkItemViewModel model) { await this.workItemService.Reschedule(new Infrastructure.WorkItemDto { Id = model.Id, DueDate = model.DueDate }); } private WorkItemViewModel ToViewModel(Domain.WorkItemDto dto) { return PropertyMapper<Domain.WorkItemDto, WorkItemViewModel>.From(dto); // return new WorkItemViewModel // { // Id = dto.Id, // TriggerName = dto.TriggerName, // EntityId = dto.EntityId, // WorkflowType = dto.WorkflowType, // Retries = dto.Retries, // Error = dto.Error, // DueDate = dto.DueDate // }; } } }
thomasduft/microwf
src/microwf.AspNetCoreEngine/Services/JobQueueControllerService.cs
C#
mit
2,595
26.913978
91
0.690559
false
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__wchar_t_connect_socket_w32spawnl_18.c Label Definition File: CWE78_OS_Command_Injection.strings.label.xml Template File: sources-sink-18.tmpl.c */ /* * @description * CWE: 78 OS Command Injection * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Fixed string * Sink: w32spawnl * BadSink : execute command with wspawnl * Flow Variant: 18 Control flow: goto statements * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 #define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" #define COMMAND_INT L"cmd.exe" #define COMMAND_ARG1 L"/c" #define COMMAND_ARG2 L"dir" #define COMMAND_ARG3 data #else /* NOT _WIN32 */ #include <unistd.h> #define COMMAND_INT_PATH L"/bin/sh" #define COMMAND_INT L"sh" #define COMMAND_ARG1 L"ls" #define COMMAND_ARG2 L"-la" #define COMMAND_ARG3 data #endif #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else /* NOT _WIN32 */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define IP_ADDRESS "127.0.0.1" #include <process.h> #ifndef OMITBAD void CWE78_OS_Command_Injection__wchar_t_connect_socket_w32spawnl_18_bad() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; goto source; source: { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; wchar_t *replace; SOCKET connectSocket = INVALID_SOCKET; size_t dataLen = wcslen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* Abort on error or the connection was closed */ recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(wchar_t)] = L'\0'; /* Eliminate CRLF */ replace = wcschr(data, L'\r'); if (replace) { *replace = L'\0'; } replace = wcschr(data, L'\n'); if (replace) { *replace = L'\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } /* wspawnl - specify the path where the command is located */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ _wspawnl(_P_WAIT, COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() - use goodsource and badsink by reversing the blocks on the goto statement */ static void goodG2B() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; goto source; source: /* FIX: Append a fixed string to data (not user / external input) */ wcscat(data, L"*.*"); /* wspawnl - specify the path where the command is located */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ _wspawnl(_P_WAIT, COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); } void CWE78_OS_Command_Injection__wchar_t_connect_socket_w32spawnl_18_good() { goodG2B(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE78_OS_Command_Injection__wchar_t_connect_socket_w32spawnl_18_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE78_OS_Command_Injection__wchar_t_connect_socket_w32spawnl_18_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
maurer/tiamat
samples/Juliet/testcases/CWE78_OS_Command_Injection/s05/CWE78_OS_Command_Injection__wchar_t_connect_socket_w32spawnl_18.c
C
mit
5,742
28.221053
113
0.59596
false
require "pivotal/sass/version" module Pivotal module Sass class Engine < ::Rails::Engine end end end
pivotal/pivotal-styles-sass
lib/pivotal/sass.rb
Ruby
mit
114
13.25
34
0.692982
false
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password', 200); $table->string('provider'); $table->string('provider_id'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
Ranthalion/LevelUp
database/migrations/2014_10_12_000000_create_users_table.php
PHP
mit
787
20.861111
61
0.519695
false
<html><body> <h4>Windows 10 x64 (19041.208) 2004</h4><br> <h2>_HEAP_DESCRIPTOR_KEY</h2> <font face="arial"> +0x000 Key : Uint4B<br> +0x000 EncodedCommittedPageCount : Pos 0, 16 Bits<br> +0x000 LargePageCost : Pos 16, 8 Bits<br> +0x000 UnitCount : Pos 24, 8 Bits<br> </font></body></html>
epikcraw/ggool
public/Windows 10 x64 (19041.208) 2004/_HEAP_DESCRIPTOR_KEY.html
HTML
mit
328
39.25
58
0.603659
false
<?php /* * */ namespace RDF\JobDefinitionFormatBundle\Type; /** * * * @author Richard Fullmer <richardfullmer@gmail.com> */ class CMYKColor { /** * @var float */ protected $cyan; /** * @var float */ protected $magenta; /** * @var float */ protected $yellow; /** * @var float */ protected $black; /** * @param float $cyan * @param float $magenta * @param float $yellow * @param float $black */ public function __construct($cyan, $magenta, $yellow, $black) { $this->cyan = (float) $cyan; $this->magenta = (float) $magenta; $this->yellow = (float) $yellow; $this->black = (float) $black; } /** * @param float $black */ public function setBlack($black) { $this->black = (float) $black; } /** * @return float */ public function getBlack() { return $this->black; } /** * @param float $cyan */ public function setCyan($cyan) { $this->cyan = (float) $cyan; } /** * @return float */ public function getCyan() { return $this->cyan; } /** * @param float $magenta */ public function setMagenta($magenta) { $this->magenta = (float) $magenta; } /** * @return float */ public function getMagenta() { return $this->magenta; } /** * @param float $yellow */ public function setYellow($yellow) { $this->yellow = (float) $yellow; } /** * @return float */ public function getYellow() { return $this->yellow; } }
richardfullmer/RDFJobDefinitionFormatBundle
Type/CMYKColor.php
PHP
mit
1,730
14.309735
65
0.478035
false
<html> <head> <title> Install SEO Commerce</title> <META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW"> <style> #container { margin:auto; } label, input { display: block; } </style> </head> <body> <div class="container"> <form action="pasang_p.php" method="POST"> <label> Nama Situs </label> <input type="text" name="s_name"> <label> Author (Nama Pemilik) </label> <input type="text" name="s_author"> <label> Username </label> <input type="text" name="a_username"> <label> Password </label> <input type="password" name="a_password"> <input type="submit" value="kirim"> </form> </div> </body> <html>
idmahardika/SEO_commerce
pasang.php
PHP
mit
634
20.896552
49
0.634069
false
Turbocoin Core version 0.9.0 is now available from: https://turbocoin.us/bin/0.9.0/ This is a new major version release, bringing both new features and bug fixes. Please report bugs using the issue tracker at github: https://github.com/turbocoin/turbocoin/issues How to Upgrade -------------- If you are running an older version, shut it down. Wait until it has completely shut down (which might take a few minutes for older versions), uninstall all earlier versions of Turbocoin, then run the installer (on Windows) or just copy over /Applications/Turbocoin-Qt (on Mac) or turbocoind/turbocoin-qt (on Linux). If you are upgrading from version 0.7.2 or earlier, the first time you run 0.9.0 your blockchain files will be re-indexed, which will take anywhere from 30 minutes to several hours, depending on the speed of your machine. On Windows, do not forget to uninstall all earlier versions of the Turbocoin client first, especially if you are switching to the 64-bit version. Windows 64-bit installer ------------------------- New in 0.9.0 is the Windows 64-bit version of the client. There have been frequent reports of users running out of virtual memory on 32-bit systems during the initial sync. Because of this it is recommended to install the 64-bit version if your system supports it. NOTE: Release candidate 2 Windows binaries are not code-signed; use PGP and the SHA256SUMS.asc file to make sure your binaries are correct. In the final 0.9.0 release, Windows setup.exe binaries will be code-signed. OSX 10.5 / 32-bit no longer supported ------------------------------------- 0.9.0 drops support for older Macs. The minimum requirements are now: * A 64-bit-capable CPU (see http://support.apple.com/kb/ht3696); * Mac OS 10.6 or later (see https://support.apple.com/kb/ht1633). Downgrading warnings -------------------- The 'chainstate' for this release is not always compatible with previous releases, so if you run 0.9 and then decide to switch back to a 0.8.x release you might get a blockchain validation error when starting the old release (due to 'pruned outputs' being omitted from the index of unspent transaction outputs). Running the old release with the -reindex option will rebuild the chainstate data structures and correct the problem. Also, the first time you run a 0.8.x release on a 0.9 wallet it will rescan the blockchain for missing spent coins, which will take a long time (tens of minutes on a typical machine). Rebranding to Turbocoin Core --------------------------- To reduce confusion between Turbocoin-the-network and Turbocoin-the-software we have renamed the reference client to Turbocoin Core. OP_RETURN and data in the block chain ------------------------------------- On OP_RETURN: There was been some confusion and misunderstanding in the community, regarding the OP_RETURN feature in 0.9 and data in the blockchain. This change is not an endorsement of storing data in the blockchain. The OP_RETURN change creates a provably-prunable output, to avoid data storage schemes -- some of which were already deployed -- that were storing arbitrary data such as images as forever-unspendable TX outputs, bloating turbocoin's UTXO database. Storing arbitrary data in the blockchain is still a bad idea; it is less costly and far more efficient to store non-currency data elsewhere. Autotools build system ----------------------- For 0.9.0 we switched to an autotools-based build system instead of individual (q)makefiles. Using the standard "./autogen.sh; ./configure; make" to build Turbocoin-Qt and turbocoind makes it easier for experienced open source developers to contribute to the project. Be sure to check doc/build-*.md for your platform before building from source. Turbocoin-cli ------------- Another change in the 0.9 release is moving away from the turbocoind executable functioning both as a server and as a RPC client. The RPC client functionality ("tell the running turbocoin daemon to do THIS") was split into a separate executable, 'turbocoin-cli'. The RPC client code will eventually be removed from turbocoind, but will be kept for backwards compatibility for a release or two. `walletpassphrase` RPC ----------------------- The behavior of the `walletpassphrase` RPC when the wallet is already unlocked has changed between 0.8 and 0.9. The 0.8 behavior of `walletpassphrase` is to fail when the wallet is already unlocked: > walletpassphrase 1000 walletunlocktime = now + 1000 > walletpassphrase 10 Error: Wallet is already unlocked (old unlock time stays) The new behavior of `walletpassphrase` is to set a new unlock time overriding the old one: > walletpassphrase 1000 walletunlocktime = now + 1000 > walletpassphrase 10 walletunlocktime = now + 10 (overriding the old unlock time) Transaction malleability-related fixes -------------------------------------- This release contains a few fixes for transaction ID (TXID) malleability issues: - -nospendzeroconfchange command-line option, to avoid spending zero-confirmation change - IsStandard() transaction rules tightened to prevent relaying and mining of mutated transactions - Additional information in listtransactions/gettransaction output to report wallet transactions that conflict with each other because they spend the same outputs. - Bug fixes to the getbalance/listaccounts RPC commands, which would report incorrect balances for double-spent (or mutated) transactions. - New option: -zapwallettxes to rebuild the wallet's transaction information Transaction Fees ---------------- This release drops the default fee required to relay transactions across the network and for miners to consider the transaction in their blocks to 0.01mTURBO per kilobyte. Note that getting a transaction relayed across the network does NOT guarantee that the transaction will be accepted by a miner; by default, miners fill their blocks with 50 kilobytes of high-priority transactions, and then with 700 kilobytes of the highest-fee-per-kilobyte transactions. The minimum relay/mining fee-per-kilobyte may be changed with the minrelaytxfee option. Note that previous releases incorrectly used the mintxfee setting to determine which low-priority transactions should be considered for inclusion in blocks. The wallet code still uses a default fee for low-priority transactions of 0.1mTURBO per kilobyte. During periods of heavy transaction volume, even this fee may not be enough to get transactions confirmed quickly; the mintxfee option may be used to override the default. 0.9.0 Release notes ======================= RPC: - New notion of 'conflicted' transactions, reported as confirmations: -1 - 'listreceivedbyaddress' now provides tx ids - Add raw transaction hex to 'gettransaction' output - Updated help and tests for 'getreceivedby(account|address)' - In 'getblock', accept 2nd 'verbose' parameter, similar to getrawtransaction, but defaulting to 1 for backward compatibility - Add 'verifychain', to verify chain database at runtime - Add 'dumpwallet' and 'importwallet' RPCs - 'keypoolrefill' gains optional size parameter - Add 'getbestblockhash', to return tip of best chain - Add 'chainwork' (the total work done by all blocks since the genesis block) to 'getblock' output - Make RPC password resistant to timing attacks - Clarify help messages and add examples - Add 'getrawchangeaddress' call for raw transaction change destinations - Reject insanely high fees by default in 'sendrawtransaction' - Add RPC call 'decodescript' to decode a hex-encoded transaction script - Make 'validateaddress' provide redeemScript - Add 'getnetworkhashps' to get the calculated network hashrate - New RPC 'ping' command to request ping, new 'pingtime' and 'pingwait' fields in 'getpeerinfo' output - Adding new 'addrlocal' field to 'getpeerinfo' output - Add verbose boolean to 'getrawmempool' - Add rpc command 'getunconfirmedbalance' to obtain total unconfirmed balance - Explicitly ensure that wallet is unlocked in `importprivkey` - Add check for valid keys in `importprivkey` Command-line options: - New option: -nospendzeroconfchange to never spend unconfirmed change outputs - New option: -zapwallettxes to rebuild the wallet's transaction information - Rename option '-tor' to '-onion' to better reflect what it does - Add '-disablewallet' mode to let turbocoind run entirely without wallet (when built with wallet) - Update default '-rpcsslciphers' to include TLSv1.2 - make '-logtimestamps' default on and rework help-message - RPC client option: '-rpcwait', to wait for server start - Remove '-logtodebugger' - Allow `-noserver` with turbocoind Block-chain handling and storage: - Update leveldb to 1.15 - Check for correct genesis (prevent cases where a datadir from the wrong network is accidentally loaded) - Allow txindex to be removed and add a reindex dialog - Log aborted block database rebuilds - Store orphan blocks in serialized form, to save memory - Limit the number of orphan blocks in memory to 750 - Fix non-standard disconnected transactions causing mempool orphans - Add a new checkpoint at block 279,000 Wallet: - Bug fixes and new regression tests to correctly compute the balance of wallets containing double-spent (or mutated) transactions - Store key creation time. Calculate whole-wallet birthday. - Optimize rescan to skip blocks prior to birthday - Let user select wallet file with -wallet=foo.dat - Consider generated coins mature at 101 instead of 120 blocks - Improve wallet load time - Don't count txins for priority to encourage sweeping - Don't create empty transactions when reading a corrupted wallet - Fix rescan to start from beginning after importprivkey - Only create signatures with low S values Mining: - Increase default -blockmaxsize/prioritysize to 750K/50K - 'getblocktemplate' does not require a key to create a block template - Mining code fee policy now matches relay fee policy Protocol and network: - Drop the fee required to relay a transaction to 0.01mTURBO per kilobyte - Send tx relay flag with version - New 'reject' P2P message (BIP 0061, see https://gist.github.com/gavinandresen/7079034 for draft) - Dump addresses every 15 minutes instead of 10 seconds - Relay OP_RETURN data TxOut as standard transaction type - Remove CENT-output free transaction rule when relaying - Lower maximum size for free transaction creation - Send multiple inv messages if mempool.size > MAX_INV_SZ - Split MIN_PROTO_VERSION into INIT_PROTO_VERSION and MIN_PEER_PROTO_VERSION - Do not treat fFromMe transaction differently when broadcasting - Process received messages one at a time without sleeping between messages - Improve logging of failed connections - Bump protocol version to 70002 - Add some additional logging to give extra network insight - Added new DNS seed from turbocoinstats.com Validation: - Log reason for non-standard transaction rejection - Prune provably-unspendable outputs, and adapt consistency check for it. - Detect any sufficiently long fork and add a warning - Call the -alertnotify script when we see a long or invalid fork - Fix multi-block reorg transaction resurrection - Reject non-canonically-encoded serialization sizes - Reject dust amounts during validation - Accept nLockTime transactions that finalize in the next block Build system: - Switch to autotools-based build system - Build without wallet by passing `--disable-wallet` to configure, this removes the BerkeleyDB dependency - Upgrade gitian dependencies (libpng, libz, libupnpc, boost, openssl) to more recent versions - Windows 64-bit build support - Solaris compatibility fixes - Check integrity of gitian input source tarballs - Enable full GCC Stack-smashing protection for all OSes GUI: - Switch to Qt 5.2.0 for Windows build - Add payment request (BIP 0070) support - Improve options dialog - Show transaction fee in new send confirmation dialog - Add total balance in overview page - Allow user to choose data directory on first start, when data directory is missing, or when the -choosedatadir option is passed - Save and restore window positions - Add vout index to transaction id in transactions details dialog - Add network traffic graph in debug window - Add open URI dialog - Add Coin Control Features - Improve receive coins workflow: make the 'Receive' tab into a form to request payments, and move historical address list functionality to File menu. - Rebrand to `Turbocoin Core` - Move initialization/shutdown to a thread. This prevents "Not responding" messages during startup. Also show a window during shutdown. - Don't regenerate autostart link on every client startup - Show and store message of normal turbocoin:URI - Fix richtext detection hang issue on very old Qt versions - OS X: Make use of the 10.8+ user notification center to display Growl-like notifications - OS X: Added NSHighResolutionCapable flag to Info.plist for better font rendering on Retina displays. - OS X: Fix turbocoin-qt startup crash when clicking dock icon - Linux: Fix Gnome turbocoin: URI handler Miscellaneous: - Add Linux script (contrib/qos/tc.sh) to limit outgoing bandwidth - Add '-regtest' mode, similar to testnet but private with instant block generation with 'setgenerate' RPC. - Add 'linearize.py' script to contrib, for creating bootstrap.dat - Add separate turbocoin-cli client Credits -------- Thanks to everyone who contributed to this release: - Andrey - Ashley Holman - b6393ce9-d324-4fe1-996b-acf82dbc3d53 - bitsofproof - Brandon Dahler - Calvin Tam - Christian Decker - Christian von Roques - Christopher Latham - Chuck - coblee - constantined - Cory Fields - Cozz Lovan - daniel - Daniel Larimer - David Hill - Dmitry Smirnov - Drak - Eric Lombrozo - fanquake - fcicq - Florin - frewil - Gavin Andresen - Gregory Maxwell - gubatron - Guillermo Céspedes Tabárez - Haakon Nilsen - HaltingState - Han Lin Yap - harry - Ian Kelling - Jeff Garzik - Johnathan Corgan - Jonas Schnelli - Josh Lehan - Josh Triplett - Julian Langschaedel - Kangmo - Lake Denman - Luke Dashjr - Mark Friedenbach - Matt Corallo - Michael Bauer - Michael Ford - Michagogo - Midnight Magic - Mike Hearn - Nils Schneider - Noel Tiernan - Olivier Langlois - patrick s - Patrick Strateman - paveljanik - Peter Todd - phantomcircuit - phelixbtc - Philip Kaufmann - Pieter Wuille - Rav3nPL - R E Broadley - regergregregerrge - Robert Backhaus - Roman Mindalev - Rune K. Svendsen - Ryan Niebur - Scott Ellis - Scott Willeke - Sergey Kazenyuk - Shawn Wilkinson - Sined - sje - Subo1978 - super3 - Tamas Blummer - theuni - Thomas Holenstein - Timon Rapp - Timothy Stranex - Tom Geller - Torstein Husebø - Vaclav Vobornik - vhf / victor felder - Vinnie Falco - Warren Togami - Wil Bown - Wladimir J. van der Laan
Phonemetra/TurboCoin
doc/release-notes/release-notes-0.9.0.md
Markdown
mit
14,787
34.970803
86
0.770833
false
{{ define "main" }} <!-- Header --> {{ partial "header" . }} <div class="container"> <section id="projects"> <h4 class="my-5">{{ .Site.Data.projects.name }}</h4> <div class="panel"> <div class="panel-body"> {{ range $el := .Site.Data.projects.source }} <h5> <i class="{{ .icon }}"></i>&nbsp;&nbsp; <b><a href="{{ .url }}">{{ $el.name }}</a></b>&nbsp;-&nbsp;{{ $el.description }} </h5> {{ end }} </div> </div> </section> </div> {{ end }}
nurlansu/hugo-sustain
layouts/_default/projects.html
HTML
mit
560
27
94
0.423214
false
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DebtSnowBall2017 { class LoanList { private List<Loan> loanList; public LoanList() { this.loanList = new List<Loan>(); } public void addLoan(Loan newLoan) { this.loanList.Add(newLoan); this.loanList.Sort(delegate(Loan L1, Loan L2){ return L1.getTotalOwed().CompareTo(L2.getTotalOwed()); }); } public void printToScreen(TableLayoutPanel panel) { panel.Controls.Clear(); foreach(Loan loan in loanList) { Label principle = new Label(); principle.Text = Convert.ToString(loan.getPrinciple()); panel.Controls.Add(principle); Label interest = new Label(); interest.Text = Convert.ToString(loan.getInterest() * 100) + "%"; panel.Controls.Add(interest); Label monthsToPay = new Label(); if (loan.getMonthsToPay() <= 0) { monthsToPay.Text = "Not Yet Calculated"; } else { monthsToPay.Text = Convert.ToString(loan.getMonthsToPay()); } panel.Controls.Add(monthsToPay); Label totalPaid = new Label(); if (loan.getTotalPaid() < 0) { totalPaid.Text = "Not Yet Calculated"; } else { totalPaid.Text = Convert.ToString(loan.getTotalPaid()); } panel.Controls.Add(totalPaid); } } public bool allPaid() { foreach(Loan loan in loanList) { if (!loan.isFullyPaid()) { return false; } } return true; } public void calculate(double salary) { while (!allPaid()) { double thisMonthsSalary = salary; foreach (Loan nextLoan in this.loanList) { thisMonthsSalary = nextLoan.payMonthlyBill(thisMonthsSalary); } foreach (Loan nextLoan in this.loanList) { if (!nextLoan.isFullyPaid()) { nextLoan.payExtra(thisMonthsSalary); break; } } } } } }
passanpm/DebtSnowBall
DebtSnowBall2017/DebtSnowBall2017/LoanList.cs
C#
mit
2,759
27.42268
117
0.449764
false
--- layout: default title: Отправить совет! --- <div class="grid_8 alpha omega white"> <h2>Отправить совет!</h2> <iframe src="http://spreadsheets.google.com/embeddedform?key=pNxLaOX4yIJnLpmHYEDxXXQ" width="590" height="616" frameborder="0" marginheight="0" marginwidth="0">Загрузка...</iframe> </div>
gitready/ru
submit.html
HTML
mit
341
37.125
182
0.72459
false
package render import ( "github.com/gin-gonic/gin" ) /* ================================================================================ * Render 工具模块 * qq group: 582452342 * email : 2091938785@qq.com * author : 美丽的地球啊 - mliu * ================================================================================ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * 输出错误消息 * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ func Error(c *gin.Context, msg string) { String(c, msg, 400) }
sanxia/ging
render/error.go
GO
mit
601
28.947368
86
0.261863
false
/* * _____ _ _ _ _____ _ _ _ _____ _ __ _____ _____ * / ___| | | | | | | |_ _| | | / / | | | ____| | | / / | ____| | _ \ * | | | | | | | | | | | | / / | | | |__ | | __ / / | |__ | |_| | * | | _ | | | | | | | | | | / / | | | __| | | / | / / | __| | _ / * | |_| | | |___ | |_| | | | | |/ / | | | |___ | |/ |/ / | |___ | | \ \ * \_____/ |_____| \_____/ |_| |___/ |_| |_____| |___/|___/ |_____| |_| \_\ * * Version 0.9 * Bruno Levy, August 2006 * INRIA, Project ALICE * */ #include "glut_viewer_gui.h" #include <GLsdk/gl_stuff.h> #include <GL/glut.h> #include <iostream> #include <stdarg.h> #include <math.h> #include <stdio.h> namespace GlutViewerGUI { // ------------------- Primitives for internal use -------------------------------------- static void printf_xy(GLfloat x, GLfloat y, const char *format, ...) { va_list args; char buffer[1024], *p; va_start(args, format); vsprintf(buffer, format, args); va_end(args); glPushMatrix(); glTranslatef(x, y, 0); for (p = buffer; *p; p++) { glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, *p); } glPopMatrix(); } static void circle_arc_vertices( GLfloat x, GLfloat y, GLfloat r1, GLfloat r2, GLfloat theta1, GLfloat theta2 ) { const GLfloat delta_theta = 1.0f ; if(theta2 > theta1) { for(GLfloat theta = theta1; theta <= theta2; theta += delta_theta) { GLfloat theta_rad = theta * 3.14159f / 200.0f ; glVertex2f(x + r1 * cos(theta_rad), y + r2 * sin(theta_rad)) ; } } else { for(GLfloat theta = theta1; theta >= theta2; theta -= delta_theta) { GLfloat theta_rad = theta * 3.14159f / 200.0f ; glVertex2f(x + r1 * cos(theta_rad), y + r2 * sin(theta_rad)) ; } } } static void circle_arc_vertices( GLfloat x, GLfloat y, GLfloat r, GLfloat theta1, GLfloat theta2 ) { circle_arc_vertices(x,y,r,r,theta1,theta2) ; } static void circle(GLfloat x, GLfloat y, GLfloat r) { glBegin(GL_LINE_LOOP) ; circle_arc_vertices(x,y,r,0.0f,400.0f) ; glEnd() ; } static void fill_circle(GLfloat x, GLfloat y, GLfloat r) { glBegin(GL_POLYGON) ; circle_arc_vertices(x,y,r,0.0f,400.0f) ; glEnd() ; } static void round_rectangle_vertices( GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLfloat r ) { glVertex2f(x1+r,y2) ; glVertex2f(x2-r,y2) ; circle_arc_vertices(x2-r, y2-r, r, 100.0f, 0.0f) ; glVertex2f(x2,y2-r) ; glVertex2f(x2,y1+r) ; circle_arc_vertices(x2-r, y1+r, r, 0.0f, -100.0f) ; glVertex2f(x2-r,y1) ; glVertex2f(x1+r,y1) ; circle_arc_vertices(x1+r, y1+r, r, -100.0f, -200.0f) ; glVertex2f(x1,y1+r) ; glVertex2f(x1,y2-r) ; circle_arc_vertices(x1+r, y2-r, r, -200.0f, -300.0f) ; } static void round_rectangle(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLfloat r) { glBegin(GL_LINE_LOOP) ; round_rectangle_vertices(x1, y1, x2, y2, r) ; glEnd() ; } static void fill_round_rectangle(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLfloat r) { glBegin(GL_POLYGON) ; round_rectangle_vertices(x1, y1, x2, y2, r) ; glEnd() ; } static void arrow_vertices(Direction dir, GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2) { GLfloat x12 = 0.5 * (x1 + x2) ; GLfloat y12 = 0.5 * (y1 + y2) ; switch(dir) { case DOWN: glVertex2f(x1,y2) ; glVertex2f(x2,y2) ; glVertex2f(x12,y1) ; break ; case UP: glVertex2f(x1,y1) ; glVertex2f(x2,y1) ; glVertex2f(x12,y2) ; break ; case LEFT: glVertex2f(x2,y2) ; glVertex2f(x2,y1) ; glVertex2f(x1,y12) ; break ; case RIGHT: glVertex2f(x1,y2) ; glVertex2f(x1,y1) ; glVertex2f(x2,y12) ; break ; } } static void arrow(Direction dir, GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2) { glBegin(GL_LINE_LOOP) ; arrow_vertices(dir, x1, y1, x2, y2) ; glEnd() ; } static void fill_arrow(Direction dir, GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2) { glBegin(GL_POLYGON) ; arrow_vertices(dir, x1, y1, x2, y2) ; glEnd() ; } // ------------------- Widget class -------------------------------------- Widget::Widget( GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2 ) : style_(BlueStyle), visible_(true), highlight_(false) { set_geometry(x1, y1, x2, y2) ; r_ = 100.0f ; } Widget::~Widget() { } void Widget::glColor(ColorRole role_in) { ColorRole role = role_in ; if(highlight_) { switch(role_in) { case Background: role = Foreground ; break ; case Middleground: role = Middleground ; break ; case Foreground: role = Foreground ; break ; } } switch(style_) { case RedStyle: { switch(role) { case Background: glColor4f(0.5f, 0.0f, 0.0f, 0.5f) ; break ; case Middleground: glColor4f(1.0f, 0.5f, 0.5f, 1.0f) ; break ; case Foreground: glColor4f(5.0f, 5.0f, 5.0f, 1.0f) ; break ; } } break ; case GreenStyle: { switch(role) { case Background: glColor4f(0.0f, 0.5f, 0.0f, 0.5f) ; break ; case Middleground: glColor4f(0.5f, 1.0f, 0.5f, 1.0f) ; break ; case Foreground: glColor4f(5.0f, 5.0f, 5.0f, 1.0f) ; break ; } } break ; case BlueStyle: { switch(role) { case Background: glColor4f(0.0f, 0.0f, 0.5f, 0.5f) ; break ; case Middleground: glColor4f(0.5f, 0.5f, 1.0f, 1.0f) ; break ; case Foreground: glColor4f(5.0f, 5.0f, 5.0f, 1.0f) ; break ; } } break ; case BWStyle: { switch(role) { case Background: glColor4f(5.0f, 5.0f, 5.0f, 0.5f) ; break ; case Middleground: glColor4f(0.2f, 0.2f, 0.2f, 1.0f) ; break ; case Foreground: glColor4f(0.0f, 0.0f, 0.0f, 1.0f) ; break ; } } break ; } } GLboolean Widget::process_mouse_event(float x, float y, int button, GlutViewerEvent event) { return contains(int(x),int(y)) ; } void Widget::draw() { if(!visible()) { return ; } draw_background() ; draw_border() ; } void Widget::draw_background() { glEnable(GL_BLEND) ; glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ; glColor(Background) ; fill_round_rectangle(x1_, y1_, x2_, y2_, r_) ; glDisable(GL_BLEND) ; } void Widget::draw_border() { glColor(Foreground) ; glLineWidth(2.0) ; round_rectangle(x1_, y1_, x2_, y2_, r_) ; } //______________________________________________________________________________________________________ Container* Container::main_widget_ = NULL ; Container::~Container() { if(main_widget_ == this) { main_widget_ = NULL ; } for(size_t i=0; i<children_.size(); i++) { delete children_[i] ; } } void Container::draw() { if(!visible()) { return ; } for(size_t i=0; i<children_.size(); i++) { children_[i]->draw() ; } } GLboolean Container::process_mouse_event(float x, float y, int button, GlutViewerEvent event) { if(!visible()) { return GL_FALSE ; } switch(event) { case GLUT_VIEWER_DOWN: { for(size_t i=0; i<children_.size(); i++) { if(children_[i]->contains(x,y) && children_[i]->process_mouse_event(x, y, button, event)) { active_child_ = children_[i] ; return GL_TRUE ; } } } break ; case GLUT_VIEWER_MOVE: { if(active_child_ != NULL) { return active_child_->process_mouse_event(x, y, button, event) ; } } break ; case GLUT_VIEWER_UP: { if(active_child_ != NULL) { Widget* w = active_child_ ; active_child_ = NULL ; return w->process_mouse_event(x, y, button, event) ; } } break ; } return GL_FALSE ; } void Container::draw_handler() { if(main_widget_ != NULL) { main_widget_->draw() ; } } GLboolean Container::mouse_handler(float x, float y, int button, enum GlutViewerEvent event) { if(main_widget_ != NULL) { return main_widget_->process_mouse_event(x, y, button, event) ; } return GL_FALSE ; } void Container::set_as_main_widget() { main_widget_ = this ; glut_viewer_set_overlay_func(draw_handler) ; glut_viewer_set_mouse_func(mouse_handler) ; } //______________________________________________________________________________________________________ void Panel::draw() { Widget::draw() ; Container::draw() ; } GLboolean Panel::process_mouse_event(float x, float y, int button, GlutViewerEvent event) { if(!visible() || !contains(x,y)) { return GL_FALSE ; } return Container::process_mouse_event(x,y,button,event) ; } //______________________________________________________________________________________________________ void Button::draw() { Widget::draw() ; } GLboolean Button::process_mouse_event(float x, float y, int button, GlutViewerEvent event) { if(visible() && contains(x,y) && event == GLUT_VIEWER_DOWN) { pressed() ; highlight_ = GL_TRUE ; return GL_TRUE ; } if(visible() && contains(x,y) && event == GLUT_VIEWER_UP) { highlight_ = GL_FALSE ; return GL_TRUE ; } return GL_FALSE ; } void Button::pressed() { if(callback_ != NULL) { callback_(client_data_) ; } } //______________________________________________________________________________________________________ void Checkbox::draw() { if(!visible()) { return ; } Button::draw() ; glColor(Foreground) ; GLfloat x = 0.5f * (x1_ + x2_) ; GLfloat y = 0.5f * (y1_ + y2_) ; if(toggle_) { glColor(Middleground) ; fill_circle(x,y,d_) ; glColor(Foreground) ; glLineWidth(1.0f) ; circle(x,y,d_) ; } } void Checkbox::pressed() { toggle_ = !toggle_ ; } //______________________________________________________________________________________________________ ArrowButton::ArrowButton( Direction dir, GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2 ) : Button(x1, y1, x2, y2), direction_(dir) { d_ /= 1.5 ; r_ /= 2.0 ; } void ArrowButton::draw() { Button::draw() ; glColor(Middleground) ; fill_arrow(direction_, x1_ + d_, y1_ + d_, x2_ - d_, y2_ - d_) ; glColor(Foreground); arrow(direction_, x1_ + d_, y1_ + d_, x2_ - d_, y2_ - d_) ; } //______________________________________________________________________________________________________ void Slider::set_value(GLfloat x, bool update) { if(integer_) { x = GLfloat(GLint(x)) ; } if(x < min_) { x = min_ ; } if(x > max_) { x = max_ ; } value_ = x ; if(update && callback_ != NULL) { callback_(value_) ; } } void Slider::set_range(GLfloat x1, GLfloat x2) { min_ = x1 ; max_ = x2 ; if(value_ < min_) { set_value(min_) ; } if(value_ > max_) { set_value(max_) ; } } void Slider::draw() { if(!visible()) { return ; } Widget::draw() ; glColor(Middleground) ; glLineWidth(2.0f) ; glBegin(GL_LINES) ; glVertex2f(x1_+d_, 0.5f*(y1_+y2_)) ; glVertex2f(x2_-d_, 0.5f*(y1_+y2_)) ; glEnd() ; GLfloat w = (value_ - min_) / (max_ - min_) ; GLfloat x = w*(x2_ - d_) + (1.0f - w)*(x1_ + d_) ; GLfloat y = 0.5f*(y1_+y2_) ; glColor(Middleground) ; fill_circle(x,y,d_) ; glColor(Foreground) ; glLineWidth(1.0f) ; circle(x,y,d_) ; } GLboolean Slider::process_mouse_event(float x, float y, int button, GlutViewerEvent event) { if(!visible()) { return GL_FALSE ; } if(event == GLUT_VIEWER_DOWN || event == GLUT_VIEWER_MOVE) { GLfloat w = GLfloat(x - x1_ - d_) / GLfloat(x2_ - x1_ - 2.0f * d_) ; set_value((1.0f - w) * min_ + w * max_, continuous_update_ == GL_TRUE) ; return GL_TRUE ; } else if(event == GLUT_VIEWER_UP) { set_value(value_) ; } return GL_FALSE ; } //______________________________________________________________________________________________________ void CurveEditor::draw() { if(!visible()) { return ; } draw_background() ; // Draw grid glColor(Middleground) ; glLineWidth(1.0) ; glBegin(GL_LINES) ; for(unsigned int i=1; i<10; i++) { float x = x1_ + (x2_ - x1_) * float(i) / 10.0f ; glVertex2f(x, y1_) ; glVertex2f(x, y2_) ; } for(unsigned int i=1; i<4; i++) { float y = y1_ + (y2_ - y1_) * float(i) / 4.0f ; glVertex2f(x1_, y) ; glVertex2f(x2_, y) ; } glEnd() ; // Draw curve glColor(Foreground) ; glLineWidth(2.0) ; glBegin(GL_LINE_STRIP) ; for(unsigned int i=0; i<CurveSize; i++) { glVertex2f( x1_ + (float)i * (x2_ - x1_) / (float)(CurveSize - 1), y1_ + curve_[i] * (y2_ - y1_) ) ; } glEnd() ; draw_border() ; } GLboolean CurveEditor::process_mouse_event(float x, float y, int button, GlutViewerEvent event) { if(!visible()) { return GL_FALSE ; } if(event == GLUT_VIEWER_DOWN && !contains(x,y)) { return GL_FALSE ; } int i = int((x - x1_) * (CurveSize - 1) / (x2_ - x1_)) ; GLfloat v = GLfloat(y - y1_) / GLfloat(y2_ - y1_) ; if(v < 0.0) { v = 0.0 ; } if(v > 1.0) { v = 1.0 ; } if(i < 0) { i = 0 ; } if(i >= CurveSize) { i = CurveSize - 1 ; } if(event == GLUT_VIEWER_DOWN) { last_i_ = i ; last_v_ = v ; return GL_TRUE ; } if(event == GLUT_VIEWER_UP) { if(callback_ != NULL) { callback_(curve_, CurveSize) ; } return GL_TRUE ; } if(event == GLUT_VIEWER_MOVE) { if(i > last_i_) { set_curve(last_i_, last_v_, i, v) ; } else { set_curve(i, v, last_i_, last_v_) ; } } last_i_ = i ; last_v_ = v ; return GL_TRUE ; } void CurveEditor::set_curve(int i1, float val1, int i2, float val2) { if(i1 == i2) { curve_[i1] = val1 ; } else { for(int i=i1; i<=i2; i++) { curve_[i] = val1 + (float)(i - i1) * (val2 - val1) / (float)(i2 - i1) ; } } } void CurveEditor::set_curve(GLfloat* curve, bool update) { for(unsigned int i=0; i<CurveSize; i++) { curve_[i] = curve[i] ; } if(update && callback_ != NULL) { callback_(curve_, CurveSize) ; } } void CurveEditor::reset(bool update) { for(unsigned int i=0; i<CurveSize; i++) { curve_[i] = 0.5f ; } if(update && callback_ != NULL) { callback_(curve_, CurveSize) ; } } void CurveEditor::reset_ramp(bool update) { for(unsigned int i=0; i<CurveSize; i++) { curve_[i] = float(i) / float(CurveSize - 1) ; } if(update && callback_ != NULL) { callback_(curve_, CurveSize) ; } } GLfloat CurveEditor::value(GLfloat x) const { if(x < 0.0f) { x = 0.0f ; } if(x > 1.0f) { x = 1.0f ; } return curve_[int(x * (CurveSize - 1))] ; } //______________________________________________________________________________________________________ void ColormapEditor::draw() { if(!visible()) { return ; } draw_background() ; // Draw curve glColor(Foreground) ; glLineWidth(2.0) ; glBegin(GL_LINE_STRIP) ; for(unsigned int i=0; i<ColormapSize; i++) { glVertex2f( x1_ + (float)i * (x2_ - x1_) / (float)(ColormapSize - 1), y1_ + curve()[i] * (y2_ - y1_) ) ; } glEnd() ; draw_border() ; } void ColormapEditor::draw_background() { glEnable(GL_BLEND) ; glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ; drawBackgroundCB_(curve(), ColormapSize) ; glDisable(GL_BLEND) ; } void ColormapEditor::draw_border() { glColor(Foreground) ; glLineWidth(2.0) ; glBegin(GL_LINE_LOOP) ; glVertex2f(x1_, y1_) ; glVertex2f(x1_, y2_) ; glVertex2f(x2_, y2_) ; glVertex2f(x2_, y1_) ; glEnd() ; } void ColormapEditor::update(unsigned char* cmap_data, int size, int component) { for(unsigned int i = 0; i < ColormapSize; ++i) { int idx = (double(i) / double(ColormapSize)) * (size-1) ; curve()[i] = double(cmap_data[4*idx + component]) / 255.0 ; } } //______________________________________________________________________________________________________ void TextLabel::draw() { if(!visible()) { return ; } glLineWidth(textwidth_) ; printf_xy(x1_+10, y1_+50, (char*)text_.c_str()) ; } //______________________________________________________________________________________________________ Spinbox::Spinbox( GLfloat x, GLfloat y, GLenum& value, const std::vector<std::string>& labels ) : Container(x, y, x+3000, y+170), value_(value), labels_(labels) { down_ = new ArrowButton(DOWN, x, y, x+170, y+170) ; up_ = new ArrowButton(UP, x+200, y, x+370, y+170) ; up_->set_callback(increment_CB, this) ; down_->set_callback(decrement_CB, this) ; if(value_ < 0) { value_ = 0 ; } if(value_ >= int(labels_.size())) { value_ = (GLenum)(labels_.size() - 1) ; } text_ = new TextLabel(x+450,y,labels_[value_]) ; add_child(up_) ; add_child(down_) ; add_child(text_) ; show() ; } void Spinbox::draw() { Container::draw() ; } void Spinbox::increment() { value_++ ; if(value_ >= labels_.size()) { value_ = 0 ; } text_->set_text(labels_[value_]) ; } void Spinbox::decrement() { if(int(value_) - 1 < 0) { value_ = (GLenum)(labels_.size() - 1) ; } else { value_-- ; } text_->set_text(labels_[value_]) ; } void Spinbox::increment_CB(void* spinbox) { static_cast<Spinbox*>(spinbox)->increment() ; } void Spinbox::decrement_CB(void* spinbox) { static_cast<Spinbox*>(spinbox)->decrement() ; } //______________________________________________________________________________________________________ void MessageBox::draw() { if(!visible()) { return ; } Panel::draw() ; glLineWidth(2) ; for(unsigned int i=0; i<message_.size(); i++) { printf_xy(x1_+100, y2_-200-i*150, (char*)message_[i].c_str()) ; } } //______________________________________________________________________________________________________ PropertyPage::PropertyPage( GLfloat x_in, GLfloat y_in, const std::string& caption ) : Panel(x_in,y_in-10,x_in+Width,y_in) { y_ = y2_ - 200 ; x_caption_ = x1_ + 100 ; x_widget_ = x1_ + 1300 ; caption_ = add_separator(caption) ; y1_ = y_ ; } TextLabel* PropertyPage::add_separator(const std::string& text) { TextLabel* w = new TextLabel(x1_ + 400, y_, text, 2.0f) ; add_child(w) ; y_ -= 250 ; y1_ = y_ ; return w ; } TextLabel* PropertyPage::add_string(const std::string& text) { TextLabel* w = new TextLabel(x1_ + 200, y_, text, 1.0f) ; add_child(w) ; y_ -= 150 ; y1_ = y_ ; return w ; } Slider* PropertyPage::add_slider( const std::string& caption, GLfloat& value, GLfloat vmin, GLfloat vmax ) { add_child(new TextLabel(x_caption_, y_, caption)) ; Slider* w = new Slider(x_widget_, y_, x_widget_+800, y_+200, value) ; w->set_range(vmin, vmax) ; add_child(w) ; y_ -= 250 ; y1_ = y_ ; return w ; } Checkbox* PropertyPage::add_toggle( const std::string& caption, GLboolean& value ) { add_child(new TextLabel(x_caption_, y_, caption)) ; Checkbox* w = new Checkbox(x_widget_, y_, x_widget_+200, y_+200, value) ; add_child(w) ; y_ -= 250 ; y1_ = y_ ; return w ; } Spinbox* PropertyPage::add_enum( const std::string& caption, GLenum& value, const std::vector<std::string>& labels) { add_child(new TextLabel(x_caption_, y_, caption)) ; Spinbox* w = new Spinbox(x_widget_, y_, value, labels) ; add_child(w) ; y_ -= 250 ; y1_ = y_ ; return w ; } //______________________________________________________________________________________________________ ViewerProperties::ViewerProperties(GLfloat x_left, GLfloat y_top) : PropertyPage( x_left, y_top, "Viewer" ) { add_toggle("Rot. light", *glut_viewer_is_enabled_ptr(GLUT_VIEWER_ROTATE_LIGHT)) ; if(glut_viewer_is_enabled(GLUT_VIEWER_HDR)) { add_slider("Exposure", *glut_viewer_float_ptr(GLUT_VIEWER_HDR_EXPOSURE), 0.001, 3.0) ; add_slider("Gamma", *glut_viewer_float_ptr(GLUT_VIEWER_HDR_GAMMA), 0.2, 1.5) ; add_toggle("Vignette", *glut_viewer_is_enabled_ptr(GLUT_VIEWER_HDR_VIGNETTE)) ; add_slider("Blur amount", *glut_viewer_float_ptr(GLUT_VIEWER_HDR_BLUR_AMOUNT)) ; add_slider("Blur width", *glut_viewer_float_ptr(GLUT_VIEWER_HDR_BLUR_WIDTH), 1.0, 20.0) ; add_toggle("UnMsk.", *glut_viewer_is_enabled_ptr(GLUT_VIEWER_HDR_UNSHARP_MASKING)) ; add_toggle("UnMsk.+", *glut_viewer_is_enabled_ptr(GLUT_VIEWER_HDR_POSITIVE_UNSHARP_MASKING)) ; add_slider("UnMsk. Gamm", *glut_viewer_float_ptr(GLUT_VIEWER_HDR_UNSHARP_MASKING_GAMMA), 0.2, 1.5) ; } } void ViewerProperties::draw() { if(glut_viewer_is_enabled(GLUT_VIEWER_IDLE_REDRAW)) { static char buff[256] ; sprintf(buff, " [%4d FPS]", glut_viewer_fps()) ; caption_->set_text("Viewer" + std::string(buff)) ; } else { caption_->set_text("Viewer") ; } PropertyPage::draw() ; } void ViewerProperties::apply() { } //______________________________________________________________________________________________________ Image::Image( GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLint texture, GLint target ) : Widget(x1, y1, x2, y2), texture_(texture), texture_target_(target) { } void Image::draw() { if(texture_ == 0) { return ; } glEnable(texture_target_) ; glBindTexture(texture_target_, texture_) ; glBegin(GL_QUADS) ; glTexCoord2f(0.0, 0.0) ; glVertex2f(x1_, y1_) ; glTexCoord2f(1.0, 0.0) ; glVertex2f(x2_, y1_) ; glTexCoord2f(1.0, 1.0) ; glVertex2f(x2_, y2_) ; glTexCoord2f(0.0, 1.0) ; glVertex2f(x1_, y2_) ; glEnd() ; glDisable(texture_target_) ; } //______________________________________________________________________________________________________ }
stormHan/gpu_rvd
Gpu_Rvd/header/thid_party/glut_viewer/glut_viewer_gui.cpp
C++
mit
25,552
29.748496
112
0.43703
false
<?php /** * Description of aSites * * @author almaz */ class aSitesUsers extends Action { protected $defaultAct = 'List'; protected function configure() { require_once $this->module->pathModels . 'as_Sites.php'; require_once $this->module->pathModels . 'as_SitesUsers.php'; $authModule = General::$loadedModules['Auth']; require_once $authModule->pathModels . 'au_Users.php'; } /**setTpl * выводит список всех сайтов */ public function act_List() { if ($this->request->isAjax()) { $this->context->setTopTpl('html_list'); } else { $this->_parent(); $this->context->setTpl('content', 'html_list'); } $sql = Stmt::prepare2(as_Stmt::GET_SITES_USERS_USER, array('user_id' => $this->userInfo['user']['id'])); $tbl = new oTable(DBExt::selectToTable($sql)); $tbl->setIsDel(); $tbl->setIsEdit(); $tbl->setNamesColumns(array('host'=>'Сайт')); $tbl->addRulesView('password', '******'); $tbl->sort(Navigation::get('field'), Navigation::get('order')); $this->context->set('tbl', $tbl); $this->context->set('h1', 'Мои сайты'); } /** * выводит список всех сайтов */ public function act_Add() { if ($this->request->isAjax()) { $this->context->setTopTpl('site_add_html'); } else { $this->_parent(); $this->context->setTpl('content', 'site_add_html'); } $sqlSites = Stmt::prepare2(as_Stmt::ALL_SITES, array(), array (Stmt::ORDER => 'sort')); $listSites = new oList(DBExt::selectToList($sqlSites)); $fields['site_id'] = array('title' => 'Сайт', 'value' => '', 'data' => $listSites, 'type'=>'select', 'required' => true, 'validator' => null, 'info'=>'Список поддерживаемых на данный момент сайтов', 'error' => false, 'attr' => '', $checked = array()); $fields['login'] = array('title' => 'Логин', 'value'=>'', 'type'=>'text', 'required' => true, 'validator' => null, 'info'=>'', 'error' => false, 'attr' => '', $checked = array()); $fields['password'] = array('title' => 'Пароль', 'value'=>'', 'type'=>'text', 'required' => true, 'validator' => null, 'info'=>'', 'error' => false, 'attr' => '', $checked = array()); $form = new oForm($fields); $this->context->set('form', $form); $this->context->set('info_text', 'Добавление настроек для нового сайта...'); if ($this->request->is('POST')) { $form->fill($this->request->get('POST')); if ($form->isComplited()) { $siteUser = new as_SitesUsers(); $siteUser->site_id = $form->getFieldValue('site_id'); $siteUser->login = $form->getFieldValue('login'); $siteUser->password = $form->getFieldValue('password'); $siteUser->user_id = $this->userInfo['user']['id']; $siteUser->save(); $this->context->del('form'); $this->context->set('info_text', 'Настройки добавлены'); } } } function act_Del () { $id = (int)$this->request->get('id', 0); $sqlSites = Stmt::prepare2(as_Stmt::DEL_SITE_USER, array('user_id' => $this->userInfo['user']['id'], 'site_id' => $id)); DB::execute($prepare_stmt); $sql = Stmt::prepare(se_Stmt::IS_KEYWORDS_SET, array('set_id' => $id, Stmt::LIMIT => 1)); $sitesUsers = new as_SitesUsers((int)$this->request->get('id')); $sets->delete(); $iRoute = new InternalRoute(); $iRoute->module = 'SEParsing'; $iRoute->action = 'Sets'; $actR = new ActionResolver(); $act = $actR->getInternalAction($iRoute); $act->runAct(); } /** * Функция-обвертка, модули уровнем выще. для отображения * @param InternalRoute $iRoute */ function _parent(InternalRoute $iRoute = null) { $this->context->set('title', 'Сайты'); if (!$iRoute) { $iRoute = new InternalRoute(); $iRoute->module = 'Pages'; $iRoute->action = 'Pages'; } $actR = new ActionResolver(); $act = $actR->getInternalAction($iRoute); $act->runParentAct(); } }
AlmazKo/Brill
Brill/Modules/AutoSubmitter/Actions/aSitesUsers.php
PHP
mit
4,519
38.145455
259
0.528455
false
package cz.muni.fi.pa165.mushrooms.service.exceptions; /** * @author bkompis */ public class EntityOperationServiceException extends MushroomHunterServiceDataAccessException { public <T> EntityOperationServiceException(String what, String operation, T entity, Throwable e) { super("Could not " + operation + " " + what + " (" + entity + ").", e); } public EntityOperationServiceException(String msg) { super(msg); } public EntityOperationServiceException(String msg, Throwable cause) { super(msg, cause); } }
PA165-MushroomHunter/MushroomHunter
service/src/main/java/cz/muni/fi/pa165/mushrooms/service/exceptions/EntityOperationServiceException.java
Java
mit
563
28.631579
102
0.689165
false
#!/usr/bin/env python import subprocess import praw from hashlib import sha1 from flask import Flask from flask import Response from flask import request from cStringIO import StringIO from base64 import b64encode from base64 import b64decode from ConfigParser import ConfigParser import OAuth2Util import os import markdown import bleach # encoding=utf8 import sys from participantCollection import ParticipantCollection reload(sys) sys.setdefaultencoding('utf8') # Edit Me! # Each day after you post a signup post, copy its 6-character ID to this array. signupPageSubmissionIds = [ '7zrrj1', '7zxkpq', '8055hn', '80ddrf', '80nbm1', '80waq3' ] flaskport = 8993 app = Flask(__name__) app.debug = True commentHashesAndComments = {} def loginAndReturnRedditSession(): config = ConfigParser() config.read("../reddit-password-credentials.cfg") user = config.get("Reddit", "user") password = config.get("Reddit", "password") # TODO: password auth is going away, and we will soon need to do oauth. redditSession = praw.Reddit(user_agent='Test Script by /u/foobarbazblarg') redditSession.login(user, password, disable_warning=True) # submissions = redditSession.get_subreddit('pornfree').get_hot(limit=5) # print [str(x) for x in submissions] return redditSession def loginOAuthAndReturnRedditSession(): redditSession = praw.Reddit(user_agent='Test Script by /u/foobarbazblarg') # New version of praw does not require explicit use of the OAuth2Util object. Presumably because reddit now REQUIRES oauth. # o = OAuth2Util.OAuth2Util(redditSession, print_log=True, configfile="../reddit-oauth-credentials.cfg") # TODO: Testing comment of refresh. We authenticate fresh every time, so presumably no need to do o.refresh(). # o.refresh(force=True) return redditSession def getSubmissionsForRedditSession(redditSession): # submissions = [redditSession.get_submission(submission_id=submissionId) for submissionId in signupPageSubmissionIds] submissions = [redditSession.submission(id=submissionId) for submissionId in signupPageSubmissionIds] for submission in submissions: submission.comments.replace_more(limit=None) # submission.replace_more_comments(limit=None, threshold=0) return submissions def getCommentsForSubmissions(submissions): comments = [] for submission in submissions: commentForest = submission.comments comments += [comment for comment in commentForest.list() if comment.__class__ == praw.models.Comment] return comments def retireCommentHash(commentHash): with open("retiredcommenthashes.txt", "a") as commentHashFile: commentHashFile.write(commentHash + '\n') def retiredCommentHashes(): with open("retiredcommenthashes.txt", "r") as commentHashFile: # return commentHashFile.readlines() return commentHashFile.read().splitlines() @app.route('/moderatesignups.html') def moderatesignups(): global commentHashesAndComments commentHashesAndComments = {} stringio = StringIO() stringio.write('<html>\n<head>\n</head>\n\n') # redditSession = loginAndReturnRedditSession() redditSession = loginOAuthAndReturnRedditSession() submissions = getSubmissionsForRedditSession(redditSession) flat_comments = getCommentsForSubmissions(submissions) retiredHashes = retiredCommentHashes() i = 1 stringio.write('<iframe name="invisibleiframe" style="display:none;"></iframe>\n') stringio.write("<h3>") stringio.write(os.getcwd()) stringio.write("<br>\n") for submission in submissions: stringio.write(submission.title) stringio.write("<br>\n") stringio.write("</h3>\n\n") stringio.write('<form action="copydisplayduringsignuptoclipboard.html" method="post" target="invisibleiframe">') stringio.write('<input type="submit" value="Copy display-during-signup.py stdout to clipboard">') stringio.write('</form>') for comment in flat_comments: # print comment.is_root # print comment.score i += 1 commentHash = sha1() commentHash.update(comment.fullname) commentHash.update(comment.body.encode('utf-8')) commentHash = commentHash.hexdigest() if commentHash not in retiredHashes: commentHashesAndComments[commentHash] = comment authorName = str(comment.author) # can be None if author was deleted. So check for that and skip if it's None. stringio.write("<hr>\n") stringio.write('<font color="blue"><b>') stringio.write(authorName) # can be None if author was deleted. So check for that and skip if it's None. stringio.write('</b></font><br>') if ParticipantCollection().hasParticipantNamed(authorName): stringio.write(' <small><font color="green">(member)</font></small>') # if ParticipantCollection().participantNamed(authorName).isStillIn: # stringio.write(' <small><font color="green">(in)</font></small>') # else: # stringio.write(' <small><font color="red">(out)</font></small>') else: stringio.write(' <small><font color="red">(not a member)</font></small>') stringio.write('<form action="takeaction.html" method="post" target="invisibleiframe">') stringio.write('<input type="submit" name="actiontotake" value="Signup" style="color:white;background-color:green">') # stringio.write('<input type="submit" name="actiontotake" value="Signup and checkin">') # stringio.write('<input type="submit" name="actiontotake" value="Relapse">') # stringio.write('<input type="submit" name="actiontotake" value="Reinstate">') stringio.write('<input type="submit" name="actiontotake" value="Skip comment">') stringio.write('<input type="submit" name="actiontotake" value="Skip comment and don\'t upvote">') stringio.write('<input type="hidden" name="username" value="' + b64encode(authorName) + '">') stringio.write('<input type="hidden" name="commenthash" value="' + commentHash + '">') # stringio.write('<input type="hidden" name="commentpermalink" value="' + comment.permalink + '">') stringio.write('</form>') stringio.write(bleach.clean(markdown.markdown(comment.body.encode('utf-8')), tags=['p'])) stringio.write("\n<br><br>\n\n") stringio.write('</html>') pageString = stringio.getvalue() stringio.close() return Response(pageString, mimetype='text/html') @app.route('/takeaction.html', methods=["POST"]) def takeaction(): username = b64decode(request.form["username"]) commentHash = str(request.form["commenthash"]) # commentPermalink = request.form["commentpermalink"] actionToTake = request.form["actiontotake"] # print commentHashesAndComments comment = commentHashesAndComments[commentHash] # print "comment: " + str(comment) if actionToTake == 'Signup': print "signup - " + username subprocess.call(['./signup.py', username]) comment.upvote() retireCommentHash(commentHash) # if actionToTake == 'Signup and checkin': # print "signup and checkin - " + username # subprocess.call(['./signup-and-checkin.sh', username]) # comment.upvote() # retireCommentHash(commentHash) # elif actionToTake == 'Relapse': # print "relapse - " + username # subprocess.call(['./relapse.py', username]) # comment.upvote() # retireCommentHash(commentHash) # elif actionToTake == 'Reinstate': # print "reinstate - " + username # subprocess.call(['./reinstate.py', username]) # comment.upvote() # retireCommentHash(commentHash) elif actionToTake == 'Skip comment': print "Skip comment - " + username comment.upvote() retireCommentHash(commentHash) elif actionToTake == "Skip comment and don't upvote": print "Skip comment and don't upvote - " + username retireCommentHash(commentHash) return Response("hello", mimetype='text/html') @app.route('/copydisplayduringsignuptoclipboard.html', methods=["POST"]) def copydisplayduringsignuptoclipboard(): print "TODO: Copy display to clipboard" subprocess.call(['./display-during-signup.py']) return Response("hello", mimetype='text/html') if __name__ == '__main__': app.run(host='127.0.0.1', port=flaskport)
foobarbazblarg/stayclean
stayclean-2018-march/serve-signups-with-flask.py
Python
mit
8,581
41.691542
129
0.67731
false
#![cfg_attr(all(feature = "nightly", test), feature(test))] #![cfg(all(feature = "nightly", test))] extern crate test; extern crate cxema; #[cfg(test)] use cxema::sha2::{Sha256}; use cxema::digest::Digest; use test::Bencher; #[bench] pub fn sha256_10(bh: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8; 10]; bh.iter(|| { sh.input(&bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn sha256_1k(bh: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8; 1024]; bh.iter(|| { sh.input(&bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn sha256_64k(bh: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8; 65536]; bh.iter(|| { sh.input(&bytes); }); bh.bytes = bytes.len() as u64; }
alexyer/cxema
benches/sha256_bench.rs
Rust
mit
818
17.613636
59
0.55379
false
using System.Collections.Generic; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; using JsonApiDotNetCore.Serialization.Objects; namespace JsonApiDotNetCore.Serialization.Building { /// <summary> /// Responsible for converting resources into <see cref="ResourceObject" />s given a collection of attributes and relationships. /// </summary> public interface IResourceObjectBuilder { /// <summary> /// Converts <paramref name="resource" /> into a <see cref="ResourceObject" />. Adds the attributes and relationships that are enlisted in /// <paramref name="attributes" /> and <paramref name="relationships" />. /// </summary> /// <param name="resource"> /// Resource to build a <see cref="ResourceObject" /> for. /// </param> /// <param name="attributes"> /// Attributes to include in the building process. /// </param> /// <param name="relationships"> /// Relationships to include in the building process. /// </param> /// <returns> /// The resource object that was built. /// </returns> ResourceObject Build(IIdentifiable resource, IReadOnlyCollection<AttrAttribute> attributes, IReadOnlyCollection<RelationshipAttribute> relationships); } }
Research-Institute/json-api-dotnet-core
src/JsonApiDotNetCore/Serialization/Building/IResourceObjectBuilder.cs
C#
mit
1,337
42.129032
158
0.66193
false
# Wir backen uns ein Mandelbrötchen ![Screenshot](images/mandelbrotmenge.jpg) Die [Mandelbrot-Menge](https://de.wikipedia.org/wiki/Mandelbrot-Menge) ist die zentrale Ikone der Chaos-Theorie und das Urbild aller Fraktale. Sie ist die Menge aller komplexen Zahlen *c*, für welche die durch $$ \begin{align} z_{0} & = 0\\\\ z_{n+1} & = z_{n}^{2}+c\\\\ \end{align} $$ rekursiv definierte Folge beschränkt ist. Bilder der Mandelbrot-Menge können erzeugt werden, indem für jeden Wert des Parameters *c*, der gemäß obiger Rekursion endlich bleibt, ein Farbwert in der komplexen Ebene zugeordnet wird. Die komplexe Ebene wird in der Regel so dargestellt, daß in der Horizontalen (in der kartesisschen Ebene die *x-Achse*) der Realteil der komplexen Zahl und in der Vertikalen (in der kartesischen Ebene die *y-Achse*) der imaginäre Teil aufgetragen wird. Jede komplexe Zahl entspricht also einen Punkt in der komplexen Ebene. Die zur Mandelbrotmenge gehörenden Zahlen werden im Allgemeinen schwarz dargestellt, die übrigen Farbwerte werden der Anzahl von Iterationen (`maxiter`) zugeordnet, nach der der gewählte Punkt der Ebene einen Grenzwert (`maxlimit`) verläßt. Der theoretische Grenzwert ist *2.0*, doch können besonders bei Ausschnitten aus der Menge, um andere Farbkombinationen zu erreichen, auch höhere Grenzwerte verwendet werden. Bei Ausschnitten muß auch die Anzahl der Iterationen massiv erhöht werden, um eine hinreichende Genauigkeit der Darstellung zu erreichen. ## Das Programm Python kennt den Datentyp `complex` und kann mit komplexen Zahlen rechnen. Daher drängt sich die Sprache für Experimente mit komplexen Zahlen geradezu auf. Zuert werden mit `cr` und `ci` Real- und Imaginärteil definiert und dann mit ~~~python c = complex(cr, ci) ~~~ die komplexe Zahl erzeugt. Für die eigentliche Iteration wird dann -- nachdem der Startwert `z = 0.0` festgelegt wurde -- nur eine Zeile benötigt: ~~~python z = (z**2) + c ~~~ Wie schon in anderen Beispielen habe ich für die Farbdarstellung den HSB-Raum verwendet und über den *Hue*-Wert iteriert. Das macht alles schön bunt, aber es gibt natürlich viele Möglichkeiten, ansprechendere Farben zu bekommen, beliebt sind zum Beispiel selbsterstellte Paletten mit 256 ausgesuchten Farbwerten, die entweder harmonisch ineinander übergehen oder bestimmte Kontraste betonen. ## Der komplette Quellcode ~~~python left = -2.25 right = 0.75 bottom = -1.5 top = 1.5 maxlimit = 2.0 maxiter = 20 def setup(): size(400, 400) background("#ffffff") colorMode(HSB, 255, 100, 100) # frame.setTitle(u"Mandelbrötchen") noLoop() def draw(): for x in range(width): cr = left + x*(right - left)/width for y in range(height): ci = bottom + y*(top - bottom)/height c = complex(cr, ci) z = 0.0 i = 0 for i in range(maxiter): if abs(z) > maxlimit: break z = (z**2) + c if i == (maxiter - 1): set(x, y, color(0, 0, 0)) else: set(x, y, color((i*48)%255, 100, 100)) ~~~ Um zu sehen, wie sich die Farben ändern, kann man durchaus mal mit den Werten von `maxlimit` spielen und diesen zum Beispiel auf `3.0` oder `4.0` setzen. Auch die Erhöhung der Anzahl der Iterationen `maxiter` verändert die Farbzuordnung, verlängert aber auch die Rechhenzeit drastisch, so daß man speziell bei Ausschnitten aus der Mandelbrotmenge schon einige Zeit auf das Ergebnis warten muß.
kantel/processingpy
docs/mandelbrot.md
Markdown
mit
3,571
49.514286
877
0.710891
false
<html> <head> <title>User agent detail - Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <div class="container"> <div class="section"> <h1 class="header center orange-text">User agent detail</h1> <div class="row center"> <h5 class="header light"> Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 </h5> </div> </div> <div class="section"> <table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Source result (test suite)</th></tr><tr><td>piwik/device-detector<br /><small>/Tests/fixtures/tablet.yml</small></td><td>Android Browser </td><td>Android 4.0.3</td><td>WebKit </td><td style="border-left: 1px solid #555">Asus</td><td>Eee Pad MeMO 171</td><td>tablet</td><td></td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td></td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-test">Detail</a> <!-- Modal Structure --> <div id="modal-test" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Testsuite result detail</h4> <p><pre><code class="php">Array ( [user_agent] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 [os] => Array ( [name] => Android [short_name] => AND [version] => 4.0.3 [platform] => ) [client] => Array ( [type] => browser [name] => Android Browser [short_name] => AN [version] => [engine] => WebKit ) [device] => Array ( [type] => tablet [brand] => AU [model] => Eee Pad MeMO 171 ) [os_family] => Android [browser_family] => Android Browser ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapPhp<br /><small>6012</small></td><td>Android 4.0</td><td>WebKit </td><td>Android 4.0</td><td style="border-left: 1px solid #555"></td><td></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.02101</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-215ac98d-ccf8-4615-916e-5a819d6a59c9">Detail</a> <!-- Modal Structure --> <div id="modal-215ac98d-ccf8-4615-916e-5a819d6a59c9" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapPhp result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.4\.0.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android?4.0* build/*)*applewebkit/*(*khtml,*like gecko*)*version/4.0*safari* [parent] => Android Browser 4.0 [comment] => Android Browser 4.0 [browser] => Android [browser_type] => Browser [browser_bits] => 32 [browser_maker] => Google Inc [browser_modus] => unknown [version] => 4.0 [majorver] => 4 [minorver] => 0 [platform] => Android [platform_version] => 4.0 [platform_description] => Android OS [platform_bits] => 32 [platform_maker] => Google Inc [alpha] => [beta] => [win16] => [win32] => [win64] => [frames] => 1 [iframes] => 1 [tables] => 1 [cookies] => 1 [backgroundsounds] => [javascript] => 1 [vbscript] => [javaapplets] => 1 [activexcontrols] => [ismobiledevice] => 1 [istablet] => [issyndicationreader] => [crawler] => [cssversion] => 3 [aolversion] => 0 [device_name] => general Mobile Phone [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => touchscreen [device_code_name] => general Mobile Phone [device_brand_name] => unknown [renderingengine_name] => WebKit [renderingengine_version] => unknown [renderingengine_description] => For Google Chrome, iOS (including both mobile Safari, WebViews within third-party apps, and web clips), Safari, Arora, Midori, OmniWeb, Shiira, iCab since version 4, Web, SRWare Iron, Rekonq, and in Maxthon 3. [renderingengine_maker] => Apple Inc ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>DonatjUAParser<br /><small>v0.5.0</small></td><td>Android Browser 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661">Detail</a> <!-- Modal Structure --> <div id="modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>DonatjUAParser result detail</h4> <p><pre><code class="php">Array ( [platform] => Android [browser] => Android Browser [version] => 4.0 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>NeutrinoApiCom<br /><small></small></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.0.3</td><td style="border-left: 1px solid #555">Generic</td><td>Android 4.0</td><td>mobile-browser</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.247</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc">Detail</a> <!-- Modal Structure --> <div id="modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>NeutrinoApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [mobile_screen_height] => 480 [is_mobile] => 1 [type] => mobile-browser [mobile_brand] => Generic [mobile_model] => Android 4.0 [version] => 4.0 [is_android] => 1 [browser_name] => Android Webkit [operating_system_family] => Android [operating_system_version] => 4.0.3 [is_ios] => [producer] => Google Inc. [operating_system] => Android 4.0.x Ice Cream Sandwich [mobile_screen_width] => 320 [mobile_browser] => Android Webkit ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>PiwikDeviceDetector<br /><small>3.5.2</small></td><td>Android Browser </td><td>WebKit </td><td>Android 4.0</td><td style="border-left: 1px solid #555">Asus</td><td>Eee Pad MeMO 171</td><td>tablet</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.004</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-21638055-738d-46ba-a1b1-f5114bc26475">Detail</a> <!-- Modal Structure --> <div id="modal-21638055-738d-46ba-a1b1-f5114bc26475" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>PiwikDeviceDetector result detail</h4> <p><pre><code class="php">Array ( [client] => Array ( [type] => browser [name] => Android Browser [short_name] => AN [version] => [engine] => WebKit ) [operatingSystem] => Array ( [name] => Android [short_name] => AND [version] => 4.0 [platform] => ) [device] => Array ( [brand] => AU [brandName] => Asus [model] => Eee Pad MeMO 171 [device] => 2 [deviceName] => tablet ) [bot] => [extra] => Array ( [isBot] => [isBrowser] => 1 [isFeedReader] => [isMobileApp] => [isPIM] => [isLibrary] => [isMediaPlayer] => [isCamera] => [isCarBrowser] => [isConsole] => [isFeaturePhone] => [isPhablet] => [isPortableMediaPlayer] => [isSmartDisplay] => [isSmartphone] => [isTablet] => 1 [isTV] => [isDesktop] => [isMobile] => 1 [isTouchEnabled] => ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.0</small></td><td>Navigator 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.0.3</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c">Detail</a> <!-- Modal Structure --> <div id="modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>SinergiBrowserDetector result detail</h4> <p><pre><code class="php">Array ( [browser] => Sinergi\BrowserDetector\Browser Object ( [userAgent:Sinergi\BrowserDetector\Browser:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 ) [name:Sinergi\BrowserDetector\Browser:private] => Navigator [version:Sinergi\BrowserDetector\Browser:private] => 4.0 [isRobot:Sinergi\BrowserDetector\Browser:private] => [isChromeFrame:Sinergi\BrowserDetector\Browser:private] => ) [operatingSystem] => Sinergi\BrowserDetector\Os Object ( [name:Sinergi\BrowserDetector\Os:private] => Android [version:Sinergi\BrowserDetector\Os:private] => 4.0.3 [isMobile:Sinergi\BrowserDetector\Os:private] => 1 [userAgent:Sinergi\BrowserDetector\Os:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 ) ) [device] => Sinergi\BrowserDetector\Device Object ( [name:Sinergi\BrowserDetector\Device:private] => unknown [userAgent:Sinergi\BrowserDetector\Device:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 ) ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UAParser<br /><small>v3.4.5</small></td><td>Android 4.0.3</td><td><i class="material-icons">close</i></td><td>Android 4.0.3</td><td style="border-left: 1px solid #555">Asus</td><td>ME171</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b">Detail</a> <!-- Modal Structure --> <div id="modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">UAParser\Result\Client Object ( [ua] => UAParser\Result\UserAgent Object ( [major] => 4 [minor] => 0 [patch] => 3 [family] => Android ) [os] => UAParser\Result\OperatingSystem Object ( [major] => 4 [minor] => 0 [patch] => 3 [patchMinor] => [family] => Android ) [device] => UAParser\Result\Device Object ( [brand] => Asus [model] => ME171 [family] => Asus ME171 ) [originalUserAgent] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentStringCom<br /><small></small></td><td>Android Webkit Browser </td><td><i class="material-icons">close</i></td><td>Android 4.0.3</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.047</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4">Detail</a> <!-- Modal Structure --> <div id="modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentStringCom result detail</h4> <p><pre><code class="php">stdClass Object ( [agent_type] => Browser [agent_name] => Android Webkit Browser [agent_version] => -- [os_type] => Android [os_name] => Android [os_versionName] => [os_versionNumber] => 4.0.3 [os_producer] => [os_producerURL] => [linux_distibution] => Null [agent_language] => Chinese - Taiwan [agent_languageTag] => zh-tw ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhatIsMyBrowserCom<br /><small></small></td><td>Android Browser 4.0</td><td>WebKit 534.30</td><td>Android 4.0.3</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.421</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9795f66f-7271-430e-973a-a5c0e14dc35a">Detail</a> <!-- Modal Structure --> <div id="modal-9795f66f-7271-430e-973a-a5c0e14dc35a" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhatIsMyBrowserCom result detail</h4> <p><pre><code class="php">stdClass Object ( [operating_system_name] => Android [simple_sub_description_string] => [simple_browser_string] => Android Browser 4 on Android (Ice Cream Sandwich) [browser_version] => 4 [extra_info] => Array ( ) [operating_platform] => [extra_info_table] => stdClass Object ( [System Build] => IML74K ) [layout_engine_name] => WebKit [detected_addons] => Array ( ) [operating_system_flavour_code] => [hardware_architecture] => [operating_system_flavour] => [operating_system_frameworks] => Array ( ) [browser_name_code] => android-browser [operating_system_version] => Ice Cream Sandwich [simple_operating_platform_string] => [is_abusive] => [layout_engine_version] => 534.30 [browser_capabilities] => Array ( ) [operating_platform_vendor_name] => [operating_system] => Android (Ice Cream Sandwich) [operating_system_version_full] => 4.0.3 [operating_platform_code] => [browser_name] => Android Browser [operating_system_name_code] => android [user_agent] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30 [browser_version_full] => 4.0 [browser] => Android Browser 4 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhichBrowser<br /><small>2.0.10</small></td><td>Android Browser </td><td>Webkit 534.30</td><td>Android 4.0.3</td><td style="border-left: 1px solid #555">Asus</td><td>Eee Pad MeMO</td><td>tablet</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.008</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4">Detail</a> <!-- Modal Structure --> <div id="modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhichBrowser result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [name] => Android Browser ) [engine] => Array ( [name] => Webkit [version] => 534.30 ) [os] => Array ( [name] => Android [version] => 4.0.3 ) [device] => Array ( [type] => tablet [manufacturer] => Asus [model] => Eee Pad MeMO ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Woothee<br /><small>v1.2.0</small></td><td>Safari 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>smartphone</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-3f285ff5-314b-4db4-9948-54572e92e7b6">Detail</a> <!-- Modal Structure --> <div id="modal-3f285ff5-314b-4db4-9948-54572e92e7b6" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Woothee result detail</h4> <p><pre><code class="php">Array ( [name] => Safari [vendor] => Apple [version] => 4.0 [category] => smartphone [os] => Android [os_version] => 4.0.3 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Wurfl<br /><small>1.6.4</small></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 4.0</td><td style="border-left: 1px solid #555"></td><td></td><td>Tablet</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.13004</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-1a1aee36-7ce7-4111-a391-8e2c501f1532">Detail</a> <!-- Modal Structure --> <div id="modal-1a1aee36-7ce7-4111-a391-8e2c501f1532" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Wurfl result detail</h4> <p><pre><code class="php">Array ( [virtual] => Array ( [is_android] => true [is_ios] => false [is_windows_phone] => false [is_app] => false [is_full_desktop] => false [is_largescreen] => true [is_mobile] => true [is_robot] => false [is_smartphone] => false [is_touchscreen] => true [is_wml_preferred] => false [is_xhtmlmp_preferred] => false [is_html_preferred] => true [advertised_device_os] => Android [advertised_device_os_version] => 4.0 [advertised_browser] => Android Webkit [advertised_browser_version] => 4.0 [complete_device_name] => Generic Android 4 Tablet [form_factor] => Tablet [is_phone] => false [is_app_webview] => false ) [all] => Array ( [brand_name] => Generic [model_name] => Android 4 Tablet [unique] => true [ununiqueness_handler] => [is_wireless_device] => true [device_claims_web_support] => true [has_qwerty_keyboard] => true [can_skip_aligned_link_row] => true [uaprof] => [uaprof2] => [uaprof3] => [nokia_series] => 0 [nokia_edition] => 0 [device_os] => Android [mobile_browser] => Android Webkit [mobile_browser_version] => [device_os_version] => 4.0 [pointing_method] => touchscreen [release_date] => 2012_january [marketing_name] => [model_extra_info] => [nokia_feature_pack] => 0 [can_assign_phone_number] => false [is_tablet] => true [manufacturer_name] => [is_bot] => false [is_google_glass] => false [proportional_font] => false [built_in_back_button_support] => false [card_title_support] => true [softkey_support] => false [table_support] => true [numbered_menus] => false [menu_with_select_element_recommended] => false [menu_with_list_of_links_recommended] => true [icons_on_menu_items_support] => false [break_list_of_links_with_br_element_recommended] => true [access_key_support] => false [wrap_mode_support] => false [times_square_mode_support] => false [deck_prefetch_support] => false [elective_forms_recommended] => true [wizards_recommended] => false [image_as_link_support] => false [insert_br_element_after_widget_recommended] => false [wml_can_display_images_and_text_on_same_line] => false [wml_displays_image_in_center] => false [opwv_wml_extensions_support] => false [wml_make_phone_call_string] => wtai://wp/mc; [chtml_display_accesskey] => false [emoji] => false [chtml_can_display_images_and_text_on_same_line] => false [chtml_displays_image_in_center] => false [imode_region] => none [chtml_make_phone_call_string] => tel: [chtml_table_support] => false [xhtml_honors_bgcolor] => true [xhtml_supports_forms_in_table] => true [xhtml_support_wml2_namespace] => false [xhtml_autoexpand_select] => false [xhtml_select_as_dropdown] => false [xhtml_select_as_radiobutton] => false [xhtml_select_as_popup] => false [xhtml_display_accesskey] => false [xhtml_supports_invisible_text] => false [xhtml_supports_inline_input] => false [xhtml_supports_monospace_font] => false [xhtml_supports_table_for_layout] => true [xhtml_supports_css_cell_table_coloring] => true [xhtml_format_as_css_property] => false [xhtml_format_as_attribute] => false [xhtml_nowrap_mode] => false [xhtml_marquee_as_css_property] => false [xhtml_readable_background_color1] => #FFFFFF [xhtml_readable_background_color2] => #FFFFFF [xhtml_allows_disabled_form_elements] => true [xhtml_document_title_support] => true [xhtml_preferred_charset] => iso-8859-1 [opwv_xhtml_extensions_support] => false [xhtml_make_phone_call_string] => tel: [xhtmlmp_preferred_mime_type] => text/html [xhtml_table_support] => true [xhtml_send_sms_string] => sms: [xhtml_send_mms_string] => mms: [xhtml_file_upload] => supported [cookie_support] => true [accept_third_party_cookie] => true [xhtml_supports_iframe] => full [xhtml_avoid_accesskeys] => true [xhtml_can_embed_video] => none [ajax_support_javascript] => true [ajax_manipulate_css] => true [ajax_support_getelementbyid] => true [ajax_support_inner_html] => true [ajax_xhr_type] => standard [ajax_manipulate_dom] => true [ajax_support_events] => true [ajax_support_event_listener] => true [ajax_preferred_geoloc_api] => w3c_api [xhtml_support_level] => 4 [preferred_markup] => html_web_4_0 [wml_1_1] => false [wml_1_2] => false [wml_1_3] => false [html_wi_w3_xhtmlbasic] => true [html_wi_oma_xhtmlmp_1_0] => true [html_wi_imode_html_1] => false [html_wi_imode_html_2] => false [html_wi_imode_html_3] => false [html_wi_imode_html_4] => false [html_wi_imode_html_5] => false [html_wi_imode_htmlx_1] => false [html_wi_imode_htmlx_1_1] => false [html_wi_imode_compact_generic] => false [html_web_3_2] => true [html_web_4_0] => true [voicexml] => false [multipart_support] => false [total_cache_disable_support] => false [time_to_live_support] => false [resolution_width] => 480 [resolution_height] => 800 [columns] => 60 [max_image_width] => 480 [max_image_height] => 800 [rows] => 40 [physical_screen_width] => 92 [physical_screen_height] => 153 [dual_orientation] => true [density_class] => 1.0 [wbmp] => true [bmp] => false [epoc_bmp] => false [gif_animated] => false [jpg] => true [png] => true [tiff] => false [transparent_png_alpha] => true [transparent_png_index] => true [svgt_1_1] => true [svgt_1_1_plus] => false [greyscale] => false [gif] => true [colors] => 65536 [webp_lossy_support] => true [webp_lossless_support] => false [post_method_support] => true [basic_authentication_support] => true [empty_option_value_support] => true [emptyok] => false [nokia_voice_call] => false [wta_voice_call] => false [wta_phonebook] => false [wta_misc] => false [wta_pdc] => false [https_support] => true [phone_id_provided] => false [max_data_rate] => 3600 [wifi] => true [sdio] => false [vpn] => false [has_cellular_radio] => true [max_deck_size] => 2000000 [max_url_length_in_requests] => 256 [max_url_length_homepage] => 0 [max_url_length_bookmark] => 0 [max_url_length_cached_page] => 0 [max_no_of_connection_settings] => 0 [max_no_of_bookmarks] => 0 [max_length_of_username] => 0 [max_length_of_password] => 0 [max_object_size] => 0 [downloadfun_support] => false [directdownload_support] => true [inline_support] => false [oma_support] => true [ringtone] => false [ringtone_3gpp] => false [ringtone_midi_monophonic] => false [ringtone_midi_polyphonic] => false [ringtone_imelody] => false [ringtone_digiplug] => false [ringtone_compactmidi] => false [ringtone_mmf] => false [ringtone_rmf] => false [ringtone_xmf] => false [ringtone_amr] => false [ringtone_awb] => false [ringtone_aac] => false [ringtone_wav] => false [ringtone_mp3] => false [ringtone_spmidi] => false [ringtone_qcelp] => false [ringtone_voices] => 1 [ringtone_df_size_limit] => 0 [ringtone_directdownload_size_limit] => 0 [ringtone_inline_size_limit] => 0 [ringtone_oma_size_limit] => 0 [wallpaper] => false [wallpaper_max_width] => 0 [wallpaper_max_height] => 0 [wallpaper_preferred_width] => 0 [wallpaper_preferred_height] => 0 [wallpaper_resize] => none [wallpaper_wbmp] => false [wallpaper_bmp] => false [wallpaper_gif] => false [wallpaper_jpg] => false [wallpaper_png] => false [wallpaper_tiff] => false [wallpaper_greyscale] => false [wallpaper_colors] => 2 [wallpaper_df_size_limit] => 0 [wallpaper_directdownload_size_limit] => 0 [wallpaper_inline_size_limit] => 0 [wallpaper_oma_size_limit] => 0 [screensaver] => false [screensaver_max_width] => 0 [screensaver_max_height] => 0 [screensaver_preferred_width] => 0 [screensaver_preferred_height] => 0 [screensaver_resize] => none [screensaver_wbmp] => false [screensaver_bmp] => false [screensaver_gif] => false [screensaver_jpg] => false [screensaver_png] => false [screensaver_greyscale] => false [screensaver_colors] => 2 [screensaver_df_size_limit] => 0 [screensaver_directdownload_size_limit] => 0 [screensaver_inline_size_limit] => 0 [screensaver_oma_size_limit] => 0 [picture] => false [picture_max_width] => 0 [picture_max_height] => 0 [picture_preferred_width] => 0 [picture_preferred_height] => 0 [picture_resize] => none [picture_wbmp] => false [picture_bmp] => false [picture_gif] => false [picture_jpg] => false [picture_png] => false [picture_greyscale] => false [picture_colors] => 2 [picture_df_size_limit] => 0 [picture_directdownload_size_limit] => 0 [picture_inline_size_limit] => 0 [picture_oma_size_limit] => 0 [video] => false [oma_v_1_0_forwardlock] => false [oma_v_1_0_combined_delivery] => false [oma_v_1_0_separate_delivery] => false [streaming_video] => true [streaming_3gpp] => true [streaming_mp4] => true [streaming_mov] => false [streaming_video_size_limit] => 0 [streaming_real_media] => none [streaming_flv] => false [streaming_3g2] => false [streaming_vcodec_h263_0] => 10 [streaming_vcodec_h263_3] => -1 [streaming_vcodec_mpeg4_sp] => 2 [streaming_vcodec_mpeg4_asp] => -1 [streaming_vcodec_h264_bp] => 3.0 [streaming_acodec_amr] => nb [streaming_acodec_aac] => lc [streaming_wmv] => none [streaming_preferred_protocol] => rtsp [streaming_preferred_http_protocol] => apple_live_streaming [wap_push_support] => false [connectionless_service_indication] => false [connectionless_service_load] => false [connectionless_cache_operation] => false [connectionoriented_unconfirmed_service_indication] => false [connectionoriented_unconfirmed_service_load] => false [connectionoriented_unconfirmed_cache_operation] => false [connectionoriented_confirmed_service_indication] => false [connectionoriented_confirmed_service_load] => false [connectionoriented_confirmed_cache_operation] => false [utf8_support] => true [ascii_support] => false [iso8859_support] => false [expiration_date] => false [j2me_cldc_1_0] => false [j2me_cldc_1_1] => false [j2me_midp_1_0] => false [j2me_midp_2_0] => false [doja_1_0] => false [doja_1_5] => false [doja_2_0] => false [doja_2_1] => false [doja_2_2] => false [doja_3_0] => false [doja_3_5] => false [doja_4_0] => false [j2me_jtwi] => false [j2me_mmapi_1_0] => false [j2me_mmapi_1_1] => false [j2me_wmapi_1_0] => false [j2me_wmapi_1_1] => false [j2me_wmapi_2_0] => false [j2me_btapi] => false [j2me_3dapi] => false [j2me_locapi] => false [j2me_nokia_ui] => false [j2me_motorola_lwt] => false [j2me_siemens_color_game] => false [j2me_siemens_extension] => false [j2me_heap_size] => 0 [j2me_max_jar_size] => 0 [j2me_storage_size] => 0 [j2me_max_record_store_size] => 0 [j2me_screen_width] => 0 [j2me_screen_height] => 0 [j2me_canvas_width] => 0 [j2me_canvas_height] => 0 [j2me_bits_per_pixel] => 0 [j2me_audio_capture_enabled] => false [j2me_video_capture_enabled] => false [j2me_photo_capture_enabled] => false [j2me_capture_image_formats] => none [j2me_http] => false [j2me_https] => false [j2me_socket] => false [j2me_udp] => false [j2me_serial] => false [j2me_gif] => false [j2me_gif89a] => false [j2me_jpg] => false [j2me_png] => false [j2me_bmp] => false [j2me_bmp3] => false [j2me_wbmp] => false [j2me_midi] => false [j2me_wav] => false [j2me_amr] => false [j2me_mp3] => false [j2me_mp4] => false [j2me_imelody] => false [j2me_rmf] => false [j2me_au] => false [j2me_aac] => false [j2me_realaudio] => false [j2me_xmf] => false [j2me_wma] => false [j2me_3gpp] => false [j2me_h263] => false [j2me_svgt] => false [j2me_mpeg4] => false [j2me_realvideo] => false [j2me_real8] => false [j2me_realmedia] => false [j2me_left_softkey_code] => 0 [j2me_right_softkey_code] => 0 [j2me_middle_softkey_code] => 0 [j2me_select_key_code] => 0 [j2me_return_key_code] => 0 [j2me_clear_key_code] => 0 [j2me_datefield_no_accepts_null_date] => false [j2me_datefield_broken] => false [receiver] => false [sender] => false [mms_max_size] => 0 [mms_max_height] => 0 [mms_max_width] => 0 [built_in_recorder] => false [built_in_camera] => true [mms_jpeg_baseline] => false [mms_jpeg_progressive] => false [mms_gif_static] => false [mms_gif_animated] => false [mms_png] => false [mms_bmp] => false [mms_wbmp] => false [mms_amr] => false [mms_wav] => false [mms_midi_monophonic] => false [mms_midi_polyphonic] => false [mms_midi_polyphonic_voices] => 0 [mms_spmidi] => false [mms_mmf] => false [mms_mp3] => false [mms_evrc] => false [mms_qcelp] => false [mms_ota_bitmap] => false [mms_nokia_wallpaper] => false [mms_nokia_operatorlogo] => false [mms_nokia_3dscreensaver] => false [mms_nokia_ringingtone] => false [mms_rmf] => false [mms_xmf] => false [mms_symbian_install] => false [mms_jar] => false [mms_jad] => false [mms_vcard] => false [mms_vcalendar] => false [mms_wml] => false [mms_wbxml] => false [mms_wmlc] => false [mms_video] => false [mms_mp4] => false [mms_3gpp] => false [mms_3gpp2] => false [mms_max_frame_rate] => 0 [nokiaring] => false [picturemessage] => false [operatorlogo] => false [largeoperatorlogo] => false [callericon] => false [nokiavcard] => false [nokiavcal] => false [sckl_ringtone] => false [sckl_operatorlogo] => false [sckl_groupgraphic] => false [sckl_vcard] => false [sckl_vcalendar] => false [text_imelody] => false [ems] => false [ems_variablesizedpictures] => false [ems_imelody] => false [ems_odi] => false [ems_upi] => false [ems_version] => 0 [siemens_ota] => false [siemens_logo_width] => 101 [siemens_logo_height] => 29 [siemens_screensaver_width] => 101 [siemens_screensaver_height] => 50 [gprtf] => false [sagem_v1] => false [sagem_v2] => false [panasonic] => false [sms_enabled] => true [wav] => false [mmf] => false [smf] => false [mld] => false [midi_monophonic] => false [midi_polyphonic] => false [sp_midi] => false [rmf] => false [xmf] => false [compactmidi] => false [digiplug] => false [nokia_ringtone] => false [imelody] => false [au] => false [amr] => false [awb] => false [aac] => true [mp3] => true [voices] => 1 [qcelp] => false [evrc] => false [flash_lite_version] => [fl_wallpaper] => false [fl_screensaver] => false [fl_standalone] => false [fl_browser] => false [fl_sub_lcd] => false [full_flash_support] => true [css_supports_width_as_percentage] => true [css_border_image] => webkit [css_rounded_corners] => webkit [css_gradient] => none [css_spriting] => true [css_gradient_linear] => none [is_transcoder] => false [transcoder_ua_header] => user-agent [rss_support] => false [pdf_support] => true [progressive_download] => true [playback_vcodec_h263_0] => 10 [playback_vcodec_h263_3] => -1 [playback_vcodec_mpeg4_sp] => 0 [playback_vcodec_mpeg4_asp] => -1 [playback_vcodec_h264_bp] => 3.0 [playback_real_media] => none [playback_3gpp] => true [playback_3g2] => false [playback_mp4] => true [playback_mov] => false [playback_acodec_amr] => nb [playback_acodec_aac] => none [playback_df_size_limit] => 0 [playback_directdownload_size_limit] => 0 [playback_inline_size_limit] => 0 [playback_oma_size_limit] => 0 [playback_acodec_qcelp] => false [playback_wmv] => none [hinted_progressive_download] => true [html_preferred_dtd] => html4 [viewport_supported] => true [viewport_width] => device_width_token [viewport_userscalable] => no [viewport_initial_scale] => [viewport_maximum_scale] => [viewport_minimum_scale] => [mobileoptimized] => false [handheldfriendly] => false [canvas_support] => full [image_inlining] => true [is_smarttv] => false [is_console] => false [nfc_support] => false [ux_full_desktop] => false [jqm_grade] => A [is_sencha_touch_ok] => false [controlcap_is_smartphone] => default [controlcap_is_ios] => default [controlcap_is_android] => default [controlcap_is_robot] => default [controlcap_is_app] => default [controlcap_advertised_device_os] => default [controlcap_advertised_device_os_version] => default [controlcap_advertised_browser] => default [controlcap_advertised_browser_version] => default [controlcap_is_windows_phone] => default [controlcap_is_full_desktop] => default [controlcap_is_largescreen] => default [controlcap_is_mobile] => default [controlcap_is_touchscreen] => default [controlcap_is_wml_preferred] => default [controlcap_is_xhtmlmp_preferred] => default [controlcap_is_html_preferred] => default [controlcap_form_factor] => default [controlcap_complete_device_name] => default ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr></table> </div> <div class="section"> <h1 class="header center orange-text">About this comparison</h1> <div class="row center"> <h5 class="header light"> The primary goal of this project is simple<br /> I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br /> <br /> The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br /> <br /> You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br /> <br /> The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a> </h5> </div> </div> <div class="card"> <div class="card-content"> Comparison created <i>2016-02-13 13:41:35</i> | by <a href="https://github.com/ThaDafinser">ThaDafinser</a> </div> </div> </div> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.1.1/list.min.js"></script> <script> $(document).ready(function(){ // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered $('.modal-trigger').leanModal(); }); </script> </body> </html>
ThaDafinser/UserAgentParserComparison
v4/user-agent-detail/e6/ea/e6eaf7e7-11e5-4133-96e9-37b82f74ebf9.html
HTML
mit
46,902
39.963319
773
0.536139
false
<html> <head> <script src='https://surikov.github.io/webaudiofont/npm/dist/WebAudioFontPlayer.js'></script> <script src='0410_Aspirin_sf2_file.js'></script> <script> var selectedPreset=_tone_0410_Aspirin_sf2_file; var AudioContextFunc = window.AudioContext || window.webkitAudioContext; var audioContext = new AudioContextFunc(); var player=new WebAudioFontPlayer(); player.adjustPreset(audioContext,selectedPreset); function startWaveTableNow(pitch) { var audioBufferSourceNode = player.queueWaveTable(audioContext, audioContext.destination, selectedPreset, audioContext.currentTime + 0, pitch, 0.4); var audioBufferSourceNode = player.queueWaveTable(audioContext, audioContext.destination, selectedPreset, audioContext.currentTime + 0.4, pitch, 0.2); var audioBufferSourceNode = player.queueWaveTable(audioContext, audioContext.destination, selectedPreset, audioContext.currentTime + 0.6, pitch, 0.2); var audioBufferSourceNode = player.queueWaveTable(audioContext, audioContext.destination, selectedPreset, audioContext.currentTime + 0.8, pitch, 4); } </script> </head> <body> <p>file: 0410_Aspirin_sf2_file.js<br/> variable: _tone_0410_Aspirin_sf2_file<br/> MIDI: 41. Viola: Strings</p> <p><a href='javascript:player.cancelQueue(audioContext);'>stop</a></p> <p>chords: <a href='javascript:startWaveTableNow(4+12*4+0); startWaveTableNow(9+12*4+0); startWaveTableNow(2+12*5+2); startWaveTableNow(7+12*5+2); startWaveTableNow(11+12*5+1); startWaveTableNow(4+12*6+0);'>Am</a> | <a href='javascript:startWaveTableNow(4+12*4+0); startWaveTableNow(9+12*4+3); startWaveTableNow(2+12*5+2); startWaveTableNow(7+12*5+0); startWaveTableNow(11+12*5+1); startWaveTableNow(4+12*6+0);'>C</a> | <a href='javascript:startWaveTableNow(4+12*4+0); startWaveTableNow(9+12*4+2); startWaveTableNow(2+12*5+2); startWaveTableNow(7+12*5+1); startWaveTableNow(11+12*5+0); startWaveTableNow(4+12*6+0);'>E</a> | <a href='javascript:startWaveTableNow(4+12*4+3); startWaveTableNow(9+12*4+2); startWaveTableNow(2+12*5+0); startWaveTableNow(7+12*5+0); startWaveTableNow(11+12*5+0); startWaveTableNow(4+12*6+3);'>G</a> </p> <p>1. <a href='javascript:startWaveTableNow(0+12*1);'>C</a> <a href='javascript:startWaveTableNow(1+12*1);'>C#</a> <a href='javascript:startWaveTableNow(2+12*1);'>D</a> <a href='javascript:startWaveTableNow(3+12*1);'>D#</a> <a href='javascript:startWaveTableNow(4+12*1);'>E</a> <a href='javascript:startWaveTableNow(5+12*1);'>F</a> <a href='javascript:startWaveTableNow(6+12*1);'>F#</a> <a href='javascript:startWaveTableNow(7+12*1);'>G</a> <a href='javascript:startWaveTableNow(8+12*1);'>G#</a> <a href='javascript:startWaveTableNow(9+12*1);'>A</a> <a href='javascript:startWaveTableNow(10+12*1);'>A#</a> <a href='javascript:startWaveTableNow(11+12*1);'>B</a> </p> <p>2. <a href='javascript:startWaveTableNow(0+12*2);'>C</a> <a href='javascript:startWaveTableNow(1+12*2);'>C#</a> <a href='javascript:startWaveTableNow(2+12*2);'>D</a> <a href='javascript:startWaveTableNow(3+12*2);'>D#</a> <a href='javascript:startWaveTableNow(4+12*2);'>E</a> <a href='javascript:startWaveTableNow(5+12*2);'>F</a> <a href='javascript:startWaveTableNow(6+12*2);'>F#</a> <a href='javascript:startWaveTableNow(7+12*2);'>G</a> <a href='javascript:startWaveTableNow(8+12*2);'>G#</a> <a href='javascript:startWaveTableNow(9+12*2);'>A</a> <a href='javascript:startWaveTableNow(10+12*2);'>A#</a> <a href='javascript:startWaveTableNow(11+12*2);'>B</a> </p> <p>3. <a href='javascript:startWaveTableNow(0+12*3);'>C</a> <a href='javascript:startWaveTableNow(1+12*3);'>C#</a> <a href='javascript:startWaveTableNow(2+12*3);'>D</a> <a href='javascript:startWaveTableNow(3+12*3);'>D#</a> <a href='javascript:startWaveTableNow(4+12*3);'>E</a> <a href='javascript:startWaveTableNow(5+12*3);'>F</a> <a href='javascript:startWaveTableNow(6+12*3);'>F#</a> <a href='javascript:startWaveTableNow(7+12*3);'>G</a> <a href='javascript:startWaveTableNow(8+12*3);'>G#</a> <a href='javascript:startWaveTableNow(9+12*3);'>A</a> <a href='javascript:startWaveTableNow(10+12*3);'>A#</a> <a href='javascript:startWaveTableNow(11+12*3);'>B</a> </p> <p>4. <a href='javascript:startWaveTableNow(0+12*4);'>C</a> <a href='javascript:startWaveTableNow(1+12*4);'>C#</a> <a href='javascript:startWaveTableNow(2+12*4);'>D</a> <a href='javascript:startWaveTableNow(3+12*4);'>D#</a> <a href='javascript:startWaveTableNow(4+12*4);'>E</a> <a href='javascript:startWaveTableNow(5+12*4);'>F</a> <a href='javascript:startWaveTableNow(6+12*4);'>F#</a> <a href='javascript:startWaveTableNow(7+12*4);'>G</a> <a href='javascript:startWaveTableNow(8+12*4);'>G#</a> <a href='javascript:startWaveTableNow(9+12*4);'>A</a> <a href='javascript:startWaveTableNow(10+12*4);'>A#</a> <a href='javascript:startWaveTableNow(11+12*4);'>B</a> </p> <p>5. <a href='javascript:startWaveTableNow(0+12*5);'>C</a> <a href='javascript:startWaveTableNow(1+12*5);'>C#</a> <a href='javascript:startWaveTableNow(2+12*5);'>D</a> <a href='javascript:startWaveTableNow(3+12*5);'>D#</a> <a href='javascript:startWaveTableNow(4+12*5);'>E</a> <a href='javascript:startWaveTableNow(5+12*5);'>F</a> <a href='javascript:startWaveTableNow(6+12*5);'>F#</a> <a href='javascript:startWaveTableNow(7+12*5);'>G</a> <a href='javascript:startWaveTableNow(8+12*5);'>G#</a> <a href='javascript:startWaveTableNow(9+12*5);'>A</a> <a href='javascript:startWaveTableNow(10+12*5);'>A#</a> <a href='javascript:startWaveTableNow(11+12*5);'>B</a> </p> <p>6. <a href='javascript:startWaveTableNow(0+12*6);'>C</a> <a href='javascript:startWaveTableNow(1+12*6);'>C#</a> <a href='javascript:startWaveTableNow(2+12*6);'>D</a> <a href='javascript:startWaveTableNow(3+12*6);'>D#</a> <a href='javascript:startWaveTableNow(4+12*6);'>E</a> <a href='javascript:startWaveTableNow(5+12*6);'>F</a> <a href='javascript:startWaveTableNow(6+12*6);'>F#</a> <a href='javascript:startWaveTableNow(7+12*6);'>G</a> <a href='javascript:startWaveTableNow(8+12*6);'>G#</a> <a href='javascript:startWaveTableNow(9+12*6);'>A</a> <a href='javascript:startWaveTableNow(10+12*6);'>A#</a> <a href='javascript:startWaveTableNow(11+12*6);'>B</a> </p> <p>7. <a href='javascript:startWaveTableNow(0+12*7);'>C</a> <a href='javascript:startWaveTableNow(1+12*7);'>C#</a> <a href='javascript:startWaveTableNow(2+12*7);'>D</a> <a href='javascript:startWaveTableNow(3+12*7);'>D#</a> <a href='javascript:startWaveTableNow(4+12*7);'>E</a> <a href='javascript:startWaveTableNow(5+12*7);'>F</a> <a href='javascript:startWaveTableNow(6+12*7);'>F#</a> <a href='javascript:startWaveTableNow(7+12*7);'>G</a> <a href='javascript:startWaveTableNow(8+12*7);'>G#</a> <a href='javascript:startWaveTableNow(9+12*7);'>A</a> <a href='javascript:startWaveTableNow(10+12*7);'>A#</a> <a href='javascript:startWaveTableNow(11+12*7);'>B</a> </p> <p>8. <a href='javascript:startWaveTableNow(0+12*8);'>C</a> <a href='javascript:startWaveTableNow(1+12*8);'>C#</a> <a href='javascript:startWaveTableNow(2+12*8);'>D</a> <a href='javascript:startWaveTableNow(3+12*8);'>D#</a> <a href='javascript:startWaveTableNow(4+12*8);'>E</a> <a href='javascript:startWaveTableNow(5+12*8);'>F</a> <a href='javascript:startWaveTableNow(6+12*8);'>F#</a> <a href='javascript:startWaveTableNow(7+12*8);'>G</a> <a href='javascript:startWaveTableNow(8+12*8);'>G#</a> <a href='javascript:startWaveTableNow(9+12*8);'>A</a> <a href='javascript:startWaveTableNow(10+12*8);'>A#</a> <a href='javascript:startWaveTableNow(11+12*8);'>B</a> </p> </body> </html>
surikov/webaudiofontdata
sound/0410_Aspirin_sf2_file.html
HTML
mit
7,832
53.769231
207
0.677605
false
'use strict'; var page = 'projects'; module.exports = { renderPage: function(req, res) { if (!req.user) { res.redirect('/login'); } else { res.render(page, { helpers: { activeClass: function(section) { if (section === 'projects') { return 'active'; } else { return ''; } } }, user: req.user ? req.user.toJSON() : null }); } } }
bobholt/genealogists-friend
app/controllers/project.js
JavaScript
mit
472
18.666667
49
0.430085
false
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-jsx) # JSX Next.js example This is a really simple project that show the usage of Next.js with JSX. ## How to use it? ``` npm install # to install dependencies npm run dev # to run next.js ```
nelak/next.js
examples/with-jsx/README.md
Markdown
mit
349
37.888889
150
0.702006
false
Search = function(data, input, result) { this.data = data; this.$input = $(input); this.$result = $(result); this.$current = null; this.$view = this.$result.parent(); this.searcher = new Searcher(data.index); this.init(); }; Search.prototype = $.extend({}, Navigation, new function() { var suid = 1; this.init = function() { var _this = this; var observer = function(e) { switch(e.originalEvent.keyCode) { case 38: // Event.KEY_UP case 40: // Event.KEY_DOWN return; } _this.search(_this.$input[0].value); }; this.$input.keyup(observer); this.$input.click(observer); // mac's clear field this.searcher.ready(function(results, isLast) { _this.addResults(results, isLast); }); this.initNavigation(); this.setNavigationActive(false); }; this.search = function(value, selectFirstMatch) { value = jQuery.trim(value).toLowerCase(); if (value) { this.setNavigationActive(true); } else { this.setNavigationActive(false); } if (value == '') { this.lastQuery = value; this.$result.empty(); this.$result.attr('aria-expanded', 'false'); this.setNavigationActive(false); } else if (value != this.lastQuery) { this.lastQuery = value; this.$result.attr('aria-busy', 'true'); this.$result.attr('aria-expanded', 'true'); this.firstRun = true; this.searcher.find(value); } }; this.addResults = function(results, isLast) { var target = this.$result.get(0); if (this.firstRun && (results.length > 0 || isLast)) { this.$current = null; this.$result.empty(); } for (var i=0, l = results.length; i < l; i++) { var item = this.renderItem.call(this, results[i]); item.setAttribute('id', 'search-result-' + target.childElementCount); target.appendChild(item); } if (this.firstRun && results.length > 0) { this.firstRun = false; this.$current = $(target.firstChild); this.$current.addClass('search-selected'); } if (jQuery.browser.msie) this.$element[0].className += ''; if (isLast) this.$result.attr('aria-busy', 'false'); }; this.move = function(isDown) { if (!this.$current) return; var $next = this.$current[isDown ? 'next' : 'prev'](); if ($next.length) { this.$current.removeClass('search-selected'); $next.addClass('search-selected'); this.$input.attr('aria-activedescendant', $next.attr('id')); this.scrollIntoView($next[0], this.$view[0]); this.$current = $next; this.$input.val($next[0].firstChild.firstChild.text); this.$input.select(); } return true; }; this.hlt = function(html) { return this.escapeHTML(html). replace(/\u0001/g, '<em>'). replace(/\u0002/g, '</em>'); }; this.escapeHTML = function(html) { return html.replace(/[&<>]/g, function(c) { return '&#' + c.charCodeAt(0) + ';'; }); } });
gadzorg/gorg_mail
doc/app/js/search.js
JavaScript
mit
2,999
26.768519
75
0.587863
false
version https://git-lfs.github.com/spec/v1 oid sha256:505b4ccd47ed9526d0238c6f2d03a343ce476abc1c4aa79a9f22cabcbd0a3c16 size 12575
yogeshsaroya/new-cdnjs
ajax/libs/require.js/0.22.0/require.min.js
JavaScript
mit
130
42.333333
75
0.884615
false
#include "ConfirmationMenu.h" ConfirmationMenu::ConfirmationMenu(CarrotQt5* mainClass, std::function<void(bool)> callback, const QString& text, const QString& yesLabel, const QString& noLabel) : MenuScreen(mainClass), text(text) { menuOptions.append(buildMenuItem([this, callback]() { root->popState(); callback(true); }, yesLabel)); menuOptions.append(buildMenuItem([this, callback]() { root->popState(); callback(false); }, noLabel)); cancelItem = buildMenuItem([this, callback]() { root->popState(); callback(false); }, noLabel); setMenuItemSelected(0); } ConfirmationMenu::~ConfirmationMenu() { } void ConfirmationMenu::renderTick(bool, bool) { auto canvas = root->getCanvas(); uint viewWidth = canvas->getView().getSize().x; uint viewHeight = canvas->getView().getSize().y; BitmapString::drawString(canvas, root->getFont(), text, viewWidth / 2, viewHeight / 2 - 50, FONT_ALIGN_CENTER); menuOptions[0]->text->drawString(canvas, viewWidth / 2 - 100, viewHeight / 2 + 50); menuOptions[1]->text->drawString(canvas, viewWidth / 2 + 100, viewHeight / 2 + 50); } void ConfirmationMenu::processControlDownEvent(const ControlEvent& e) { MenuScreen::processControlDownEvent(e); switch (e.first.keyboardKey) { case Qt::Key_Left: setMenuItemSelected(-1, true); break; case Qt::Key_Right: setMenuItemSelected(1, true); break; } }
soulweaver91/project-carrot
src/menu/ConfirmationMenu.cpp
C++
mit
1,509
33.295455
163
0.649437
false
'use strict'; //Ghost service used for communicating with the ghost api angular.module('ghost').factory('Ghost', ['$http', 'localStorageService', function($http, localStorageService) { return { login: function() { return $http.get('api/ghost/login'). success(function(data, status, headers, config) { // this callback will be called asynchronously // when the response is available data.authenticator = 'simple-auth-authenticator:oauth2-password-grant'; data.expires_at = data.expires_in + Date.now(); localStorageService.set('ghost-cms:session',data); }). error(function(data, status, headers, config) { // called asynchronously if an error occurs // or server returns response with an error status. console.log('ghost login failure'); }); } }; } ]).factory('GhostPosts', ['$http', function($http) { return { read: function(options) { return $http.get('api/ghost/posts/slug/' + options.slug). success(function(data, status, headers, config) { //console.log(data); return data; }); }, query: function(options) { return $http.get('api/ghost/posts/tag/' + options.tag). success(function(data, status, headers, config) { //console.log(data); return data; }); } }; } ]);
newcrossfoodcoop/nxfc
modules/ghost/client/services/ghost.client.service.js
JavaScript
mit
1,804
39.088889
95
0.465632
false
from flask_webapi import status from unittest import TestCase class TestStatus(TestCase): def test_is_informational(self): self.assertFalse(status.is_informational(99)) self.assertFalse(status.is_informational(200)) for i in range(100, 199): self.assertTrue(status.is_informational(i)) def test_is_success(self): self.assertFalse(status.is_success(199)) self.assertFalse(status.is_success(300)) for i in range(200, 299): self.assertTrue(status.is_success(i)) def test_is_redirect(self): self.assertFalse(status.is_redirect(299)) self.assertFalse(status.is_redirect(400)) for i in range(300, 399): self.assertTrue(status.is_redirect(i)) def test_is_client_error(self): self.assertFalse(status.is_client_error(399)) self.assertFalse(status.is_client_error(500)) for i in range(400, 499): self.assertTrue(status.is_client_error(i)) def test_is_server_error(self): self.assertFalse(status.is_server_error(499)) self.assertFalse(status.is_server_error(600)) for i in range(500, 599): self.assertTrue(status.is_server_error(i))
viniciuschiele/flask-webapi
tests/test_status.py
Python
mit
1,233
30.615385
55
0.648824
false
/* * Copyright 2014 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. */ package uk.ac.nott.mrl.gles.program; import android.opengl.GLES20; import android.util.Log; import com.android.grafika.gles.GlUtil; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; public class GraphProgram { private static final int SIZEOF_FLOAT = 4; private static final int VERTEX_STRIDE = SIZEOF_FLOAT * 2; private static final String TAG = GlUtil.TAG; private static final String VERTEX_SHADER = "uniform mat4 uMVPMatrix;" + "attribute vec4 aPosition;" + "void main() {" + " gl_Position = uMVPMatrix * aPosition;" + "}"; private static final String FRAGMENT_SHADER = "precision mediump float;" + "uniform vec4 uColor;" + "void main() {" + " gl_FragColor = uColor;" + "}"; private final int MAX_SIZE = 200; // Handles to the GL program and various components of it. private int programHandle = -1; private int colorLocation = -1; private int matrixLocation = -1; private int positionLocation = -1; private final float[] colour = {1f, 1f, 1f, 1f}; private final FloatBuffer points; private final float[] values = new float[MAX_SIZE]; private int size = 0; private int offset = 0; private boolean bufferValid = false; private float min = Float.MAX_VALUE; private float max = Float.MIN_VALUE; private static final float left = 1.8f; private static final float right = 0.2f; private static final float top = 0.8f; private static final float bottom = -0.8f; /** * Prepares the program in the current EGL context. */ public GraphProgram() { programHandle = GlUtil.createProgram(VERTEX_SHADER, FRAGMENT_SHADER); if (programHandle == 0) { throw new RuntimeException("Unable to create program"); } Log.d(TAG, "Created program " + programHandle); // get locations of attributes and uniforms ByteBuffer bb = ByteBuffer.allocateDirect(MAX_SIZE * VERTEX_STRIDE); bb.order(ByteOrder.nativeOrder()); points = bb.asFloatBuffer(); positionLocation = GLES20.glGetAttribLocation(programHandle, "aPosition"); GlUtil.checkLocation(positionLocation, "aPosition"); matrixLocation = GLES20.glGetUniformLocation(programHandle, "uMVPMatrix"); GlUtil.checkLocation(matrixLocation, "uMVPMatrix"); colorLocation = GLES20.glGetUniformLocation(programHandle, "uColor"); GlUtil.checkLocation(colorLocation, "uColor"); } /** * Releases the program. */ public void release() { GLES20.glDeleteProgram(programHandle); programHandle = -1; } public synchronized void add(float value) { values[offset] = value; min = Math.min(value, min); max = Math.max(value, max); size = Math.min(size + 1, MAX_SIZE); offset = (offset + 1) % MAX_SIZE; bufferValid = false; } public void setColour(final float r, final float g, final float b) { colour[0] = r; colour[1] = g; colour[2] = b; } private synchronized FloatBuffer getValidBuffer() { if (!bufferValid) { points.position(0); for(int index = 0; index < size; index++) { float value = values[(offset + index) % size]; float scaledValue = ((value - min) / (max - min) * (top - bottom)) + bottom; //Log.i(TAG, "x=" + ((index * (right - left) / size) + left) + ", y=" + scaledValue); points.put((index * (right - left) / (size - 1)) + left); points.put(scaledValue); } points.position(0); bufferValid = true; } return points; } public void draw(float[] matrix) { GlUtil.checkGlError("draw start"); // Select the program. GLES20.glUseProgram(programHandle); GlUtil.checkGlError("glUseProgram"); // Copy the model / view / projection matrix over. GLES20.glUniformMatrix4fv(matrixLocation, 1, false, matrix, 0); GlUtil.checkGlError("glUniformMatrix4fv"); // Copy the color vector in. GLES20.glUniform4fv(colorLocation, 1, colour, 0); GlUtil.checkGlError("glUniform4fv "); // Enable the "aPosition" vertex attribute. GLES20.glEnableVertexAttribArray(positionLocation); GlUtil.checkGlError("glEnableVertexAttribArray"); // Connect vertexBuffer to "aPosition". GLES20.glVertexAttribPointer(positionLocation, 2, GLES20.GL_FLOAT, false, VERTEX_STRIDE, getValidBuffer()); GlUtil.checkGlError("glVertexAttribPointer"); // Draw the rect. GLES20.glDrawArrays(GLES20.GL_LINE_STRIP, 0, size); GlUtil.checkGlError("glDrawArrays"); // Done -- disable vertex array and program. GLES20.glDisableVertexAttribArray(positionLocation); GLES20.glUseProgram(0); } }
ktg/openFood
src/main/java/uk/ac/nott/mrl/gles/program/GraphProgram.java
Java
mit
5,077
28.178161
89
0.702777
false
# nazdrave Като Untappd ама за ракия
bgstartupidei/nazdrave
README.md
Markdown
mit
51
17.5
25
0.783784
false
Omnom App ========= This is the example app for Omnom. See [Omnom](https://github.com/tombenner/omnom) for details. License ------- Omnom App is released under the MIT License. Please see the MIT-LICENSE file for details.
tombenner/omnom-app
README.md
Markdown
mit
225
27.125
96
0.711111
false
package org.sfm.tuples; public class Tuple20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> extends Tuple19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> { private final T20 element19; public Tuple20(T1 element0, T2 element1, T3 element2, T4 element3, T5 element4, T6 element5, T7 element6, T8 element7, T9 element8, T10 element9, T11 element10, T12 element11, T13 element12, T14 element13, T15 element14, T16 element15, T17 element16, T18 element17, T19 element18, T20 element19) { super(element0, element1, element2, element3, element4, element5, element6, element7, element8, element9, element10, element11, element12, element13, element14, element15, element16, element17, element18); this.element19 = element19; } public final T20 getElement19() { return element19; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Tuple20 tuple20 = (Tuple20) o; if (element19 != null ? !element19.equals(tuple20.element19) : tuple20.element19 != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (element19 != null ? element19.hashCode() : 0); return result; } @Override public String toString() { return "Tuple20{" + "element0=" + getElement0() + ", element1=" + getElement1() + ", element2=" + getElement2() + ", element3=" + getElement3() + ", element4=" + getElement4() + ", element5=" + getElement5() + ", element6=" + getElement6() + ", element7=" + getElement7() + ", element8=" + getElement8() + ", element9=" + getElement9() + ", element10=" + getElement10() + ", element11=" + getElement11() + ", element12=" + getElement12() + ", element13=" + getElement13() + ", element14=" + getElement14() + ", element15=" + getElement15() + ", element16=" + getElement16() + ", element17=" + getElement17() + ", element18=" + getElement18() + ", element19=" + getElement19() + '}'; } public <T21> Tuple21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> tuple21(T21 element20) { return new Tuple21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>(getElement0(), getElement1(), getElement2(), getElement3(), getElement4(), getElement5(), getElement6(), getElement7(), getElement8(), getElement9(), getElement10(), getElement11(), getElement12(), getElement13(), getElement14(), getElement15(), getElement16(), getElement17(), getElement18(), getElement19(), element20); } }
tsdl2013/SimpleFlatMapper
sfm/src/main/java/org/sfm/tuples/Tuple20.java
Java
mit
3,155
47.538462
444
0.570523
false
# Supported tags and respective `Dockerfile` links - [`8.3.0-alpha1-apache`, `8.3-rc-apache`, `rc-apache`, `8.3.0-alpha1`, `8.3-rc`, `rc` (*8.3-rc/apache/Dockerfile*)](https://github.com/docker-library/drupal/blob/a5a6b1294bd3a987d6410887ba895e5649dc163c/8.3-rc/apache/Dockerfile) - [`8.3.0-alpha1-fpm`, `8.3-rc-fpm`, `rc-fpm` (*8.3-rc/fpm/Dockerfile*)](https://github.com/docker-library/drupal/blob/a5a6b1294bd3a987d6410887ba895e5649dc163c/8.3-rc/fpm/Dockerfile) - [`8.2.6-apache`, `8.2-apache`, `8-apache`, `apache`, `8.2.6`, `8.2`, `8`, `latest` (*8.2/apache/Dockerfile*)](https://github.com/docker-library/drupal/blob/1ad01e8c9b0b34d8525e277dc6b4a6aaaddf020f/8.2/apache/Dockerfile) - [`8.2.6-fpm`, `8.2-fpm`, `8-fpm`, `fpm` (*8.2/fpm/Dockerfile*)](https://github.com/docker-library/drupal/blob/1ad01e8c9b0b34d8525e277dc6b4a6aaaddf020f/8.2/fpm/Dockerfile) - [`7.54-apache`, `7-apache`, `7.54`, `7` (*7/apache/Dockerfile*)](https://github.com/docker-library/drupal/blob/aac79bfa92b93b484bd1d459adef02789ac2e011/7/apache/Dockerfile) - [`7.54-fpm`, `7-fpm` (*7/fpm/Dockerfile*)](https://github.com/docker-library/drupal/blob/aac79bfa92b93b484bd1d459adef02789ac2e011/7/fpm/Dockerfile) For more information about this image and its history, please see [the relevant manifest file (`library/drupal`)](https://github.com/docker-library/official-images/blob/master/library/drupal). This image is updated via [pull requests to the `docker-library/official-images` GitHub repo](https://github.com/docker-library/official-images/pulls?q=label%3Alibrary%2Fdrupal). For detailed information about the virtual/transfer sizes and individual layers of each of the above supported tags, please see [the `repos/drupal/tag-details.md` file](https://github.com/docker-library/repo-info/blob/master/repos/drupal/tag-details.md) in [the `docker-library/repo-info` GitHub repo](https://github.com/docker-library/repo-info). # What is Drupal? Drupal is a free and open-source content-management framework written in PHP and distributed under the GNU General Public License. It is used as a back-end framework for at least 2.1% of all Web sites worldwide ranging from personal blogs to corporate, political, and government sites including WhiteHouse.gov and data.gov.uk. It is also used for knowledge management and business collaboration. > [wikipedia.org/wiki/Drupal](https://en.wikipedia.org/wiki/Drupal) ![logo](https://raw.githubusercontent.com/docker-library/docs/a0f37ddfd711f858bb968d6c85715f5bc1f7393f/drupal/logo.png) # How to use this image The basic pattern for starting a `drupal` instance is: ```console $ docker run --name some-drupal -d drupal ``` If you'd like to be able to access the instance from the host without the container's IP, standard port mappings can be used: ```console $ docker run --name some-drupal -p 8080:80 -d drupal ``` Then, access it via `http://localhost:8080` or `http://host-ip:8080` in a browser. There are multiple database types supported by this image, most easily used via standard container linking. In the default configuration, SQLite can be used to avoid a second container and write to flat-files. More detailed instructions for different (more production-ready) database types follow. When first accessing the webserver provided by this image, it will go through a brief setup process. The details provided below are specifically for the "Set up database" step of that configuration process. ## MySQL ```console $ docker run --name some-drupal --link some-mysql:mysql -d drupal ``` - Database type: `MySQL, MariaDB, or equivalent` - Database name/username/password: `<details for accessing your MySQL instance>` (`MYSQL_USER`, `MYSQL_PASSWORD`, `MYSQL_DATABASE`; see environment variables in the description for [`mysql`](https://registry.hub.docker.com/_/mysql/)) - ADVANCED OPTIONS; Database host: `mysql` (for using the `/etc/hosts` entry added by `--link` to access the linked container's MySQL instance) ## PostgreSQL ```console $ docker run --name some-drupal --link some-postgres:postgres -d drupal ``` - Database type: `PostgreSQL` - Database name/username/password: `<details for accessing your PostgreSQL instance>` (`POSTGRES_USER`, `POSTGRES_PASSWORD`; see environment variables in the description for [`postgres`](https://registry.hub.docker.com/_/postgres/)) - ADVANCED OPTIONS; Database host: `postgres` (for using the `/etc/hosts` entry added by `--link` to access the linked container's PostgreSQL instance) ## Volumes By default, this image does not include any volumes. There is a lot of good discussion on this topic in [docker-library/drupal#3](https://github.com/docker-library/drupal/issues/3), which is definitely recommended reading. There is consensus that `/var/www/html/modules`, `/var/www/html/profiles`, and `/var/www/html/themes` are things that generally ought to be volumes (and might have an explicit `VOLUME` declaration in a future update to this image), but handling of `/var/www/html/sites` is somewhat more complex, since the contents of that directory *do* need to be initialized with the contents from the image. If using bind-mounts, one way to accomplish pre-seeding your local `sites` directory would be something like the following: ```console $ docker run --rm drupal tar -cC /var/www/html/sites . | tar -xC /path/on/host/sites ``` This can then be bind-mounted into a new container: ```console $ docker run --name some-drupal --link some-postgres:postgres -d \ -v /path/on/host/modules:/var/www/html/modules \ -v /path/on/host/profiles:/var/www/html/profiles \ -v /path/on/host/sites:/var/www/html/sites \ -v /path/on/host/themes:/var/www/html/themes \ drupal ``` Another solution using Docker Volumes: ```console $ docker volume create drupal-sites $ docker run --rm -v drupal-sites:/temporary/sites drupal cp -aRT /var/www/html/sites /temporary/sites $ docker run --name some-drupal --link some-postgres:postgres -d \ -v drupal-modules:/var/www/html/modules \ -v drupal-profiles:/var/www/html/profiles \ -v drupal-sites:/var/www/html/sites \ -v drupal-themes:/var/www/html/themes \ ``` ## ... via [`docker-compose`](https://github.com/docker/compose) Example `docker-compose.yml` for `drupal`: ```yaml # Drupal with PostgreSQL # # Access via "http://localhost:8080" # (or "http://$(docker-machine ip):8080" if using docker-machine) # # During initial Drupal setup, # Database type: PostgreSQL # Database name: postgres # Database username: postgres # Database password: example # ADVANCED OPTIONS; Database host: postgres version: '2' services: drupal: image: drupal:8.2-apache ports: - 8080:80 volumes: - /var/www/html/modules - /var/www/html/profiles - /var/www/html/themes # this takes advantage of the feature in Docker that a new anonymous # volume (which is what we're creating here) will be initialized with the # existing content of the image at the same location - /var/www/html/sites restart: always postgres: image: postgres:9.6 environment: POSTGRES_PASSWORD: example restart: always ``` ## Adding additional libraries / extensions This image does not provide any additional PHP extensions or other libraries, even if they are required by popular plugins. There are an infinite number of possible plugins, and they potentially require any extension PHP supports. Including every PHP extension that exists would dramatically increase the image size. If you need additional PHP extensions, you'll need to create your own image `FROM` this one. The [documentation of the `php` image](https://github.com/docker-library/docs/blob/master/php/README.md#how-to-install-more-php-extensions) explains how to compile additional extensions. Additionally, the [`drupal:7` Dockerfile](https://github.com/docker-library/drupal/blob/bee08efba505b740a14d68254d6e51af7ab2f3ea/7/Dockerfile#L6-9) has an example of doing this. The following Docker Hub features can help with the task of keeping your dependent images up-to-date: - [Automated Builds](https://docs.docker.com/docker-hub/builds/) let Docker Hub automatically build your Dockerfile each time you push changes to it. - [Repository Links](https://docs.docker.com/docker-hub/builds/#repository-links) can ensure that your image is also rebuilt any time `drupal` is updated. # License View [license information](https://www.drupal.org/licensing/faq) for the software contained in this image. # Supported Docker versions This image is officially supported on Docker version 1.13.1. Support for older versions (down to 1.6) is provided on a best-effort basis. Please see [the Docker installation documentation](https://docs.docker.com/installation/) for details on how to upgrade your Docker daemon. # User Feedback ## Issues If you have any problems with or questions about this image, please contact us through a [GitHub issue](https://github.com/docker-library/drupal/issues). If the issue is related to a CVE, please check for [a `cve-tracker` issue on the `official-images` repository first](https://github.com/docker-library/official-images/issues?q=label%3Acve-tracker). You can also reach many of the official image maintainers via the `#docker-library` IRC channel on [Freenode](https://freenode.net). ## Contributing You are invited to contribute new features, fixes, or updates, large or small; we are always thrilled to receive pull requests, and do our best to process them as fast as we can. Before you start to code, we recommend discussing your plans through a [GitHub issue](https://github.com/docker-library/drupal/issues), especially for more ambitious contributions. This gives other contributors a chance to point you in the right direction, give you feedback on your design, and help you find out if someone else is working on the same thing. ## Documentation Documentation for this image is stored in the [`drupal/` directory](https://github.com/docker-library/docs/tree/master/drupal) of the [`docker-library/docs` GitHub repo](https://github.com/docker-library/docs). Be sure to familiarize yourself with the [repository's `README.md` file](https://github.com/docker-library/docs/blob/master/README.md) before attempting a pull request.
vmassol/docs
drupal/README.md
Markdown
mit
10,246
56.561798
457
0.758052
false
<?php $districts = array('Ampara', 'Anuradhapura', 'Badulla', 'Batticaloa', 'Colombo', 'Galle', 'Gampaha', 'Hambantota', 'Jaffna', 'Kaluthara', 'Kandy', 'Kilinochchi', 'Kegalle', 'Mannar', 'Matale', 'Matara', 'Monaragala', 'Mulattivu', 'Nuwaraeliya', 'Polonnaruwa', 'Rathnapura', 'Trincomalee', 'Vavuniya'); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>AdminLTE 2 | Log in</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"> <link rel="stylesheet" href="../plugins/select2/select2.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"> <!-- iCheck --> <link rel="stylesheet" href="../plugins/iCheck/square/blue.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="../plugins/select2/select2.full.min.js"></script> <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 login-page"> <div class="login-box"> <div class="login-logo"> <a href="../index2.html"><b>SCHOOL</b> LOGIN</a> </div> <!-- /.login-logo --> <div class="login-box-body"> <p class="login-box-msg">Choose your school and enter password</p> <form action="./index.php" method="post"> <div class="row"> <div class="form-group has-feedback"> <label for="name" class="col-sm-2 control-label">District</label> <div class="col-sm-12"> <select class="form-control select2" style="width: 100%;" onchange="load_district_schools(this.value)" name="district" id="district"> <option></option> <?php foreach ($districts as $district) { ?> <option><?php echo $district; ?></option> <?php } ?> </select> </div> <br><br><br><br> <div class="form-group"> <label for="name" class="col-sm-2 control-label">School</label> <div class="col-sm-12"> <select class="form-control select2" style="width: 100%;" name="schoolsfordistrict" id="schoolsfordistrict" > </select> </div> </div> </div> </div> <br> <label for="name" class=" control-label">Password</label> <div class="form-group has-feedback"> <input type="password" class="form-control" placeholder="Password" name="password"> <span class="glyphicon glyphicon-lock form-control-feedback"></span> </div> <div class="row"> <div class="col-xs-8"> <div class="checkbox icheck"> </div> </div> <!-- /.col --> <div class="col-xs-4"> <button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button> </div> <!-- /.col --> </div> <input type="hidden" id="login" name="login"> </form> </div> <!-- /.login-box-body --> </div> <!-- /.login-box --> <!-- jQuery 2.1.4 --> <script src="../plugins/jQuery/jQuery-2.1.4.min.js"></script> <script src="../plugins/select2/select2.full.min.js"></script> <!-- Bootstrap 3.3.5 --> <script src="../bootstrap/js/bootstrap.min.js"></script> <!-- iCheck --> <script src="../plugins/iCheck/icheck.min.js"></script> <script> $(function () { $('input').iCheck({ checkboxClass: 'icheckbox_square-blue', radioClass: 'iradio_square-blue', increaseArea: '20%' // optional }); }); </script> <script type="text/javascript"> $('#Date').datepicker({ autoclose: true, todayHighlight: true, format: 'yyyy-mm-dd' }); function load_district_schools(district) { if (district != "") { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById('schoolsfordistrict').innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET", "get_schools_from_district.php?district=" + district, true); xmlhttp.send(); } } function load_school_students(school_id) { if (school_id != "") { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { string = xmlhttp.responseText; alert(string); document.getElementById('studentsforschool').innerHTML = string; } }; xmlhttp.open("GET", "get_students_from_school.php?school_id=" + school_id, true); xmlhttp.send(); } } </script> <script> $(function () { //Initialize Select2 Elements $(".select2").select2(); //Datemask dd/mm/yyyy $("#datemask").inputmask("dd/mm/yyyy", {"placeholder": "dd/mm/yyyy"}); //Datemask2 mm/dd/yyyy $("#datemask2").inputmask("mm/dd/yyyy", {"placeholder": "mm/dd/yyyy"}); //Money Euro $("[data-mask]").inputmask(); //Date range picker $('#reservation').daterangepicker(); //Date range picker with time picker $('#reservationtime').daterangepicker({timePicker: true, timePickerIncrement: 30, format: 'MM/DD/YYYY h:mm A'}); //Date range as a button $('#daterange-btn').daterangepicker( { ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] }, startDate: moment().subtract(29, 'days'), endDate: moment() }, function (start, end) { $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); } ); //iCheck for checkbox and radio inputs $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({ checkboxClass: 'icheckbox_minimal-blue', radioClass: 'iradio_minimal-blue' }); //Red color scheme for iCheck $('input[type="checkbox"].minimal-red, input[type="radio"].minimal-red').iCheck({ checkboxClass: 'icheckbox_minimal-red', radioClass: 'iradio_minimal-red' }); //Flat red color scheme for iCheck $('input[type="checkbox"].flat-red, input[type="radio"].flat-red').iCheck({ checkboxClass: 'icheckbox_flat-green', radioClass: 'iradio_flat-green' }); //Colorpicker $(".my-colorpicker1").colorpicker(); //color picker with addon $(".my-colorpicker2").colorpicker(); //Timepicker $(".timepicker").timepicker({ showInputs: false }); }); </script> </body> </html>
buddhiv/DatabaseProject
school_views/login.php
PHP
mit
9,115
37.622881
301
0.512781
false
/* * file: twi.h * created: 20160807 * author(s): mr-augustine * * These are the Two-Wire Interface (TWI) bit mask definitions * They were copied from the following site: * http://www.nongnu.org/avr-libc/user-manual/group__util__twi.html * * The mnemonics are defined as follows: * TW_MT_xxx: Master Transmitter * TW_MR_xxx: Master Receiver * TW_ST_xxx: Slave Transmitter * TW_SR_xxx: Slave Receiver * * SLA: Slave Address * Comments are appended to the mask definitions we use */ #ifndef _TWI_H_ #define _TWI_H_ #define TW_START 0x08 // Start condition transmitted #define TW_REP_START 0x10 // Repeated Start condition transmitted #define TW_MT_SLA_ACK 0x18 // SLA+W transmitted, ACK received #define TW_MT_SLA_NACK 0x20 #define TW_MT_DATA_ACK 0x28 // Data transmitted, ACK received #define TW_MT_DATA_NACK 0x30 #define TW_MT_ARB_LOST 0x38 #define TW_MR_ARB_LOST 0x38 #define TW_MR_SLA_ACK 0x40 // SLA+R transmitted, ACK received #define TW_MR_SLA_NACK 0x48 #define TW_MR_DATA_ACK 0x50 // Data received, ACK returned #define TW_MR_DATA_NACK 0x58 // Data received, NACK returned #define TW_ST_SLA_ACK 0xA8 #define TW_ST_ARB_LOST_SLA_ACK 0xB0 #define TW_ST_DATA_ACK 0xB8 #define TW_ST_DATA_NACK 0xC0 #define TW_ST_LAST_DATA 0xC8 #define TW_SR_SLA_ACK 0x60 #define TW_SR_ARB_LOST_SLA_ACK 0x68 #define TW_SR_GCALL_ACK 0x70 #define TW_SR_ARB_LOST_GCALL_ACK 0x78 #define TW_SR_DATA_ACK 0x80 #define TW_SR_DATA_NACK 0x88 #define TW_SR_GCALL_DATA_ACK 0x90 #define TW_SR_GCALL_DATA_NACK 0x98 #define TW_SR_STOP 0xA0 #define TW_NO_INFO 0xF8 #define TW_BUS_ERROR 0x00 #define TW_STATUS (TWSR & TW_NO_INFO) // Grab the status bits #define TW_READ 1 // Read-mode flag #define TW_WRITE 0 // Write-mode flag #endif // #ifndef _TWI_H_
mr-augustine/kintobor
demo_sgcom/twi.h
C
mit
2,112
38.111111
79
0.602273
false
/* * This file is part of ViaVersion - https://github.com/ViaVersion/ViaVersion * Copyright (C) 2016-2021 ViaVersion and contributors * * 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 com.viaversion.viaversion.protocols.protocol1_12_2to1_12_1; import com.viaversion.viaversion.api.protocol.AbstractProtocol; import com.viaversion.viaversion.api.protocol.remapper.PacketRemapper; import com.viaversion.viaversion.api.type.Type; import com.viaversion.viaversion.protocols.protocol1_12_1to1_12.ClientboundPackets1_12_1; import com.viaversion.viaversion.protocols.protocol1_12_1to1_12.ServerboundPackets1_12_1; public class Protocol1_12_2To1_12_1 extends AbstractProtocol<ClientboundPackets1_12_1, ClientboundPackets1_12_1, ServerboundPackets1_12_1, ServerboundPackets1_12_1> { public Protocol1_12_2To1_12_1() { super(ClientboundPackets1_12_1.class, ClientboundPackets1_12_1.class, ServerboundPackets1_12_1.class, ServerboundPackets1_12_1.class); } @Override protected void registerPackets() { registerClientbound(ClientboundPackets1_12_1.KEEP_ALIVE, new PacketRemapper() { @Override public void registerMap() { map(Type.VAR_INT, Type.LONG); } }); registerServerbound(ServerboundPackets1_12_1.KEEP_ALIVE, new PacketRemapper() { @Override public void registerMap() { map(Type.LONG, Type.VAR_INT); } }); } }
MylesIsCool/ViaVersion
common/src/main/java/com/viaversion/viaversion/protocols/protocol1_12_2to1_12_1/Protocol1_12_2To1_12_1.java
Java
mit
2,084
42.416667
166
0.722169
false
//config file for bae if(sumeru.BAE_VERSION){ sumeru.config.database({ dbname : '', user: '',//bae 3.0 required password: ''//bae 3.0 required }); sumeru.config({ site_url : '' //with tailing slash }); }
Clouda-team/Cloudajs-examples
ExternalData/clouda_request_data/app/server_config/bae.js
JavaScript
mit
251
21.909091
42
0.52988
false
.preloader-background { display: flex; align-items: center; justify-content: center; background-color: #eee; position: fixed; z-index: 100; top: 0; left: 0; right: 0; bottom: 0; } .collapsible header { background-color: #546e7a !important; }
gmcfiesta/gmcfiesta.github.io
index.css
CSS
mit
267
10.125
41
0.655431
false
#include <cassert> #include <cmath> #include "gtest/gtest.h" #include "interlude.hpp" // defined in the header // #define MAT_SIZE 5 using std::cout; using std::endl; // void matDiagSum(int a[][MAT_SIZE], int rows, int cols){ // } // 1 2 3 4 5 1 2 3 4 5 // 6 7 8 9 10 6 8 10 12 14 // 11 12 13 14 15 11 18 21 24 27 // 16 17 18 19 20 16 28 36 40 44 // 21 22 23 24 25 21 38 51 60 65 // 0,0 0,1 0,2 0,3 0,4 // 1,0 1,1 1,2 1,3 1,4 // 2,0 2,1 2,2 2,3 2,4 // 3,0 3,1 3,2 3,3 3,4 // 4,0 4,1 4,2 4,3 4,4 void printArr(int arr[][MAT_SIZE], int rows, int cols) { cout << "The two dimensional array:" << endl; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { cout << arr[i][j] << "\t"; } cout << endl; } } // int digitMultiSeq(int n){ // } // int multiplyDigits(int a){ // } // bool isPermutation(unsigned int n, unsigned int m){ // } // From http://www.doc.ic.ac.uk/~wjk/C++Intro/RobMillerE3.html#Q3 // double standardDeviation(double values[], int length, int size){ // The formula for standard deviation // a is the avarage of of the values r1 ... rN // sqrt( ( ((r1 - a) x (r1 - a)) + ((r2-a) x (r2-a)) + ... + ((rN - a) x (rN - a)) ) / N ) // assert(length <= size); // } // From http://www.doc.ic.ac.uk/~wjk/C++Intro/RobMillerL6.html#S6-2 double average(double list[], int length, int size){ double total = 0; int count; for (count = 0 ; count < length ; count++) total += list[count]; return (total / length); } /*=================================================== Tests ===================================================*/ // TEST(Functions, digit_multi_seq){ // EXPECT_EQ(38, digitMultiSeq(8)); // EXPECT_EQ(62, digitMultiSeq(9)); // EXPECT_EQ(74, digitMultiSeq(10)); // } // TEST(Functions, multiply_digits){ // int a = 1234; // EXPECT_EQ(24, multiplyDigits(a)); // } // TEST(Matrix, mat_diag_sum){ // int mat[MAT_SIZE][MAT_SIZE] = { { 1, 2, 3, 4, 5}, // { 6, 7, 8, 9, 10}, // { 11, 12, 13, 14, 15}, // { 16, 17, 18, 19, 20}, // { 21, 22, 23, 24, 25}}; // int ans[MAT_SIZE][MAT_SIZE] = { {1, 2, 3, 4, 5}, // {6, 8, 10, 12, 14}, // {11, 18,21, 24, 27}, // {16, 28, 36, 40, 44}, // {21, 38, 51, 60, 65}}; // matDiagSum(mat,MAT_SIZE,MAT_SIZE); // printArr(mat,MAT_SIZE,MAT_SIZE); // printArr(ans,MAT_SIZE,MAT_SIZE); // for(int i = 0; i < MAT_SIZE; i++){ // for(int j = 0; j < MAT_SIZE; j++){ // EXPECT_EQ(ans[i][j], mat[i][j]); // } // } // } // TEST(Arrays, is_permutation){ // int n = 1234; // int m = 4231; // int n2 = 456723; // int m2 = 456724; // int n3 = 45647235; // int m3 = 45657234; // EXPECT_TRUE(isPermutation(n,m)); // EXPECT_FALSE(isPermutation(n2,m2)); // EXPECT_TRUE(isPermutation(n3,m3)); // } TEST(Functions, average){ int length = 5; int size = 5; double list[] = {2.51, 5.468, 89.12, 546.49, 65489.877}; EXPECT_DOUBLE_EQ(13226.693, average(list,length,size)); } // TEST(Arrays, standard_deviation){ // int length = 5; // int size = 5; // double list[] = {2.51, 5.468, 89.12, 546.49, 65489.877}; // double epsilon = 0.001; // EXPECT_TRUE( abs(26132.36913 - standardDeviation(list,length,size)) <= epsilon); // }
JonMuehlst/WORKSPACE_A
8_interlude/interlude.cpp
C++
mit
3,372
19.820988
91
0.511862
false
<?php /** * @author "Michael Collette" <metrol@metrol.net> * @package Metrol_Libs * @version 2.0 * @copyright (c) 2014, Michael Collette */ namespace Metrol\HTML\Table; /** * Defines an HTML Table Foot Area */ class Foot extends Section { /** */ public function __construct() { parent::__construct('tfoot'); $this->rows = array(); } }
Metrol/Metrol
HTML/Table/Foot.php
PHP
mit
364
14.166667
49
0.612637
false
clean_zsh_history ================= Erase tautological history in `.zsh_history`. # Usage python ./clean_zsh_history.py [path/to/.zsh_history] default arguments is `$HOME/.zsh_history`
xeno1991/clean_zsh_history
README.md
Markdown
mit
192
16.454545
54
0.661458
false
import sys sys.path.insert(0,'../') from fast_guided_filter import blur print("hello")
justayak/fast_guided_filters
test/sample.py
Python
mit
88
16.6
35
0.715909
false