code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/* This script generates mock data for local development. This way you don't have to point to an actual API, but you can enjoy realistic, but randomized data, and rapid page loads due to local, static data. */ /* eslint-disable no-console */ import jsf from 'json-schema-faker'; import {schema} from './mockDataSchema'; import fs from 'fs'; import chalk from 'chalk'; const json = JSON.stringify(jsf.resolve(schema)); fs.writeFile("./src/api/db.json", json, function(err) { if (err) { console.log(chalk.red(err)); } else { console.log(chalk.green("Mock data generated.")); } });
davefud/js-dev-env
buildScripts/generateMockData.js
JavaScript
mit
604
import logging import ConfigParser from collections import namedtuple # User Configuration Handler class ConfigHandler: # Some Config Constants FILE_NAME = 'app.cfg' FILE_MODE = 'wb' CONSUMER_SECTION = 'Consumer Info' ACCESS_SECTION = 'Access Info' MENTION_SECTION = 'Mention Info' CONSUMER_KEY = 'CONSUMER_KEY' CONSUMER_SECRET = 'CONSUMER_SECRET' ACCESS_KEY = 'ACCESS_KEY' ACCESS_SECRET = 'ACCESS_SECRET' MENTION_ID = 'MENTION_ID' def __init__(self): self.config = ConfigParser.SafeConfigParser() self.get_config() # GETTERS!!! def consumer_key(self): return self.config.get(self.CONSUMER_SECTION, self.CONSUMER_KEY) def consumer_secret(self): return self.config.get(self.CONSUMER_SECTION, self.CONSUMER_SECRET) def access_key(self): return self.config.get(self.ACCESS_SECTION, self.ACCESS_KEY) def access_secret(self): return self.config.get(self.ACCESS_SECTION, self.ACCESS_SECRET) def mention_id(self): return self.config.get(self.MENTION_SECTION, self.MENTION_ID) # Gets settings out of the config file def get_config(self): logging.info('Attempting to read configuration') try: self.config.read(self.FILE_NAME) logging.info('Config read') except (ConfigParser.Error): logging.error("There was an error reading your configuration") return None # Set a config values def set_value(self, section, option, value): logging.info('Updating Configuration Values') self.config.set(section, option, value) # Write changes to file with open(self.FILE_NAME, self.FILE_MODE) as configFile: self.config.write(configFile)
Th3BFG/hex-note
HexNote/confighandler.py
Python
mit
1,649
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MathML { public abstract class MathMLElement : IMathMLNode { [MathMLAttributeName("id")] [MathMLAttributeOrderIndex(1)] [DefaultValue("")] public string Id { get; set; } [MathMLAttributeName("class")] [MathMLAttributeOrderIndex(2)] [DefaultValue("")] public string StyleClass { get; set; } [MathMLAttributeName("style")] [MathMLAttributeOrderIndex(3)] [DefaultValue("")] public string Style { get; set; } [MathMLAttributeName("href")] [MathMLAttributeOrderIndex(4)] [DefaultValue("")] public string HRef { get; set; } [MathMLAttributeName("mathbackground")] [MathMLAttributeOrderIndex(5)] public MathMLColor MathBackgroundColor { get; set; } [MathMLAttributeName("mathcolor")] [MathMLAttributeOrderIndex(6)] public MathMLColor MathColor { get; set; } public IMathMLNode Parent { get; set; } public IList<IMathMLNode> Children { get; set; } public MathMLElement() { Id = ""; StyleClass = ""; Style = ""; HRef = ""; Parent = null; Children = new List<IMathMLNode>(); } } }
BenjaminTMilnes/MathML
MathML/MathMLElement.cs
C#
mit
1,408
import { NgModule } from '@angular/core'; import { SharedModule } from '../shared/shared.module'; import { NgBusyModule } from 'ng-busy'; import { SurvivalRoutingModule } from './survival-routing.module'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { CommonModule } from '@angular/common'; import { HotkeyModule } from 'angular2-hotkeys'; import { NgxDatatableModule } from '@swimlane/ngx-datatable'; import { SurvivalFormComponent } from './survival-form.component'; import { SurvivalSummaryComponent } from './survival-summary.component'; import { SurvivalSummaryTableComponent } from './survival-summary-table.component'; import { SurvivalReportComponent } from './survival-report.component'; import { SurvivalProbabilityComponent } from './survival-probability.component'; import { SurvivalChanceComponent } from './survival-chance.component'; import { LifeTableService } from '../shared/life-table/life-table.service'; import { SurvivalService } from './survival.service'; import { ApiService } from '../shared/services/api.service'; @NgModule({ imports: [ CommonModule, HotkeyModule, FormsModule, ReactiveFormsModule, NgxDatatableModule, SharedModule, NgBusyModule, SurvivalRoutingModule ], declarations: [ SurvivalFormComponent, SurvivalSummaryComponent, SurvivalSummaryTableComponent, SurvivalReportComponent, SurvivalProbabilityComponent, SurvivalChanceComponent, ], providers: [ LifeTableService, SurvivalService, ApiService ] }) export class SurvivalModule { }
brevinL/longevity-visualizer-front-end
src/app/survival/survival.module.ts
TypeScript
mit
1,553
package fi.csc.chipster.sessionworker; public class SupportRequest { private String message; private String mail; private String session; private String app; private String log; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getMail() { return mail; } public void setMail(String email) { this.mail = email; } public String getSession() { return session; } public void setSession(String session) { this.session = session; } public String getApp() { return app; } public void setApp(String app) { this.app = app; } public String getLog() { return log; } public void setLog(String log) { this.log = log; } }
chipster/chipster-web-server
src/main/java/fi/csc/chipster/sessionworker/SupportRequest.java
Java
mit
748
using System; namespace RecurringInterval { public abstract class Interval { protected Interval(Period period) { Period = period; } public int TotalDays => (int)EndDate.Subtract(StartDate).TotalDays + 1; public DateTime StartDate { get; protected set; } public DateTime EndDate { get; protected set; } public Period Period { get; } static readonly IntervalFactory factory = new IntervalFactory(); public static Interval Create(Period period, DateTime startDate, DateTime? firstStartDate = null) { return factory.CreateFromStartDate(period, startDate, firstStartDate); } public abstract Interval Next(); } }
ribbles/RecurringInterval
RecurringInterval/Interval.cs
C#
mit
786
/* global describe,it */ var getSlug = require('../lib/speakingurl'); describe('getSlug symbols', function () { 'use strict'; it('should convert symbols', function (done) { getSlug('Foo & Bar | Baz') .should.eql('foo-and-bar-or-baz'); getSlug('Foo & Bar | Baz', { lang: 'cs' }) .should.eql('foo-a-bar-nebo-baz'); getSlug('Foo & Bar | Baz', { lang: 'en' }) .should.eql('foo-and-bar-or-baz'); getSlug('Foo & Bar | Baz', { lang: 'de' }) .should.eql('foo-und-bar-oder-baz'); getSlug('Foo & Bar | Baz', { lang: 'fr' }) .should.eql('foo-et-bar-ou-baz'); getSlug('Foo & Bar | Baz', { lang: 'es' }) .should.eql('foo-y-bar-u-baz'); getSlug('Foo & Bar | Baz', { lang: 'ru' }) .should.eql('foo-i-bar-ili-baz'); getSlug('Foo & Bar | Baz', { lang: 'ro' }) .should.eql('foo-si-bar-sau-baz'); getSlug('Foo & Bar | Baz', { lang: 'sk' }) .should.eql('foo-a-bar-alebo-baz'); done(); }); it('shouldn\'t convert symbols', function (done) { getSlug('Foo & Bar | Baz', { symbols: false }) .should.eql('foo-bar-baz'); getSlug('Foo & Bar | Baz', { lang: 'en', symbols: false }) .should.eql('foo-bar-baz'); getSlug('Foo & Bar | Baz', { lang: 'de', symbols: false }) .should.eql('foo-bar-baz'); getSlug('Foo & Bar | Baz', { lang: 'fr', symbols: false }) .should.eql('foo-bar-baz'); getSlug('Foo & Bar | Baz', { lang: 'es', symbols: false }) .should.eql('foo-bar-baz'); getSlug('Foo & Bar | Baz', { lang: 'ru', symbols: false }) .should.eql('foo-bar-baz'); getSlug('Foo & Bar | Baz', { lang: 'cs', symbols: false }) .should.eql('foo-bar-baz'); getSlug('Foo & Bar | Baz', { lang: 'sk', symbols: false }) .should.eql('foo-bar-baz'); done(); }); it('should not convert symbols with uric flag true', function (done) { getSlug('Foo & Bar | Baz', { uric: true }) .should.eql('foo-&-bar-or-baz'); getSlug('Foo & Bar | Baz', { lang: 'en', uric: true }) .should.eql('foo-&-bar-or-baz'); getSlug('Foo & Bar | Baz', { lang: 'de', uric: true }) .should.eql('foo-&-bar-oder-baz'); getSlug('Foo & Bar | Baz', { lang: 'fr', uric: true }) .should.eql('foo-&-bar-ou-baz'); getSlug('Foo & Bar | Baz', { lang: 'es', uric: true }) .should.eql('foo-&-bar-u-baz'); getSlug('Foo & Bar | Baz', { lang: 'ru', uric: true }) .should.eql('foo-&-bar-ili-baz'); getSlug('Foo & Bar | Baz', { lang: 'cs', uric: true }) .should.eql('foo-&-bar-nebo-baz'); getSlug('Foo & Bar | Baz', { lang: 'sk', uric: true }) .should.eql('foo-&-bar-alebo-baz'); done(); }); it('should not convert symbols with uricNoSlash flag true', function (done) { getSlug('Foo & Bar | Baz', { uricNoSlash: true }) .should.eql('foo-&-bar-or-baz'); getSlug('Foo & Bar | Baz', { lang: 'en', uricNoSlash: true }) .should.eql('foo-&-bar-or-baz'); getSlug('Foo & Bar | Baz', { lang: 'de', uricNoSlash: true }) .should.eql('foo-&-bar-oder-baz'); getSlug('Foo & Bar | Baz', { lang: 'fr', uricNoSlash: true }) .should.eql('foo-&-bar-ou-baz'); getSlug('Foo & Bar | Baz', { lang: 'es', uricNoSlash: true }) .should.eql('foo-&-bar-u-baz'); getSlug('Foo & Bar | Baz', { lang: 'ru', uricNoSlash: true }) .should.eql('foo-&-bar-ili-baz'); getSlug('Foo & Bar | Baz', { lang: 'cs', uricNoSlash: true }) .should.eql('foo-&-bar-nebo-baz'); getSlug('Foo & Bar | Baz', { lang: 'sk', uricNoSlash: true }) .should.eql('foo-&-bar-alebo-baz'); done(); }); it('should not convert symbols with mark flag true', function (done) { getSlug('Foo (Bar) . Baz', { mark: true }) .should.eql('foo-(bar)-.-baz'); getSlug('Foo (Bar) . Baz', { lang: 'en', mark: true }) .should.eql('foo-(bar)-.-baz'); getSlug('Foo (Bar) . Baz', { lang: 'de', mark: true }) .should.eql('foo-(bar)-.-baz'); getSlug('Foo (Bar) . Baz', { lang: 'fr', mark: true }) .should.eql('foo-(bar)-.-baz'); getSlug('Foo (Bar) . Baz', { lang: 'es', mark: true }) .should.eql('foo-(bar)-.-baz'); getSlug('Foo (Bar) . Baz', { lang: 'ru', mark: true }) .should.eql('foo-(bar)-.-baz'); getSlug('Foo (Bar) . Baz', { lang: 'cs', mark: true }) .should.eql('foo-(bar)-.-baz'); getSlug('Foo (Bar) . Baz', { lang: 'sk', mark: true }) .should.eql('foo-(bar)-.-baz'); done(); }); it('should convert symbols with flags true', function (done) { getSlug('Foo (♥) ; Baz=Bar', { lang: 'en', uric: true, uricNoSlash: true, mark: true }) .should.eql('foo-(love)-;-baz=bar'); getSlug('Foo (♥) ; Baz=Bar', { lang: 'de', uric: true, uricNoSlash: true, mark: true }) .should.eql('foo-(liebe)-;-baz=bar'); getSlug('Foo (♥) ; Baz=Bar', { lang: 'fr', uric: true, uricNoSlash: true, mark: true }) .should.eql('foo-(amour)-;-baz=bar'); getSlug('Foo (♥) ; Baz=Bar', { lang: 'es', uric: true, uricNoSlash: true, mark: true }) .should.eql('foo-(amor)-;-baz=bar'); getSlug('Foo (♥) ; Baz=Bar', { lang: 'ru', uric: true, uricNoSlash: true, mark: true }) .should.eql('foo-(lubov)-;-baz=bar'); getSlug('Foo (♥) ; Baz=Bar', { lang: 'cs', uric: true, uricNoSlash: true, mark: true }) .should.eql('foo-(laska)-;-baz=bar'); getSlug('Foo (♥) ; Baz=Bar', { lang: 'sk', uric: true, uricNoSlash: true, mark: true }) .should.eql('foo-(laska)-;-baz=bar'); getSlug(' Sch(* )ner (♥)Ti♥tel ♥läßt grüßen!? Bel♥♥ été !', { lang: 'en', uric: true, uricNoSlash: true, mark: true, maintainCase: true }) .should.eql( 'Sch(*-)ner-(love)Ti-love-tel-love-laesst-gruessen!?-Bel-love-love-ete-!' ); done(); }); it('should replace symbols (de)', function (done) { getSlug('Äpfel & Birnen', { lang: 'de' }) .should.eql('aepfel-und-birnen'); getSlug('ÄÖÜäöüß', { lang: 'de', maintainCase: true }) .should.eql('AeOeUeaeoeuess'); done(); }); it('should replace chars by cs language standards', function (done) { getSlug( 'AaÁáBbCcČčDdĎďEeÉéĚěFfGgHhChchIiÍíJjKkLlMmNnŇňOoÓóPpQqRrŘřSsŠšTtŤťUuÚúŮůVvWwXxYyÝýZzŽž', { lang: 'cs' }) .should.eql( 'aaaabbccccddddeeeeeeffgghhchchiiiijjkkllmmnnnnooooppqqrrrrssssttttuuuuuuvvwwxxyyyyzzzz' ); getSlug( 'AaÁáBbCcČčDdĎďEeÉéĚěFfGgHhChchIiÍíJjKkLlMmNnŇňOoÓóPpQqRrŘřSsŠšTtŤťUuÚúŮůVvWwXxYyÝýZzŽž', { lang: 'cs', maintainCase: true }) .should.eql( 'AaAaBbCcCcDdDdEeEeEeFfGgHhChchIiIiJjKkLlMmNnNnOoOoPpQqRrRrSsSsTtTtUuUuUuVvWwXxYyYyZzZz' ); done(); }); it('should replace chars by fi language standards', function (done) { getSlug( 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZzÅåÄäÖö', { lang: 'fi', maintainCase: true }) .should.eql( 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZzAaAaOo' ); done(); }); it('should replace chars by sk language standards', function (done) { getSlug( 'AaÁaÄäBbCcČčDdĎďDzdzDždžEeÉéFfGgHhChchIiÍíJjKkLlĹ弾MmNnŇňOoÓóÔôPpQqRrŔŕSsŠšTtŤťUuÚúVvWwXxYyÝýZzŽž', { lang: 'sk' }) .should.eql( 'aaaaaabbccccdddddzdzdzdzeeeeffgghhchchiiiijjkkllllllmmnnnnooooooppqqrrrrssssttttuuuuvvwwxxyyyyzzzz' ); getSlug( 'AaÁaÄäBbCcČčDdĎďDzdzDždžEeÉéFfGgHhChchIiÍíJjKkLlĹ弾MmNnŇňOoÓóÔôPpQqRrŔŕSsŠšTtŤťUuÚúVvWwXxYyÝýZzŽž', { lang: 'sk', maintainCase: true }) .should.eql( 'AaAaAaBbCcCcDdDdDzdzDzdzEeEeFfGgHhChchIiIiJjKkLlLlLlMmNnNnOoOoOoPpQqRrRrSsSsTtTtUuUuVvWwXxYyYyZzZz' ); done(); }); it('should ignore not available language param', function (done) { getSlug('Äpfel & Birnen', { lang: 'xx' }) .should.eql('aepfel-and-birnen'); done(); }); it('should convert currency symbols to lowercase', function (done) { getSlug('NEXUS4 only €199!', { maintainCase: false }) .should.eql('nexus4-only-eur199'); getSlug('NEXUS4 only €299.93', { maintainCase: false }) .should.eql('nexus4-only-eur299-93'); getSlug('NEXUS4 only 円399.73', { maintainCase: false }) .should.eql('nexus4-only-yen399-73'); done(); }); it('should convert currency symbols to uppercase', function (done) { getSlug('NEXUS4 only €199!', { maintainCase: true }) .should.eql('NEXUS4-only-EUR199'); getSlug('NEXUS4 only €299.93', { maintainCase: true }) .should.eql('NEXUS4-only-EUR299-93'); getSlug('NEXUS4 only 円399.73', { maintainCase: true }) .should.eql('NEXUS4-only-YEN399-73'); done(); }); });
jotamaggi/react-calendar-app
node_modules/speakingurl/test/test-lang.js
JavaScript
mit
12,387
#include "SoundSource.hpp" #include "../Entity/Entity.hpp" #include "../Hymn.hpp" #include "../Audio/SoundFile.hpp" #include "../Audio/SoundBuffer.hpp" #include "../Manager/Managers.hpp" #include "../Manager/ResourceManager.hpp" using namespace Component; SoundSource::SoundSource() { alGenSources(1, &source); soundBuffer = new Audio::SoundBuffer(); } SoundSource::~SoundSource() { alDeleteSources(1, &source); Audio::SoundFile* soundFile = soundBuffer->GetSoundFile(); if (soundFile) Managers().resourceManager->FreeSound(soundFile); delete soundBuffer; } Json::Value SoundSource::Save() const { Json::Value component; Audio::SoundFile* soundFile = soundBuffer->GetSoundFile(); if (soundFile) component["sound"] = soundFile->path + soundFile->name; component["pitch"] = pitch; component["gain"] = gain; component["loop"] = loop; return component; } void SoundSource::Play() { shouldPlay = true; } void SoundSource::Pause() { shouldPause = true; } void SoundSource::Stop() { shouldStop = true; }
Chainsawkitten/HymnToBeauty
src/Engine/Component/SoundSource.cpp
C++
mit
1,089
[?php if ('NONE' != $fieldset): ?] <h2 class="titleSection">[?php echo __($fieldset, array(), '<?php echo $this->getI18nCatalogue() ?>') ?]</h2> [?php endif; ?] <div class="fieldSection"> <fieldset id="sf_fieldset_[?php echo preg_replace('/[^a-z0-9_]/', '_', strtolower($fieldset)) ?]"> [?php foreach ($fields as $name => $field): ?] [?php if ((isset($form[$name]) && $form[$name]->isHidden()) || (!isset($form[$name]) && $field->isReal())) continue ?] [?php include_partial('<?php echo $this->getModuleName() ?>/form_field', array( 'name' => $name, 'attributes' => $field->getConfig('attributes', array()), 'label' => $field->getConfig('label'), 'help' => $field->getConfig('help'), 'form' => $form, 'field' => $field, 'class' => 'sf_admin_form_row sf_admin_'.strtolower($field->getType()).' sf_admin_form_field_'.$name, )) ?] [?php endforeach; ?] </fieldset> </div>
retrofox/sfPropelMooDooPlugin
trunk/plugin/data/generator/sfPropelModule/mooDooAdmin/template/templates/_form_fieldset.php
PHP
mit
1,025
/*global module:false*/ module.exports = function(grunt) { // Project configuration. grunt.initConfig({ // Metadata. pkg: grunt.file.readJSON('package.json'), banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + '<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' + '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' + ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n', // Task configuration. watch: { compass: { files: ['app/styles/{,*/}*.{scss,sass}'], tasks: ['compass:server'] } }, open: { server: { path: 'http://localhost:<%= connect.options.port %>' } }, clean: { dist: { files: [{ dot: true, src: [ '.tmp', 'dist/*', '!dist/.git*' ] }] }, server: '.tmp' }, compass: { options: { sassDir: 'app/styles', cssDir: 'app/styles', generatedImagesDir: '.tmp/images/generated', imagesDir: 'app/images', javascriptsDir: 'app/scripts', fontsDir: 'app/styles/fonts', importPath: 'app/bower_components', httpImagesPath: '/images', httpGeneratedImagesPath: '/images/generated', httpFontsPath: '/styles/fonts', relativeAssets: false }, dist: {}, server: { options: { debugInfo: false } } }, }); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-compass'); grunt.registerTask('server', function (target) { if (target === 'dist') { return grunt.task.run(['build', 'open', 'connect:dist:keepalive']); } grunt.task.run([ 'clean:server', 'concurrent:server', 'connect:livereload', 'open', 'watch' ]); }); // Default task. grunt.registerTask('default', ['watch']); };
jussiip/wamefork
Gruntfile.js
JavaScript
mit
2,290
Resetme::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both thread web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Enable Rack::Cache to put a simple HTTP cache in front of your application # Add `rack-cache` to your Gemfile before enabling this. # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid. # config.action_dispatch.rack_cache = true # Disable Rails's static asset server (Apache or nginx will already do this). config.serve_static_assets = false # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Generate digests for assets URLs. config.assets.digest = true # Version of your assets, change this if you want to expire all your assets. config.assets.version = '1.0' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Set to :debug to see everything in the log. config.log_level = :info # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups. # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production. # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # config.assets.precompile += %w( search.js ) # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Disable automatic flushing of the log to improve performance. # config.autoflush_log = false # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new end
hidnasio/resetme
config/environments/production.rb
Ruby
mit
3,251
/** * Using Rails-like standard naming convention for endpoints. * GET /things -> index * POST /things -> create * GET /things/:id -> show * PUT /things/:id -> update * DELETE /things/:id -> destroy */ import {notFound, invalidData} from './errors'; import awaitify from 'awaitify'; import _ from 'lodash'; import {loadGroupUsers} from './api-utils'; import UserGroup from './models/user-group.model'; import User from './models/user.model'; export const index = awaitify(function *(req, res, next) { try { const userGroups = yield UserGroup.find({}).exec(); res.status(200).json(userGroups); } catch (err) { return next(err); } }); export const show = awaitify(function *(req, res, next) { try { const {params:{id}} = req; const userGroup = yield UserGroup.findById(id).exec(); if (!userGroup) { return notFound(req, res); } res.status(200).json(userGroup); } catch (err) { return next(err); } }); export const create = awaitify(function *(req, res, next) { try { const {body:{name}} = req; if (!name) { return invalidData(req, res); } let userGroup = new UserGroup(); userGroup.name = name; userGroup.users = []; const result = yield userGroup.save(); res.status(200).json(result); } catch (err) { return next(err); } }); export const update = awaitify(function *(req, res, next) { try { const {body:{name}, params:{id}} = req; if (!name || !id) { return invalidData(req, res); } const userGroup = yield UserGroup.findById(id).exec(); if (!userGroup) { return notFound(req, res); } userGroup.name = name; const result = yield userGroup.save().exec(); res.status(200).json(result); } catch (err) { return next(err); } }); export const users = awaitify(function *(req, res, next) { try { const {params:{name}} = req; if (!name) { return invalidData(req, res); } const result = yield loadGroupUsers(name); if (!result) { return notFound(req, res); } res.status(200).json(result); } catch (err) { return next(err); } }); export const assignUsersToGroup = awaitify(function *(req, res, next) { try { const {body, params:{name}} = req; if (!name || !_.isArray(body)) { return invalidData(req, res); } const userGroup = yield UserGroup.findOne({name}).exec(); if (!userGroup) { return notFound(req, res); } userGroup.users = _.uniq(userGroup.users.concat(body)); userGroup.markModified('users'); const result = yield userGroup.save(); res.status(200).json(result); } catch (err) { return next(err); } }); export const unassignUsersFromGroup = awaitify(function *(req, res, next) { try { const {body, params:{name}} = req; if (!name || !_.isArray(body)) { return invalidData(req, res); } const userGroup = yield UserGroup.findOne({name}).exec(); if (!userGroup) { return notFound(req, res); } _.remove(userGroup.users, id => _.includes(body, String(id))); userGroup.markModified('users'); const result = yield userGroup.save(); res.status(200).json(result); } catch (err) { return next(err); } }); export const destroy = awaitify(function *(req, res, next) { try { const userGroup = yield UserGroup.findById(req.params.id).exec(); if (!userGroup || userGroup.users.length) { return invalidData(req, res); } const result = yield UserGroup.findByIdAndRemove(req.params.id).exec(); res.status(200).json(result); } catch (err) { return next(err); } });
fixjs/user-management-app
src/apis/user-group.api.js
JavaScript
mit
3,703
<?php namespace Korsmakolnikov\InternalBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Class DependencyFactory * @package Korsmakolnikov\InternalBundle\DependencyInjection */ class DependencyFactory implements ContainerAwareInterface { /** * @var ContainerInterface */ protected $container; /** * DependencyFactory constructor. * @param ContainerInterface $container */ public function __construct(ContainerInterface $container) { $this->container = $container; } /** * Sets the container. * * @param ContainerInterface|null $container */ public function setContainer(ContainerInterface $container = null) { $this->container = $container; } /** * @param array|string $serviceName * @return DependencyMasterDecorator */ public function create($serviceName) { if(is_array($serviceName)) { $dependencyDecorator = $wrap = null; foreach ($serviceName as $s) { $dependencyDecorator = $this->decorate($dependencyDecorator, $s); } return $dependencyDecorator; } $dependencyDecorator = $this->createDecorator($serviceName); return $dependencyDecorator; } /** * @param DependencyMasterDecorator|null $host * @param $service * @return DependencyMasterDecorator */ private function decorate(DependencyMasterDecorator $host = null, $service) { if($service && $host) { $tmp = $host; $host = $this->createDecorator($service); $host->wrap($tmp); return $host; } return $this->createDecorator($service); } /** * @param $serviceName * @return DependencyMasterDecorator */ private function createDecorator($serviceName) { $dependencyDecorator = new DependencyMasterDecorator($serviceName); $dependencyDecorator->setService($this->container->get($serviceName)); return $dependencyDecorator; } }
korsmakolnikov/InternalBundle
DependencyInjection/DependencyFactory.php
PHP
mit
2,196
var express = require('express'); var app = express(); var uid = require('uid'); var databaseUrl = 'mongodb://dev:angular@ds047107.mongolab.com:47107/getitrightdev'; var collections = ['active_users']; var db = require('mongojs').connect(databaseUrl, collections); app.use(express.static('public')); app.use(express.json()); //Getting Data app.get('/api/active-users', function(req, res) { var now = new Date().valueOf(), criteria = new Date(now - 5 * 60 * 60000); db.active_users.find({'last_updated': {'$gte': criteria}}).toArray(function(err, results) { res.send(results.map(function(item, i) { return {long: item.coords.long, lat: item.coords.lat}; })); }); }); //Storing DATA app.post('/api/heartbeat', function(req, res) { var data = { id: req.body.id, coords: { long: req.query.long, lat: req.query.lat }, last_updated: new Date() }; console.log(data.id); if (data.id) { db.active_users.update({id: data.id}, data, callback); } else { data.id = uid(); db.active_users.save(data, callback); } function callback(err, saved) { if (err || !saved) { res.send('Couldnt proceed'); } else { res.send(data.id); } } }); var server = app.listen(3030, function() { console.log('Listening on port %d', server.address().port); });
getitrightio/getitright-server
app/server.js
JavaScript
mit
1,356
<?php namespace Veta\HomeworkBundle\Controller; use RedCode\TreeBundle\Controller\TreeAdminController; class CategoryAdminController extends TreeAdminController { }
eltrubetskaya/blog
src/Veta/HomeworkBundle/Controller/CategoryAdminController.php
PHP
mit
168
// 74: String - `endsWith()` // To do: make all tests pass, leave the assert lines unchanged! var assert = require("assert"); describe('`str.endsWith(searchString)` determines whether `str` ends with `searchString`.', function() { const s = 'el fin'; describe('1st parameter, the string to search for', function() { it('works with just a character', function() { const doesEndWith = s.endsWith('n'); assert.equal(doesEndWith, true); }); it('works with a string', function() { const expected = true; assert.equal(s.endsWith('fin'), expected); }); it('works with unicode characters', function() { const nuclear = '☢'; assert.equal(nuclear.endsWith('☢'), true); }); it('a regular expression throws a TypeError', function() { const aRegExp = /the/; assert.throws(() => {''.endsWith(aRegExp)}, TypeError); }); }); describe('2nd parameter, searches within this string as if this string were only this long', function() { it('find "el" at a substring of the length 2', function() { const endPos = 2; assert.equal(s.endsWith('el', endPos), true); }); it('`undefined` uses the entire string', function() { const _undefined_ = undefined; assert.equal(s.endsWith('fin', _undefined_), true); }); it('the parameter gets coerced to an int', function() { const position = '5'; assert.equal(s.endsWith('fi', position), true); }); describe('value less than 0', function() { it('returns `true`, when searching for an empty string', function() { const emptyString = ''; assert.equal('1'.endsWith(emptyString, -1), true); }); it('return `false`, when searching for a non-empty string', function() { const notEmpty = '??'; assert.equal('1'.endsWith(notEmpty, -1), false); }); }); }); describe('transfer the functionality to other objects', function() { const endsWith = (...args) => String.prototype.endsWith.call(...args); it('e.g. a boolean', function() { let aBool = true; assert.equal(endsWith(!aBool, 'lse'), true); }); it('e.g. a number', function() { let aNumber = 84; assert.equal(endsWith(aNumber + 1900, 84), true); }); it('also using the position works', function() { const position = 3; assert.equal(endsWith(1994, '99', position), true); }); }); });
jostw/es6-katas
tests/74-string-ends-with.js
JavaScript
mit
2,438
# frozen_string_literal: true require 'spec_helper' module Steam module Networking describe Packet do it 'requies a tcp body' do expect do Packet.new(nil) end.to raise_error(RuntimeError) expect do Packet.new('') end.to raise_error(RuntimeError) end it 'has a TCP identifier' do expect(Packet::TCP_MAGIC).to eq('VT01') end describe 'valid packet object' do before do # size and random junk of size identifier = 123 tcp = [identifier].pack('l') @packet = Packet.new(tcp) end it 'can encode to a valve packet' do expect(@packet.encode).to eq("\x04\x00\x00\x00VT01{\x00\x00\x00") end it 'encapsulates a raw tcp body' do expect(@packet.body).to eq("{\x00\x00\x00") end it 'has a message type' do expect(@packet.msg_type).to eq(123) expect(@packet.emsg).to eq(@packet.msg_type) end it 'is not multi' do expect(@packet.multi?).to eq(false) end it 'can decodes protobuf client messages' do msg = ProtobufMessage.new(MsgHdrProtoBuf.new, Steamclient::CMsgClientLoggedOff.new, EMsg::CLIENT_LOG_OFF) tcp = msg.encode @packet = Packet.new(tcp) msg = @packet.as_message(Steamclient::CMsgClientLogOff.new) expect(msg.header).to be_a(MsgHdrProtoBuf) expect(msg.body).to be_a(Steamclient::CMsgClientLogOff) end it 'can decodes client messages' do msg = ClientMessage.new(MsgHdr.new, MsgChannelEncryptResponse.new, EMsg::CHANNEL_ENCRYPT_RESPONSE) tcp = msg.encode @packet = Packet.new(tcp) msg = @packet.as_message(MsgChannelEncryptResponse.new) expect(msg.header).to be_a(MsgHdr) expect(msg.body).to be_a(MsgChannelEncryptResponse) expect(msg.emsg).to eq(EMsg::CHANNEL_ENCRYPT_RESPONSE) end end describe 'a multi packet object' do before do # size and random junk of size identifier = EMsg::MULTI tcp = [identifier].pack('l') @packet = Packet.new(tcp) end it 'has a truthy multi? flag' do expect(@packet.multi?).to eq(true) end end end end end
fastpeek/steam
spec/steam/networking/packet_spec.rb
Ruby
mit
2,516
require 'spec_helper' describe AridCache do describe 'results' do before :each do Company.destroy_all @company1 = Company.make(:name => 'a') @company2 = Company.make(:name => 'b') Company.class_caches do ordered_by_name { Company.all(:order => 'name ASC') } end Company.clear_caches end it "order should match the original order" do 3.times do |t| results = Company.cached_ordered_by_name results.size.should == 2 results[0].name.should == @company1.name results[1].name.should == @company2.name end end it "order should match the order option" do 3.times do |t| results = Company.cached_ordered_by_name(:order => 'name DESC') results.size.should == 2 results[0].name.should == @company2.name results[1].name.should == @company1.name end end it "with order option should go to the database to order" do lambda { Company.cached_ordered_by_name(:order => 'name DESC').inspect }.should query(2) end it "should apply limit *before* going to the database when the result is cached and no order is specified" do Company.cached_ordered_by_name id = @company1.id lambda { Company.cached_ordered_by_name(:limit => 1).inspect }.should query("SELECT \"companies\".* FROM \"companies\" WHERE (\"companies\".id in (#{id})) ORDER BY CASE WHEN \"companies\".id=#{id} THEN 1 END LIMIT 1") end it "should apply limit after going to the database when an order is specified" do Company.cached_ordered_by_name lambda { Company.cached_ordered_by_name(:limit => 1, :order => 'name DESC').inspect }.should query("SELECT \"companies\".* FROM \"companies\" WHERE (\"companies\".id in (#{@company1.id},#{@company2.id})) ORDER BY name DESC LIMIT 1") end it "should order in memory when enabled" do Company.cached_ordered_by_name with_order_in_memory do lambda { Company.cached_ordered_by_name(:limit => 1).inspect }.should query("SELECT \"companies\".* FROM \"companies\" WHERE (\"companies\".id in (#{@company1.id}))") end end end it "should set the special raw flag" do AridCache.raw_with_options.should be_false AridCache.raw_with_options = true AridCache.raw_with_options.should be_true end describe "pagination" do before :each do @user = User.make @user.companies << Company.make end it "should not fail if the page is nil" do lambda { @user.cached_companies(:page => nil) @user.cached_companies(:page => nil) # works when seeding, so call again to load from cache }.should_not raise_error(WillPaginate::InvalidPage) end end end
kjvarga/arid_cache
spec/arid_cache/arid_cache_spec.rb
Ruby
mit
2,815
#include <iostream> #include <algorithm> #include <vector> #include <string> using namespace std; #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) #define dump(x) cerr << #x << " = " << (x) << endl; int n=16; int a[16] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}; int dp[100]; int search(int a[], int cur, int edge) { if (cur > n) return edge; int cv = a[cur]; if (dp[cv] != 0) { dp[cv]+=1; int i=cv+1; while(dp[i]!=0 && dp[i]<dp[cv]) { dp[i]=dp[cv]; i+=1; } return search(a, cur+1, edge); } int v = dp[edge]; FOR(i,edge+1,cv) { dp[i]=v; } dp[cv] = v+1; return search(a, cur+1, cv); } void solve() { memset(dp, 0, sizeof(dp)); cout << dp[search(a, 0, 0)] << endl; } int main(int argc, char const *argv[]) { solve(); }
k-ori/algorithm-playground
src/dp/longest-increasing-subsequence/longest-increasing-subsequence-org.cpp
C++
mit
823
<?php namespace Pandora\MainBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class PandoraMainBundle extends Bundle { }
Kilo3/pandora
src/Pandora/MainBundle/PandoraMainBundle.php
PHP
mit
130
package io.cucumber.core.backend; /** * Marks a glue class as being scenario scoped. * <p> * Instances of scenario scoped glue can not be used between scenarios and will * be removed from the glue. This is useful when the glue holds a reference to a * scenario scoped object (e.g. a method closure). */ public interface ScenarioScoped { /** * Disposes of the test execution context. * <p> * Scenario scoped step definition may be used in events. Thus retaining a * potential reference to the test execution context. When many tests are * used this may result in an over consumption of memory. Disposing of the * execution context resolves this problem. */ default void dispose() { } }
cucumber/cucumber-jvm
core/src/main/java/io/cucumber/core/backend/ScenarioScoped.java
Java
mit
742
require_relative "helper" setup do machine = MicroMachine.new(:pending) machine.when(:confirm, pending: :confirmed) machine.when(:reset, confirmed: :pending) machine.on(:pending) { @state = "Pending" } machine.on(:confirmed) { @state = "Confirmed" } machine.on(:any) { @current = @state } machine end test "executes callbacks when entering a state" do |machine| machine.trigger(:confirm) assert_equal "Confirmed", @state machine.trigger(:reset) assert_equal "Pending", @state end test "executes the callback on any transition" do |machine| machine.trigger(:confirm) assert_equal "Confirmed", @current machine.trigger(:reset) assert_equal "Pending", @current end test "passing the event name to the callbacks" do event_name = nil machine = MicroMachine.new(:pending) machine.when(:confirm, pending: :confirmed) machine.on(:confirmed) do |event| event_name = event end machine.trigger(:confirm) assert_equal(:confirm, event_name) end test "passing the payload from transition to the callbacks" do received_payload = nil machine = MicroMachine.new(:pending) machine.when(:confirm, pending: :confirmed) machine.on(:confirmed) do |_event, payload| received_payload = payload end machine.trigger(:confirm, foo: :bar) assert_equal({ foo: :bar }, received_payload) end
soveran/micromachine
test/callbacks.rb
Ruby
mit
1,352
var merge = require('merge'); var clone = require('clone'); var Field = require('./field'); var maxCounter = require('../mixins/max-counter'); module.exports = function() { return merge.recursive(Field(), { props: { placeholder: { type:String, required:false, default:'' }, disabled: { type: Boolean }, tinymce:{ default: false }, debounce:{ type:Number, default:300 }, lazy:{ type:Boolean }, toggler:{ type:Boolean }, togglerButton:{ type:Object, default:function() { return { expand:'Expand', minimize:'Minimize' } } } }, data: function() { return { editor: null, expanded:false, fieldType:'textarea', tagName:'textarea' } }, methods:{ toggle: function() { this.expanded=!this.expanded; var textarea = $(this.$el).find("textarea"); height = this.expanded?textarea.get(0).scrollHeight:"auto"; textarea.height(height); this.$dispatch('vue-formular.textarea-was-toggled', {expanded:this.expanded}); } }, computed:merge(maxCounter, { togglerText: function() { return this.expanded?this.togglerButton.minimize:this.togglerButton.expand; } }), ready: function() { if (this.tinymce===false) return; var that = this; var setup = that.tinymce && that.tinymce.hasOwnProperty('setup')? that.tinymce.setup: function() {}; var parentSetup = that.getForm().options.tinymceOptions.hasOwnProperty('setup')? that.getForm().options.tinymceOptions.setup: function(){}; var options = typeof this.tinymce=='object'? merge.recursive(clone(this.getForm().options.tinymceOptions), this.tinymce): this.getForm().options.tinymceOptions; options = merge.recursive(options, { selector:'textarea[name=' + this.name +']', setup : function(ed) { that.editor = ed; parentSetup(ed); setup(ed); ed.on('change',function(e) { that.value = ed.getContent(); }.bind(this)); } }); tinymce.init(options); this.$watch('value', function(val) { if(val != tinymce.get("textarea_" + this.name).getContent()) { tinymce.get("textarea_" + this.name).setContent(val); } }); } }); }
matfish2/vue-formular
lib/components/fields/textarea.js
JavaScript
mit
2,395
package jnesulator.core.nes.audio; public class TriangleTimer extends Timer { private static int periodadd = 1; private static int[] triangle = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; private int divider = 0; public TriangleTimer() { period = 0; position = 0; } @Override public void clock() { if (period == 0) { return; } ++divider; // note: stay away from negative division to avoid rounding problems int periods = (divider + period + periodadd) / (period + periodadd); if (periods < 0) { periods = 0; // can happen if period or periodadd were made smaller } position = (position + periods) & 0x1F; divider -= (period + periodadd) * periods; } @Override public void clock(int cycles) { if (period == 0) { return; } divider += cycles; // note: stay away from negative division to avoid rounding problems int periods = (divider + period + periodadd) / (period + periodadd); if (periods < 0) { periods = 0; // can happen if period or periodadd were made smaller } position = (position + periods) & 0x1F; divider -= (period + periodadd) * periods; } @Override public int getval() { return (period == 0) ? 7 : triangle[position]; // needed to avoid screech when period is zero } @Override public void reset() { // no way to reset the triangle } @Override public void setduty(int duty) { throw new UnsupportedOperationException("Triangle counter has no duty setting."); } @Override public void setduty(int[] duty) { throw new UnsupportedOperationException("Triangle counter has no duty setting."); } @Override public void setperiod(int newperiod) { period = newperiod; if (period == 0) { position = 7; } } }
thomas-kendall/jnesulator
jnesulator-core/src/main/java/jnesulator/core/nes/audio/TriangleTimer.java
Java
mit
1,785
<?php namespace Ghw\UserBundle\Controller; use Symfony\Component\HttpFoundation\RedirectResponse; use FOS\UserBundle\Controller\RegistrationController as BaseController; class LoginController extends BaseController { public function loginAction() { $request = $this->container->get('request'); /* @var $request \Symfony\Component\HttpFoundation\Request */ $session = $request->getSession(); /* @var $session \Symfony\Component\HttpFoundation\Session */ // get the error if any (works with forward and redirect -- see below) if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) { $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR); } elseif (null !== $session && $session->has(SecurityContext::AUTHENTICATION_ERROR)) { $error = $session->get(SecurityContext::AUTHENTICATION_ERROR); $session->remove(SecurityContext::AUTHENTICATION_ERROR); } else { $error = ''; } if ($error) { // TODO: this is a potential security risk (see http://trac.symfony-project.org/ticket/9523) $error = $error->getMessage(); } // last username entered by the user $lastUsername = (null === $session) ? '' : $session->get(SecurityContext::LAST_USERNAME); $csrfToken = $this->container->get('form.csrf_provider')->generateCsrfToken('authenticate'); return $this->renderLogin(array( 'last_username' => $lastUsername, 'error' => $error, 'csrf_token' => $csrfToken, )); } }
deuxnids/Wiloma
src/Ghw/UserBundle/Controller/LoginController.php
PHP
mit
1,652
import i18n from 'mi18n' import Sortable from 'sortablejs' import h, { indexOfNode } from '../common/helpers' import dom from '../common/dom' import { ANIMATION_SPEED_SLOW, ANIMATION_SPEED_FAST } from '../constants' import { merge } from '../common/utils' const defaults = Object.freeze({ type: 'field', displayType: 'slider', }) const getTransition = val => ({ transform: `translateX(${val ? `${val}px` : 0})` }) /** * Edit and control sliding panels */ export default class Panels { /** * Panels initial setup * @param {Object} options Panels config * @return {Object} Panels */ constructor(options) { this.opts = merge(defaults, options) this.panelDisplay = this.opts.displayType this.activePanelIndex = 0 this.panelNav = this.createPanelNav() const panelsWrap = this.createPanelsWrap() this.nav = this.navActions() const resizeObserver = new window.ResizeObserver(([{ contentRect: { width } }]) => { if (this.currentWidth !== width) { this.toggleTabbedLayout() this.currentWidth = width this.nav.setTranslateX(this.activePanelIndex, false) } }) const observeTimeout = window.setTimeout(() => { resizeObserver.observe(panelsWrap) window.clearTimeout(observeTimeout) }, ANIMATION_SPEED_SLOW) } getPanelDisplay() { const column = this.panelsWrap const width = parseInt(dom.getStyle(column, 'width')) const autoDisplayType = width > 390 ? 'tabbed' : 'slider' const isAuto = this.opts.displayType === 'auto' this.panelDisplay = isAuto ? autoDisplayType : this.opts.displayType || defaults.displayType return this.panelDisplay } toggleTabbedLayout = () => { this.getPanelDisplay() const isTabbed = this.isTabbed this.panelsWrap.parentElement.classList.toggle('tabbed-panels', isTabbed) if (isTabbed) { this.panelNav.removeAttribute('style') } return isTabbed } /** * Resize the panel after its contents change in height * @return {String} panel's height in pixels */ resizePanels = () => { this.toggleTabbedLayout() const panelStyle = this.panelsWrap.style const activePanelHeight = dom.getStyle(this.currentPanel, 'height') panelStyle.height = activePanelHeight return activePanelHeight } /** * Wrap a panel and make properties sortable * if the panel belongs to a field * @return {Object} DOM element */ createPanelsWrap() { const panelsWrap = dom.create({ className: 'panels', content: this.opts.panels.map(({ config: { label }, ...panel }) => panel), }) if (this.opts.type === 'field') { this.sortableProperties(panelsWrap) } this.panelsWrap = panelsWrap this.panels = panelsWrap.children this.currentPanel = this.panels[this.activePanelIndex] return panelsWrap } /** * Sortable panel properties * @param {Array} panels * @return {Array} panel groups */ sortableProperties(panels) { const _this = this const groups = panels.getElementsByClassName('field-edit-group') return h.forEach(groups, (group, index) => { group.fieldId = _this.opts.id if (group.isSortable) { Sortable.create(group, { animation: 150, group: { name: 'edit-' + group.editGroup, pull: true, put: ['properties'], }, sort: true, handle: '.prop-order', onSort: evt => { _this.propertySave(evt.to) _this.resizePanels() }, }) } }) } createPanelNavLabels() { const labels = this.opts.panels.map(panel => ({ tag: 'h5', action: { click: evt => { const index = indexOfNode(evt.target, evt.target.parentElement) this.currentPanel = this.panels[index] const labels = evt.target.parentElement.childNodes this.nav.refresh(index) dom.removeClasses(labels, 'active-tab') evt.target.classList.add('active-tab') }, }, content: panel.config.label, })) const panelLabels = { className: 'panel-labels', content: { content: labels, }, } const [firstLabel] = labels firstLabel.className = 'active-tab' return dom.create(panelLabels) } /** * Panel navigation, tabs and arrow buttons for slider * @return {Object} DOM object for panel navigation wrapper */ createPanelNav() { this.labels = this.createPanelNavLabels() const next = { tag: 'button', attrs: { className: 'next-group', title: i18n.get('controlGroups.nextGroup'), type: 'button', }, dataset: { toggle: 'tooltip', placement: 'top', }, action: { click: e => this.nav.nextGroup(e), }, content: dom.icon('triangle-right'), } const prev = { tag: 'button', attrs: { className: 'prev-group', title: i18n.get('controlGroups.prevGroup'), type: 'button', }, dataset: { toggle: 'tooltip', placement: 'top', }, action: { click: e => this.nav.prevGroup(e), }, content: dom.icon('triangle-left'), } return dom.create({ tag: 'nav', attrs: { className: 'panel-nav', }, content: [prev, this.labels, next], }) } get isTabbed() { return this.panelDisplay === 'tabbed' } /** * Handlers for navigating between panel groups * @todo refactor to use requestAnimationFrame instead of css transitions * @return {Object} actions that control panel groups */ navActions() { const action = {} const groupParent = this.currentPanel.parentElement const labelWrap = this.labels.firstChild const siblingGroups = this.currentPanel.parentElement.childNodes this.activePanelIndex = indexOfNode(this.currentPanel, groupParent) let offset = { nav: 0, panel: 0 } let lastOffset = { ...offset } const groupChange = newIndex => { const labels = labelWrap.children dom.removeClasses(siblingGroups, 'active-panel') dom.removeClasses(labels, 'active-tab') this.currentPanel = siblingGroups[newIndex] this.currentPanel.classList.add('active-panel') labels[newIndex].classList.add('active-tab') return this.currentPanel } const getOffset = index => { return { nav: -labelWrap.offsetWidth * index, panel: -groupParent.offsetWidth * index, } } const translateX = ({ offset, reset, duration = ANIMATION_SPEED_FAST, animate = !this.isTabbed }) => { const panelQueue = [getTransition(lastOffset.panel), getTransition(offset.panel)] const navQueue = [getTransition(lastOffset.nav), getTransition(this.isTabbed ? 0 : offset.nav)] if (reset) { const [panelStart] = panelQueue const [navStart] = navQueue panelQueue.push(panelStart) navQueue.push(navStart) } const animationOptions = { easing: 'ease-in-out', duration: animate ? duration : 0, fill: 'forwards', } const panelTransition = groupParent.animate(panelQueue, animationOptions) labelWrap.animate(navQueue, animationOptions) const handleFinish = () => { this.panelsWrap.style.height = dom.getStyle(this.currentPanel, 'height') panelTransition.removeEventListener('finish', handleFinish) if (!reset) { lastOffset = offset } } panelTransition.addEventListener('finish', handleFinish) } action.setTranslateX = (panelIndex, animate = true) => { offset = getOffset(panelIndex || this.activePanelIndex) translateX({ offset, animate }) } action.refresh = newIndex => { if (newIndex !== undefined) { this.activePanelIndex = newIndex groupChange(newIndex) } this.resizePanels() action.setTranslateX(this.activePanelIndex, false) } /** * Slides panel to the next group * @return {Object} current group after navigation */ action.nextGroup = () => { const newIndex = this.activePanelIndex + 1 if (newIndex !== siblingGroups.length) { const curPanel = groupChange(newIndex) offset = { nav: -labelWrap.offsetWidth * newIndex, panel: -curPanel.offsetLeft, } translateX({ offset }) this.activePanelIndex++ } else { offset = { nav: lastOffset.nav - 8, panel: lastOffset.panel - 8, } translateX({ offset, reset: true }) } return this.currentPanel } action.prevGroup = () => { if (this.activePanelIndex !== 0) { const newIndex = this.activePanelIndex - 1 const curPanel = groupChange(newIndex) offset = { nav: -labelWrap.offsetWidth * newIndex, panel: -curPanel.offsetLeft, } translateX({ offset }) this.activePanelIndex-- } else { offset = { nav: 8, panel: 8, } translateX({ offset, reset: true }) } } return action } }
Draggable/formeo
src/js/components/panels.js
JavaScript
mit
9,240
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DiscordSharp.Commands { public abstract class IModule { /// <summary> /// The name of the module. /// </summary> public virtual string Name { get; set; } = "module"; /// <summary> /// A description talking about what the module contains /// </summary> public virtual string Description { get; set; } = "Please set this in the constructor of your IModule derivative."; /// <summary> /// A list of the commands this module contains /// </summary> public virtual List<ICommand> Commands { get; internal set; } = new List<ICommand>(); /// <summary> /// Installs the module's commands into the commands manager /// </summary> /// <param name="manager"></param> public abstract void Install(CommandsManager manager); /// <summary> /// Uninstall's this modules's commands from the given module manager. /// </summary> /// <param name="manager"></param> public void Uninstall(CommandsManager manager) { lock (manager.Commands) { foreach (var command in manager.Commands) { var thisModulesCommand = Commands.Find(x => x.ID == command.ID && x.Parent.Name == this.Name); //compare modules by name just in case if (thisModulesCommand != null) manager.Commands.Remove(command); } } } } }
Luigifan/DiscordSharp
DiscordSharp.Commands/IModule.cs
C#
mit
1,662
/* * Copyright (c) 2012 VMware, Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ (function (buster, define) { "use strict"; var assert, refute, undef; assert = buster.assert; refute = buster.refute; define('probe/stats/mean-test', function (require) { var mean, counter; mean = require('probe/stats/mean'); counter = require('probe/stats/counter'); buster.testCase('probe/stats/mean', { 'update the mean for each new value': function () { var m = mean(); assert.same(1, m(1)); assert.same(2, m(3)); assert.same(2, m(2)); assert.same(4, m(10)); assert.same(0, m(-16)); assert.same(1 / 6, m(1)); }, 'allow counter to be injected': function () { var m, c; c = counter(); m = mean(c); c.inc(); assert.same(1, m(1)); c.inc(); assert.same(2, m(3)); c.inc(); assert.same(2, m(2)); c.inc(); assert.same(4, m(10)); c.inc(); assert.same(0, m(-16)); c.inc(); assert.same(1 / 6, m(1)); }, 'injected counters must be incremented manually': function () { var m = mean(counter()); assert.same(Number.POSITIVE_INFINITY, m(1)); }, 'not passing a value returns the most recent mean': function () { var m = mean(); assert.same(1, m(1)); assert.same(1, m()); assert.same(1, m()); }, 'should restart from NaN when reset': function () { var m = mean(); assert.same(NaN, m()); assert.same(1, m(1)); assert.same(2, m(3)); m.reset(); assert.same(NaN, m()); assert.same(1, m(1)); assert.same(2, m(3)); }, 'should not update the readOnly stat': function () { var m, ro; m = mean(); ro = m.readOnly(); assert.same(NaN, m()); assert.same(NaN, ro()); assert.same(1, m(1)); assert.same(1, ro(2)); ro.reset(); assert.same(1, m()); m.reset(); assert.same(NaN, m()); assert.same(NaN, ro()); assert.same(ro, ro.readOnly()); } }); }); }( this.buster || require('buster'), typeof define === 'function' && define.amd ? define : function (id, factory) { var packageName = id.split(/[\/\-]/)[0], pathToRoot = id.replace(/[^\/]+/g, '..'); pathToRoot = pathToRoot.length > 2 ? pathToRoot.substr(3) : pathToRoot; factory(function (moduleId) { return require(moduleId.indexOf(packageName) === 0 ? pathToRoot + moduleId.substr(packageName.length) : moduleId); }); } // Boilerplate for AMD and Node ));
s2js/probes
test/stats/mean-test.js
JavaScript
mit
3,493
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("01.PriorityQueueImplementation")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("01.PriorityQueueImplementation")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7791088d-2137-46b3-bfa2-75a2e51f83ee")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
ni4ka7a/TelerikAcademyHomeworks
DataStructuresAndAlgorithms/05.AdvancedDataStructures/01.PriorityQueueImplementation/Properties/AssemblyInfo.cs
C#
mit
1,436
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RevStack.Client.API.Membership { public interface IValidation { void Validate(Object obj); bool IsValid { get; } Exception Exception { get; } ValidationType ValidationType { get; } } }
MISInteractive/revstack-net
src/REVStack.Client/API/Membership/IValidation.cs
C#
mit
359
/** * Copyright (c) 2010 by Gabriel Birke * * 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. */ function Sanitize(){ var i, e, options; options = arguments[0] || {} this.config = {} this.config.elements = options.elements ? options.elements : []; this.config.attributes = options.attributes ? options.attributes : {}; this.config.attributes[Sanitize.ALL] = this.config.attributes[Sanitize.ALL] ? this.config.attributes[Sanitize.ALL] : []; this.config.allow_comments = options.allow_comments ? options.allow_comments : false; this.allowed_elements = {}; this.config.protocols = options.protocols ? options.protocols : {}; this.config.add_attributes = options.add_attributes ? options.add_attributes : {}; this.dom = options.dom ? options.dom : document; for(i=0;i<this.config.elements.length;i++) { this.allowed_elements[this.config.elements[i]] = true; } this.config.remove_element_contents = {}; this.config.remove_all_contents = false; if(options.remove_contents) { if(options.remove_contents instanceof Array) { for(i=0;i<options.remove_contents.length;i++) { this.config.remove_element_contents[options.remove_contents[i]] = true; } } else { this.config.remove_all_contents = true; } } this.transformers = options.transformers ? options.transformers : []; } Sanitize.REGEX_PROTOCOL = /^([A-Za-z0-9\+\-\.\&\;\*\s]*?)(?:\:|&*0*58|&*x0*3a)/i Sanitize.RELATIVE = '__relative__'; // emulate Ruby symbol with string constant Sanitize.prototype.clean_node = function(container) { var fragment = this.dom.createDocumentFragment(); this.current_element = fragment; this.whitelist_nodes = []; /** * Utility function to check if an element exists in an array */ function _array_index(needle, haystack) { var i; for(i=0; i < haystack.length; i++) { if(haystack[i] == needle) return i; } return -1; } function _merge_arrays_uniq() { var result = []; var uniq_hash = {} var i,j; for(i=0;i<arguments.length;i++) { if(!arguments[i] || !arguments[i].length) continue; for(j=0;j<arguments[i].length;j++) { if(uniq_hash[arguments[i][j]]) continue; uniq_hash[arguments[i][j]] = true; result.push(arguments[i][j]); } } return result; } /** * Clean function that checks the different node types and cleans them up accordingly * @param elem DOM Node to clean */ function _clean(elem) { var clone; switch(elem.nodeType) { // Element case 1: _clean_element.call(this, elem) break; // Text case 3: var clone = elem.cloneNode(false); this.current_element.appendChild(clone); break; // Entity-Reference (normally not used) case 5: var clone = elem.cloneNode(false); this.current_element.appendChild(clone); break; // Comment case 8: if(this.config.allow_comments) { var clone = elem.cloneNode(false); this.current_element.appendChild(clone); } default: //console.log("unknown node type", elem.nodeType) } } function _clean_element(elem) { var i, j, clone, parent_element, name, allowed_attributes, attr, attr_name, attr_node, protocols, del, attr_ok; var transform = _transform_element.call(this, elem); elem = transform.node; name = elem.nodeName.toLowerCase(); // check if element itself is allowed parent_element = this.current_element; if(this.allowed_elements[name] || transform.whitelist) { this.current_element = this.dom.createElement(elem.nodeName); parent_element.appendChild(this.current_element); // clean attributes allowed_attributes = _merge_arrays_uniq( this.config.attributes[name], this.config.attributes['__ALL__'], transform.attr_whitelist ); for(i=0;i<allowed_attributes.length;i++) { attr_name = allowed_attributes[i]; attr = elem.attributes[attr_name]; if(attr) { attr_ok = true; // Check protocol attributes for valid protocol if(this.config.protocols[name] && this.config.protocols[name][attr_name]) { protocols = this.config.protocols[name][attr_name]; del = attr.nodeValue.toLowerCase().match(Sanitize.REGEX_PROTOCOL); if(del) { attr_ok = (_array_index(del[1], protocols) != -1); } else { attr_ok = (_array_index(Sanitize.RELATIVE, protocols) != -1); } } if(attr_ok) { attr_node = document.createAttribute(attr_name); attr_node.value = attr.nodeValue; this.current_element.setAttributeNode(attr_node); } } } // Add attributes if(this.config.add_attributes[name]) { for(attr_name in this.config.add_attributes[name]) { attr_node = document.createAttribute(attr_name); attr_node.value = this.config.add_attributes[name][attr_name]; this.current_element.setAttributeNode(attr_node); } } } // End checking if element is allowed // If this node is in the dynamic whitelist array (built at runtime by // transformers), let it live with all of its attributes intact. else if(_array_index(elem, this.whitelist_nodes) != -1) { this.current_element = elem.cloneNode(true); // Remove child nodes, they will be sanitiazied and added by other code while(this.current_element.childNodes.length > 0) { this.current_element.removeChild(this.current_element.firstChild); } parent_element.appendChild(this.current_element); } // iterate over child nodes if(!this.config.remove_all_contents && !this.config.remove_element_contents[name]) { for(i=0;i<elem.childNodes.length;i++) { _clean.call(this, elem.childNodes[i]); } } // some versions of IE don't support normalize. if(this.current_element.normalize) { this.current_element.normalize(); } this.current_element = parent_element; } // END clean_element function function _transform_element(node) { var output = { attr_whitelist:[], node: node, whitelist: false } var i, j, transform; for(i=0;i<this.transformers.length;i++) { transform = this.transformers[i]({ allowed_elements: this.allowed_elements, config: this.config, node: node, node_name: node.nodeName.toLowerCase(), whitelist_nodes: this.whitelist_nodes, dom: this.dom }); if(transform == null) continue; else if(typeof transform == 'object') { if(transform.whitelist_nodes && transform.whitelist_nodes instanceof Array) { for(j=0;j<transform.whitelist_nodes.length;j++) { if(_array_index(transform.whitelist_nodes[j], this.whitelist_nodes) == -1) { this.whitelist_nodes.push(transform.whitelist_nodes[j]); } } } output.whitelist = transform.whitelist ? true : false; if(transform.attr_whitelist) { output.attr_whitelist = _merge_arrays_uniq(output.attr_whitelist, transform.attr_whitelist); } output.node = transform.node ? transform.node : output.node; } else { throw new Error("transformer output must be an object or null"); } } return output; } for(i=0;i<container.childNodes.length;i++) { _clean.call(this, container.childNodes[i]); } if(fragment.normalize) { fragment.normalize(); } return fragment; } if(!Sanitize.Config) { Sanitize.Config = {}; } Sanitize.Config.BASIC = { elements: [ 'a', 'b', 'blockquote', 'br', 'cite', 'code', 'dd', 'dl', 'dt', 'em', 'i', 'li', 'ol', 'p', 'pre', 'q', 'small', 'strike', 'strong', 'sub', 'sup', 'u', 'ul'], attributes: { 'a' : ['href'], 'blockquote': ['cite'], 'q' : ['cite'] }, add_attributes: { 'a': {'rel': 'nofollow'} }, protocols: { 'a' : {'href': ['ftp', 'http', 'https', 'mailto', Sanitize.RELATIVE]}, 'blockquote': {'cite': ['http', 'https', Sanitize.RELATIVE]}, 'q' : {'cite': ['http', 'https', Sanitize.RELATIVE]} } };
kurbmedia/transit-legacy
app/assets/javascripts/libs/sanitize.js
JavaScript
mit
9,555
export default { actions: { edit: '編集', save: 'セーブ', cancel: 'キャンセル', new: '新しい', list: 'リスト', }, }
HospitalRun/hospitalrun-frontend
src/shared/locales/ja/translations/actions/index.ts
TypeScript
mit
156
const router = require('express').Router() const albumsQueries = require('../../db/albums') const albumsRoutes = require('./albums') const usersQueries = require('../../db/users') const usersRoutes = require('./users') const reviewsQueries = require('../../db/reviews') const {getSimpleDate} = require('../utils') router.use('/albums', albumsRoutes) router.use('/users', usersRoutes) router.get('/', (req, res) => { if (req.session.user) { const userSessionID = req.session.user[0].id const userSession = req.session.user[0] reviewsQueries.getReviews((error, reviews) => { if (error) { res.status(500).render('common/error', { error, }) } albumsQueries.getAlbums((error, albums) => { if (error) { res.status(500).render('common/error', { error, }) } res.render('index/index', { albums, reviews, userSessionID, userSession, }) }) }) } const userSessionID = null const userSession = null reviewsQueries.getReviews((error, reviews) => { if (error) { res.status(500).render('common/error', { error, }) } albumsQueries.getAlbums((error, albums) => { if (error) { res.status(500).render('common/error', { error, }) } res.render('index/index', { albums, reviews, userSessionID, userSession, }) }) }) }) router.get('/signup', (req, res) => { if (req.session.user) { const userSessionID = req.session.user[0].id const userSession = req.session.user[0] res.render('index/signup', { userSessionID, userSession, }) } const userSessionID = null const userSession = null res.render('index/signup', { userSessionID, userSession, }) }) router.post('/signup', (req, res) => { const accountInfo = req.body const dateToday = new Date() const dateJoined = getSimpleDate(dateToday) usersQueries.getUsersByEmail(accountInfo.email, (error, userEmailInfo) => { if (error) { return res.status(500).render('common/error', { error, }) } else if (userEmailInfo.length > 0) { return res.status(401).render('common/error', { error: { message: 'Email address already exists', }, }) } usersQueries.createUser(accountInfo, dateJoined, (error, accountNew) => { if (error) { return res.status(500).render('common/error', { error, }) } return res.redirect(`/users/${accountNew[0].id}`) }) }) }) router.get('/signin', (req, res) => { if (req.session.user) { const userSessionID = req.session.user[0].id const userSession = req.session.user[0] res.render('index/signin', { userSessionID, userSession, }) } const userSessionID = null const userSession = null res.render('index/signin', { userSessionID, userSession, }) }) router.post('/signin', (req, res) => { const loginEmail = req.body.email const loginPassword = req.body.password usersQueries.getUsersByEmail(loginEmail, (error, userEmailInfo) => { if (error) { return res.status(500).render('common/error', { error, }) } else if (userEmailInfo[0] !== undefined) { if (loginPassword !== userEmailInfo[0].password) { return res.status(401).render('common/error', { error: { message: 'Username and password do not match', }, }) } console.log('Logged in') req.session.user = userEmailInfo req.session.save() return res.redirect(`/users/${userEmailInfo[0].id}`) } return res.status(401).render('common/error', { error: { message: 'Username and password do not match', }, }) }) }) router.get('/signout', (req, res) => { req.session.destroy() res.clearCookie('userInformation') res.redirect('/') }) module.exports = router
hhhhhaaaa/phase-4-challenge
src/server/routes/index.js
JavaScript
mit
4,027
# Abstract model class Abstract < ActiveRecordShared belongs_to :study_subject, :counter_cache => true with_options :class_name => 'User', :primary_key => 'uid' do |u| u.belongs_to :entry_1_by, :foreign_key => 'entry_1_by_uid' u.belongs_to :entry_2_by, :foreign_key => 'entry_2_by_uid' u.belongs_to :merged_by, :foreign_key => 'merged_by_uid' end include AbstractValidations attr_protected :study_subject_id, :study_subject attr_protected :entry_1_by_uid attr_protected :entry_2_by_uid attr_protected :merged_by_uid attr_accessor :current_user attr_accessor :weight_units, :height_units attr_accessor :merging # flag to be used to skip 2 abstract limitation # The :on => :create doesn't seem to work as described # validate_on_create is technically deprecated, but still works validate_on_create :subject_has_less_than_three_abstracts #, :on => :create validate_on_create :subject_has_no_merged_abstract #, :on => :create before_create :set_user after_create :delete_unmerged before_save :convert_height_to_cm before_save :convert_weight_to_kg before_save :set_days_since_fields def self.fields # db: db field name # human: humanized field @@fields ||= YAML::load( ERB.new( IO.read( File.join(File.dirname(__FILE__),'../../config/abstract_fields.yml') )).result) end def fields Abstract.fields end def self.db_fields # @db_fields ||= fields.collect{|f|f[:db]} Abstract.fields.collect{|f|f[:db]} end def db_fields Abstract.db_fields end def comparable_attributes HashWithIndifferentAccess[attributes.select {|k,v| db_fields.include?(k)}] end def is_the_same_as?(another_abstract) self.diff(another_abstract).blank? end def diff(another_abstract) a1 = self.comparable_attributes a2 = Abstract.find(another_abstract).comparable_attributes HashWithIndifferentAccess[a1.select{|k,v| a2[k] != v unless( a2[k].blank? && v.blank? ) }] end # include AbstractSearch def self.search(params={}) # TODO stop using this. Now that study subjects and abstracts are in # the same database, this should be simplified. Particularly since # the only searching is really on the study subject and not the abstract. AbstractSearch.new(params).abstracts end def self.sections # :label: Cytogenetics # :controller: CytogeneticsController # :edit: :edit_abstract_cytogenetic_path # :show: :abstract_cytogenetic_path @@sections ||= YAML::load(ERB.new( IO.read( File.join(File.dirname(__FILE__),'../../config/abstract_sections.yml') )).result) end def merged? !merged_by_uid.blank? end protected def set_days_since_fields # must explicitly convert these DateTimes to Date so that the # difference is in days and not seconds # I really only need to do this if something changes, # but for now, just do it and make sure that # it is tested. Optimize and refactor later. unless diagnosed_on.nil? self.response_day_7_days_since_diagnosis = ( response_report_on_day_7.to_date - diagnosed_on.to_date ) unless response_report_on_day_7.nil? self.response_day_14_days_since_diagnosis = ( response_report_on_day_14.to_date - diagnosed_on.to_date ) unless response_report_on_day_14.nil? self.response_day_28_days_since_diagnosis = ( response_report_on_day_28.to_date - diagnosed_on.to_date ) unless response_report_on_day_28.nil? end unless treatment_began_on.nil? self.response_day_7_days_since_treatment_began = ( response_report_on_day_7.to_date - treatment_began_on.to_date ) unless response_report_on_day_7.nil? self.response_day_14_days_since_treatment_began = ( response_report_on_day_14.to_date - treatment_began_on.to_date ) unless response_report_on_day_14.nil? self.response_day_28_days_since_treatment_began = ( response_report_on_day_28.to_date - treatment_began_on.to_date ) unless response_report_on_day_28.nil? end end def convert_height_to_cm if( !height_units.nil? && height_units.match(/in/i) ) self.height_units = nil self.height_at_diagnosis *= 2.54 end end def convert_weight_to_kg if( !weight_units.nil? && weight_units.match(/lb/i) ) self.weight_units = nil self.weight_at_diagnosis /= 2.2046 end end # Set user if given def set_user if study_subject # because it is possible to create the first, then the second # and then delete the first, and create another, first and # second kinda lose their meaning until the merge, so set them # both as the same until the merge case study_subject.abstracts_count when 0 self.entry_1_by_uid = current_user.try(:uid)||0 self.entry_2_by_uid = current_user.try(:uid)||0 when 1 self.entry_1_by_uid = current_user.try(:uid)||0 self.entry_2_by_uid = current_user.try(:uid)||0 when 2 abs = study_subject.abstracts # compact just in case a nil crept in self.entry_1_by_uid = [abs[0].entry_1_by_uid,abs[0].entry_2_by_uid].compact.first self.entry_2_by_uid = [abs[1].entry_1_by_uid,abs[1].entry_2_by_uid].compact.first self.merged_by_uid = current_user.try(:uid)||0 end end end def delete_unmerged if study_subject and !merged_by_uid.blank? # use delete and not destroy to preserve the abstracts_count study_subject.unmerged_abstracts.each{|a|a.delete} end end def subject_has_less_than_three_abstracts # because this abstract hasn't been created yet, we're comparing to 2, not 3 if study_subject and study_subject.abstracts_count >= 2 errors.add(:study_subject_id,"Study Subject can only have 2 abstracts." ) unless merging end end def subject_has_no_merged_abstract if study_subject and study_subject.merged_abstract errors.add(:study_subject_id,"Study Subject already has a merged abstract." ) end end end
ccls/ccls_engine
app/models/abstract.rb
Ruby
mit
5,798
package com.tehreh1uneh.cloudstorage.common.messages.files; import com.tehreh1uneh.cloudstorage.common.messages.base.Message; import com.tehreh1uneh.cloudstorage.common.messages.base.MessageType; import java.io.File; import java.util.ArrayList; public class FilesListResponse extends Message { private final ArrayList<File> filesList; private final boolean root; public FilesListResponse(ArrayList<File> filesList, boolean root) { super(MessageType.FILES_LIST_RESPONSE); this.filesList = filesList; this.root = root; } public boolean isRoot() { return root; } public ArrayList<File> getFilesList() { return filesList; } }
tehreh1uneh/CloudStorage
common/src/main/java/com/tehreh1uneh/cloudstorage/common/messages/files/FilesListResponse.java
Java
mit
701
class PagesController < ApplicationController def home @emptyphoto = Photo.new @top5 = Photo.popular end end
jannewaren/toukoaalto_generator
app/controllers/pages_controller.rb
Ruby
mit
126
require "active_record" require "authem/token" module Authem class Session < ::ActiveRecord::Base self.table_name = :authem_sessions belongs_to :subject, polymorphic: true before_create do self.token ||= Authem::Token.generate self.ttl ||= 30.days self.expires_at ||= ttl_from_now end class << self def by_subject(record) where(subject_type: record.class.name, subject_id: record.id) end def active where(arel_table[:expires_at].gteq(Time.zone.now)) end def expired where(arel_table[:expires_at].lt(Time.zone.now)) end end def refresh self.expires_at = ttl_from_now save! end private def ttl_from_now ttl.to_i.from_now end end end
rwz/authem2
lib/authem/session.rb
Ruby
mit
784
require 'rails_helper' include OmniauthHelpers describe Users::SignIn do describe '#call' do it 'returns object with user_id and organisation_id' do auth = create_auth sign_in = Users::SignIn.new(auth: auth) membership = sign_in.call expect(membership.user_id).to eq(User.first.id) expect(membership.organisation_id).to eq(Organisation.first.id) end it 'adds user to the organisation' do auth = create_auth sign_in = Users::SignIn.new(auth: auth) sign_in.call expect(Organisation.first.users).to include(User.first) end it "updates user's email when it's different from one in the database" do new_email = 'different@email.com' auth = create_auth(email: new_email) user = create(:user, email: 'some@email.com', provider: auth['provider'], uid: auth['uid']) sign_in = Users::SignIn.new(auth: auth) sign_in.call expect(user.reload.email).to eq(new_email) end it 'saves authenitcation token when organisation is created' do token = 'some_token' auth = create_auth(token: token) sign_in = Users::SignIn.new(auth: auth) sign_in.call expect(Organisation.first.token).to eq(token) end it 'saves user as admin if is_admin is true' do auth = create_auth(is_admin: true) sign_in = Users::SignIn.new(auth: auth) sign_in.call expect(User.first.admin).to eq true end it 'does not save user as admin if is_admin is false' do auth = create_auth(is_admin: false) sign_in = Users::SignIn.new(auth: auth) sign_in.call expect(User.first.admin).to eq false end end end
netguru/props
spec/services/sign_in_spec.rb
Ruby
mit
1,728
using System; using System.IO; using System.IO.Abstractions; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using NSubstitute; using PactNet.Mocks.MockHttpService; using PactNet.Mocks.MockHttpService.Models; using PactNet.Mocks.MockHttpService.Validators; using PactNet.Models; using PactNet.Tests.Fakes; using Xunit; using Xunit.Sdk; namespace PactNet.Tests { public class PactVerifierTests { private Tuple<bool, IHttpRequestSender> _providerServiceValidatorFactoryCallInfo; private IFileSystem _mockFileSystem; private IProviderServiceValidator _mockProviderServiceValidator; private FakeHttpMessageHandler _fakeHttpMessageHandler; private IPactVerifier GetSubject() { _providerServiceValidatorFactoryCallInfo = null; _mockFileSystem = Substitute.For<IFileSystem>(); _mockProviderServiceValidator = Substitute.For<IProviderServiceValidator>(); _fakeHttpMessageHandler = new FakeHttpMessageHandler(); return new PactVerifier(() => {}, () => {}, _mockFileSystem, (httpRequestSender, reporter, config) => { _providerServiceValidatorFactoryCallInfo = new Tuple<bool, IHttpRequestSender>(true, httpRequestSender); return _mockProviderServiceValidator; }, new HttpClient(_fakeHttpMessageHandler), null); } [Fact] public void ProviderState_WhenCalledWithSetUpAndTearDown_SetsProviderStateWithSetUpAndTearDownActions() { const string providerState = "There is an event with id 1234 in the database"; Action providerStateSetUpAction = () => { }; Action providerStateTearDownAction = () => { }; var pactVerifier = (PactVerifier)GetSubject(); pactVerifier .ProviderState(providerState, providerStateSetUpAction, providerStateTearDownAction); var providerStateItem = pactVerifier.ProviderStates.Find(providerState); Assert.Equal(providerStateSetUpAction, providerStateItem.SetUp); Assert.Equal(providerStateTearDownAction, providerStateItem.TearDown); } [Fact] public void ProviderState_WhenCalledWithNullProviderState_ThrowsArgumentException() { var pactVerifier = GetSubject(); Assert.Throws<ArgumentException>(() => pactVerifier .ProviderState(null)); } [Fact] public void ProviderState_WhenCalledWithEmptyProviderState_ThrowsArgumentException() { var pactVerifier = GetSubject(); Assert.Throws<ArgumentException>(() => pactVerifier .ProviderState(String.Empty)); } [Fact] public void ServiceProvider_WhenCalledWithNullProviderName_ThrowsArgumentException() { var pactVerifier = GetSubject(); Assert.Throws<ArgumentException>(() => pactVerifier.ServiceProvider(null, new HttpClient())); } [Fact] public void ServiceProvider_WhenCalledWithEmptyProviderName_ThrowsArgumentException() { var pactVerifier = GetSubject(); Assert.Throws<ArgumentException>(() => pactVerifier.ServiceProvider(String.Empty, new HttpClient())); } [Fact] public void ServiceProvider_WhenCalledWithAnAlreadySetProviderName_ThrowsArgumentException() { const string providerName = "My API"; var pactVerifier = GetSubject(); pactVerifier.ServiceProvider(providerName, new HttpClient()); Assert.Throws<ArgumentException>(() => pactVerifier.ServiceProvider(providerName, new HttpClient())); } [Fact] public void ServiceProviderOverload_WhenCalledWithAnAlreadySetProviderName_ThrowsArgumentException() { const string providerName = "My API"; var pactVerifier = GetSubject(); pactVerifier.ServiceProvider(providerName, request => null); Assert.Throws<ArgumentException>(() => pactVerifier.ServiceProvider(providerName, request => null)); } [Fact] public void ServiceProvider_WhenCalledWithNullHttpClient_ThrowsArgumentException() { var pactVerifier = GetSubject(); Assert.Throws<ArgumentException>(() => pactVerifier.ServiceProvider("Event API", httpClient: null)); } [Fact] public void ServiceProvider_WhenCalledWithProviderName_SetsProviderName() { const string providerName = "Event API"; var pactVerifier = GetSubject(); pactVerifier.ServiceProvider(providerName, new HttpClient()); Assert.Equal(providerName, ((PactVerifier)pactVerifier).ProviderName); } [Fact] public void ServiceProvider_WhenCalledWithHttpClient_HttpClientRequestSenderIsPassedIntoProviderServiceValidatorFactoryWhenVerifyIsCalled() { var httpClient = new HttpClient(); var pactVerifier = GetSubject(); pactVerifier.ServiceProvider("Event API", httpClient); pactVerifier .HonoursPactWith("My client") .PactUri("../../../Consumer.Tests/pacts/my_client-event_api.json") .Verify(); Assert.True(_providerServiceValidatorFactoryCallInfo.Item1, "_providerServiceValidatorFactory was called"); Assert.IsType(typeof(HttpClientRequestSender), _providerServiceValidatorFactoryCallInfo.Item2); //was called with type } [Fact] public void ServiceProvider_WhenCalledWithNullProviderNameAndCustomRequestSender_ThrowsArgumentException() { var pactVerifier = GetSubject(); Assert.Throws<ArgumentException>(() => pactVerifier.ServiceProvider(null, request => new ProviderServiceResponse())); } [Fact] public void ServiceProvider_WhenCalledWithNullRequestSender_ThrowsArgumentException() { var pactVerifier = GetSubject(); Assert.Throws<ArgumentException>(() => pactVerifier.ServiceProvider("Event API", (Func<ProviderServiceRequest, ProviderServiceResponse>) null)); } [Fact] public void ServiceProvider_WhenCalledWithCustomRequestSender_CustomRequestSenderIsPassedIntoProviderServiceValidatorFactoryWhenVerifyIsCalled() { var pactVerifier = GetSubject(); pactVerifier.ServiceProvider("Event API", request => new ProviderServiceResponse()); pactVerifier .HonoursPactWith("My client") .PactUri("../../../Consumer.Tests/pacts/my_client-event_api.json") .Verify(); Assert.True(_providerServiceValidatorFactoryCallInfo.Item1, "_providerServiceValidatorFactory was called"); Assert.IsType(typeof(CustomRequestSender), _providerServiceValidatorFactoryCallInfo.Item2); //was called with type } [Fact] public void HonoursPactWith_WhenCalledWithNullConsumerName_ThrowsArgumentException() { var pactVerifier = GetSubject(); Assert.Throws<ArgumentException>(() => pactVerifier.HonoursPactWith(null)); } [Fact] public void HonoursPactWith_WhenCalledWithEmptyConsumerName_ThrowsArgumentException() { var pactVerifier = GetSubject(); Assert.Throws<ArgumentException>(() => pactVerifier.HonoursPactWith(String.Empty)); } [Fact] public void HonoursPactWith_WhenCalledWithAnAlreadySetConsumerName_ThrowsArgumentException() { const string consumerName = "My Consumer"; var pactVerifier = GetSubject(); pactVerifier.HonoursPactWith(consumerName); Assert.Throws<ArgumentException>(() => pactVerifier.HonoursPactWith(consumerName)); } [Fact] public void HonoursPactWith_WhenCalledWithConsumerName_SetsConsumerName() { const string consumerName = "My Client"; var pactVerifier = GetSubject(); pactVerifier.HonoursPactWith(consumerName); Assert.Equal(consumerName, ((PactVerifier)pactVerifier).ConsumerName); } [Fact] public void PactUri_WhenCalledWithNullUri_ThrowsArgumentException() { var pactVerifier = GetSubject(); Assert.Throws<ArgumentException>(() => pactVerifier.PactUri(null)); } [Fact] public void PactUri_WhenCalledWithEmptyUri_ThrowsArgumentException() { var pactVerifier = GetSubject(); Assert.Throws<ArgumentException>(() => pactVerifier.PactUri(String.Empty)); } [Fact] public void PactUri_WhenCalledWithUri_SetsPactFileUri() { const string pactFileUri = "../../../Consumer.Tests/pacts/my_client-event_api.json"; var pactVerifier = GetSubject(); pactVerifier.PactUri(pactFileUri); Assert.Equal(pactFileUri, ((PactVerifier)pactVerifier).PactFileUri); } [Fact] public void Verify_WhenHttpRequestSenderIsNull_ThrowsInvalidOperationException() { var pactVerifier = GetSubject(); pactVerifier.PactUri("../../../Consumer.Tests/pacts/my_client-event_api.json"); Assert.Throws<InvalidOperationException>(() => pactVerifier.Verify()); } [Fact] public void Verify_WhenPactFileUriIsNull_ThrowsInvalidOperationException() { var pactVerifier = GetSubject(); pactVerifier.ServiceProvider("Event API", new HttpClient()); Assert.Throws<InvalidOperationException>(() => pactVerifier.Verify()); } [Fact] public void Verify_WithFileSystemPactFileUri_CallsFileReadAllText() { var serviceProvider = "Event API"; var serviceConsumer = "My client"; var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json"; var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }"; var pactVerifier = GetSubject(); _mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson); pactVerifier .ServiceProvider(serviceProvider, new HttpClient()) .HonoursPactWith(serviceConsumer) .PactUri(pactUri); pactVerifier.Verify(); _mockFileSystem.File.Received(1).ReadAllText(pactUri); } [Fact] public void Verify_WithHttpPactFileUri_CallsHttpClientWithJsonGetRequest() { var serviceProvider = "Event API"; var serviceConsumer = "My client"; var pactUri = "http://yourpactserver.com/getlatestpactfile"; var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }"; var pactVerifier = GetSubject(); _fakeHttpMessageHandler.Response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(pactFileJson, Encoding.UTF8, "application/json") }; pactVerifier .ServiceProvider(serviceProvider, new HttpClient()) .HonoursPactWith(serviceConsumer) .PactUri(pactUri); pactVerifier.Verify(); Assert.Equal(HttpMethod.Get, _fakeHttpMessageHandler.RequestsRecieved.Single().Method); Assert.Equal("application/json", _fakeHttpMessageHandler.RequestsRecieved.Single().Headers.Single(x => x.Key == "Accept").Value.Single()); } [Fact] public void Verify_WithHttpsPactFileUri_CallsHttpClientWithJsonGetRequest() { var serviceProvider = "Event API"; var serviceConsumer = "My client"; var pactUri = "https://yourpactserver.com/getlatestpactfile"; var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }"; var pactVerifier = GetSubject(); _fakeHttpMessageHandler.Response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(pactFileJson, Encoding.UTF8, "application/json") }; pactVerifier .ServiceProvider(serviceProvider, new HttpClient()) .HonoursPactWith(serviceConsumer) .PactUri(pactUri); pactVerifier.Verify(); Assert.Equal(HttpMethod.Get, _fakeHttpMessageHandler.RequestsRecieved.Single().Method); Assert.Equal("application/json", _fakeHttpMessageHandler.RequestsRecieved.Single().Headers.Single(x => x.Key == "Accept").Value.Single()); } [Fact] public void Verify_WithHttpsPactFileUriAndBasicAuthUriOptions_CallsHttpClientWithJsonGetRequestAndBasicAuthorizationHeader() { var serviceProvider = "Event API"; var serviceConsumer = "My client"; var pactUri = "https://yourpactserver.com/getlatestpactfile"; var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }"; var options = new PactUriOptions("someuser", "somepassword"); var pactVerifier = GetSubject(); _fakeHttpMessageHandler.Response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(pactFileJson, Encoding.UTF8, "application/json") }; pactVerifier .ServiceProvider(serviceProvider, new HttpClient()) .HonoursPactWith(serviceConsumer) .PactUri(pactUri, options); pactVerifier.Verify(); Assert.Equal(HttpMethod.Get, _fakeHttpMessageHandler.RequestsRecieved.Single().Method); Assert.Equal("application/json", _fakeHttpMessageHandler.RequestsRecieved.Single().Headers.Single(x => x.Key == "Accept").Value.Single()); Assert.Equal(_fakeHttpMessageHandler.RequestsRecieved.Single().Headers.Authorization.Scheme, options.AuthorizationScheme); Assert.Equal(_fakeHttpMessageHandler.RequestsRecieved.Single().Headers.Authorization.Parameter, options.AuthorizationValue); } [Fact] public void Verify_WithFileUriAndWhenFileDoesNotExistOnFileSystem_ThrowsInvalidOperationException() { var serviceProvider = "Event API"; var serviceConsumer = "My client"; var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json"; var pactVerifier = GetSubject(); _mockFileSystem.File.ReadAllText(pactUri).Returns(x => { throw new FileNotFoundException(); }); pactVerifier .ServiceProvider(serviceProvider, new HttpClient()) .HonoursPactWith(serviceConsumer) .PactUri(pactUri); Assert.Throws<InvalidOperationException>(() => pactVerifier.Verify()); _mockFileSystem.File.Received(1).ReadAllText(pactUri); } [Fact] public void Verify_WithHttpUriAndNonSuccessfulStatusCodeIsReturned_ThrowsInvalidOperationException() { var serviceProvider = "Event API"; var serviceConsumer = "My client"; var pactUri = "http://yourpactserver.com/getlatestpactfile"; var pactVerifier = GetSubject(); _fakeHttpMessageHandler.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); pactVerifier .ServiceProvider(serviceProvider, new HttpClient()) .HonoursPactWith(serviceConsumer) .PactUri(pactUri); Assert.Throws<InvalidOperationException>(() => pactVerifier.Verify()); Assert.Equal(HttpMethod.Get, _fakeHttpMessageHandler.RequestsRecieved.Single().Method); } [Fact] public void Verify_WhenPactFileWithNoInteractionsExistOnFileSystem_CallsPactProviderValidator() { var serviceProvider = "Event API"; var serviceConsumer = "My client"; var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json"; var pactFileJson = "{ \"provider\": { \"name\": \"" + serviceProvider + "\" }, \"consumer\": { \"name\": \"" + serviceConsumer + "\" }, \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }"; var httpClient = new HttpClient(); var pactVerifier = GetSubject(); _mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson); pactVerifier .ServiceProvider(serviceProvider, httpClient) .HonoursPactWith(serviceConsumer) .PactUri(pactUri); pactVerifier.Verify(); _mockFileSystem.File.Received(1).ReadAllText(pactUri); _mockProviderServiceValidator.Received(1).Validate(Arg.Any<ProviderServicePactFile>(), Arg.Any<ProviderStates>()); } [Fact] public void Verify_WithNoProviderDescriptionOrProviderStateSupplied_CallsProviderServiceValidatorWithAll3Interactions() { var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json"; var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }"; var httpClient = new HttpClient(); var pactVerifier = GetSubject(); _mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson); pactVerifier .ProviderState("My Provider State") .ProviderState("My Provider State 2"); pactVerifier.ServiceProvider("Event API", httpClient) .HonoursPactWith("My client") .PactUri(pactUri); pactVerifier.Verify(); _mockProviderServiceValidator.Received(1).Validate( Arg.Is<ProviderServicePactFile>(x => x.Interactions.Count() == 3), Arg.Any<ProviderStates>()); } [Fact] public void Verify_WithDescription_CallsProviderServiceValidatorWith2FilteredInteractions() { var description = "My Description"; var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json"; var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }"; var httpClient = new HttpClient(); var pactVerifier = GetSubject(); _mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson); pactVerifier .ProviderState("My Provider State") .ProviderState("My Provider State 2"); pactVerifier.ServiceProvider("Event API", httpClient) .HonoursPactWith("My client") .PactUri(pactUri); pactVerifier.Verify(description: description); _mockProviderServiceValidator.Received(1).Validate( Arg.Is<ProviderServicePactFile>(x => x.Interactions.Count() == 2 && x.Interactions.All(i => i.Description.Equals(description))), Arg.Any<ProviderStates>()); } [Fact] public void Verify_WithProviderState_CallsProviderServiceValidatorWith2FilteredInteractions() { var providerState = "My Provider State"; var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json"; var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }"; var httpClient = new HttpClient(); var pactVerifier = GetSubject(); _mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson); pactVerifier .ProviderState("My Provider State") .ProviderState("My Provider State 2"); pactVerifier.ServiceProvider("Event API", httpClient) .HonoursPactWith("My client") .PactUri(pactUri); pactVerifier.Verify(providerState: providerState); _mockProviderServiceValidator.Received(1).Validate( Arg.Is<ProviderServicePactFile>(x => x.Interactions.Count() == 2 && x.Interactions.All(i => i.ProviderState.Equals(providerState))), Arg.Any<ProviderStates>()); } [Fact] public void Verify_WithDescriptionAndProviderState_CallsProviderServiceValidatorWith1FilteredInteractions() { var description = "My Description"; var providerState = "My Provider State"; var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json"; var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }"; var httpClient = new HttpClient(); var pactVerifier = GetSubject(); _mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson); pactVerifier .ProviderState("My Provider State") .ProviderState("My Provider State 2"); pactVerifier.ServiceProvider("Event API", httpClient) .HonoursPactWith("My client") .PactUri(pactUri); pactVerifier.Verify(description: description, providerState: providerState); _mockProviderServiceValidator.Received(1).Validate( Arg.Is<ProviderServicePactFile>(x => x.Interactions.Count() == 1 && x.Interactions.All(i => i.ProviderState.Equals(providerState) && i.Description.Equals(description))), Arg.Any<ProviderStates>()); } [Fact] public void Verify_WithDescriptionThatYieldsNoInteractions_ThrowsArgumentException() { var description = "Description that does not match an interaction"; var pactUri = "../../../Consumer.Tests/pacts/my_client-event_api.json"; var pactFileJson = "{ \"provider\": { \"name\": \"Event API\" }, \"consumer\": { \"name\": \"My client\" }, \"interactions\": [{ \"description\": \"My Description\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description 2\", \"provider_state\": \"My Provider State\" }, { \"description\": \"My Description\", \"provider_state\": \"My Provider State 2\" }], \"metadata\": { \"pactSpecificationVersion\": \"1.0.0\" } }"; var httpClient = new HttpClient(); var pactVerifier = GetSubject(); _mockFileSystem.File.ReadAllText(pactUri).Returns(pactFileJson); pactVerifier .ProviderState("My Provider State") .ProviderState("My Provider State 2"); pactVerifier.ServiceProvider("Event API", httpClient) .HonoursPactWith("My client") .PactUri(pactUri); Assert.Throws<ArgumentException>(() => pactVerifier.Verify(description: description)); _mockProviderServiceValidator.DidNotReceive().Validate( Arg.Any<ProviderServicePactFile>(), Arg.Any<ProviderStates>()); } [Fact] public void Verify_WithProviderStateSet_CallsProviderServiceValidatorWithProviderState() { var httpClient = new HttpClient(); var pactVerifier = GetSubject(); _mockFileSystem.File.ReadAllText(Arg.Any<string>()).Returns("{}"); pactVerifier .ProviderState("My Provider State") .ProviderState("My Provider State 2"); pactVerifier.ServiceProvider("Event API", httpClient) .HonoursPactWith("My client") .PactUri("/test.json"); pactVerifier.Verify(); _mockProviderServiceValidator.Received(1).Validate( Arg.Any<ProviderServicePactFile>(), (pactVerifier as PactVerifier).ProviderStates); } } }
mvdbuuse/pact-net
PactNet.Tests/PactVerifierTests.cs
C#
mit
27,525
// Karma configuration // Generated on Thu Jul 30 2015 17:38:26 GMT-0700 (PDT) // we try our best... let browsers; switch (process.platform) { case 'darwin': // ensured by the npm module ... but may not work on non-consumer // oses. process.env.CHROME_BIN = require('puppeteer').executablePath(); browsers = ['ChromeHeadless']; break; case 'linux': // better have it installed there! browsers = ['ChromiumNoSandbox']; process.env.CHROME_BIN = '/usr/bin/chromium-browser'; break; default: throw new Error(`Unsupported platform: ${process.platform}`); } module.exports = function (config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '../..', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine', 'requirejs'], // list of Karma plugins to use // This is someone redundant with what's in package.json, // but I like it to be explicit here. plugins: [ 'karma-jasmine', 'karma-chrome-launcher', 'karma-coverage', 'karma-requirejs' ], // list of files / patterns to load in the browser // NB: paths are relative to the root of the project, which is // set in the basePath property above. files: [ // All of the AMD modules in the hub. { pattern: 'build/dist/client/modules/**/*.js', included: false }, // {pattern: 'build/client/bower_components/**/*.js', included: false}, // Our test specs { pattern: 'test/unit-tests/specs/**/*.js', included: false }, // Spot pickup the config files // { pattern: 'build/build/client/modules/config/*.yml', included: false }, // { pattern: 'build/build/client/modules/config/*.json', included: false }, // { pattern: 'build/build/client/modules/deploy/*.json', included: false }, 'test/unit-tests/setup.js', ], // list of files to exclude exclude: [ '**/*.swp' ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor // Note that we exclude all of the external modules (bower_components). // TODO: We may want to find a way to evaluate dependency test coverage at some point. preprocessors: { 'build/dist/client/modules/!(plugins)/**/*.js': ['coverage'] // 'build/build/client/modules/**/*.js': ['coverage'] }, // TODO: we should put this somewhere else? coverageReporter: { dir: 'build/build-test-coverage/', reporters: [ { type: 'html', subdir: 'html' }, { type: 'lcov', subdir: 'lcov' } ] }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress', 'coverage'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher // browsers: ['PhantomJS'], browsers, customLaunchers: { ChromiumNoSandbox: { base: 'ChromiumHeadless', flags: ['--no-sandbox', '--headless', '--disable-gpu', '--disable-translate', '--disable-extensions'] } }, // browsers: ['ChromeHeadless'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true }); };
kbase/kbase-ui
test/unit-tests/karma.conf.js
JavaScript
mit
4,283
<?php /* * This file is part of the TraitorBundle, an RunOpenCode project. * * (c) 2017 RunOpenCode * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace RunOpenCode\Bundle\Traitor\Traits; use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** * Class EventDispatcherAwareTrait * * @package RunOpenCode\Bundle\Traitor\Traits * * @codeCoverageIgnore */ trait EventDispatcherAwareTrait { /** * @var EventDispatcherInterface */ protected $eventDispatcher; public function setEventDispatcher(EventDispatcherInterface $eventDispatcher) { $this->eventDispatcher = $eventDispatcher; } }
RunOpenCode/traitor-bundle
src/RunOpenCode/Bundle/Traitor/Traits/EventDispatcherAwareTrait.php
PHP
mit
734
let path = require('path'); let glob = require('glob'); let fs = require('fs'); let net = require('net'); let webpack = require('webpack'); let HtmlWebpackPlugin = require('html-webpack-plugin'); let ExtractTextPlugin = require('extract-text-webpack-plugin'); let slash = require('slash'); let autoprefixer = require("autoprefixer"); function getPath(projectPath, ...otherPath) { return path.join(projectPath, ...otherPath); } function fixFileLoaderPath(path) { return process.env.NODE_ENV === 'development' ? path : '/' + path; } function addEntry(directory, ext, entries, chunks, entryName) { let entry = path.join(directory, `index.${ext}`); if (fs.existsSync(entry)) { entryName = slash(entryName).replace(/\//g, '_') entries[entryName] = `${entry}?__webpack__`; chunks.push(entryName) } } function buildEntriesAndPlugins(projectPath, userConfig) { let commonChunks = {}; let vendors = []; let plugins = []; (userConfig.vendors || []).forEach((vendor, key) => { let row = vendor.dependencies; if (row instanceof Array) { row.forEach(function (value, key) { row[key] = value.replace(/\[project\]/gi, projectPath); }); } else if (row instanceof String) { row = row.replace(/\[project\]/gi, projectPath); } commonChunks[vendor.name] = row; vendors.push(vendor.name); }); let entries = Object.assign({}, commonChunks); //html webpack plugin glob.sync(getPath(projectPath, 'src', 'app', '**', '*.html')).forEach(function (file) { let fileParser = path.parse(file); let entryName = path.relative(getPath(projectPath, 'src', 'app'), fileParser.dir); let chunks = [...vendors]; addEntry(fileParser.dir, 'js', entries, chunks, entryName); // addEntry(fileParser.dir, 'less', entries, chunks, entryName); plugins.push(new HtmlWebpackPlugin({ template: file, inject: true, chunks: chunks, filename: getPath(projectPath, 'dist', userConfig.pagePath || '', `${entryName}.html`), favicon: path.join(projectPath, 'src', 'assets', 'images', 'favorite.ico') })) }); //common chunks plugin plugins.push(new webpack.optimize.CommonsChunkPlugin({ names: vendors })); return { entries, plugins } } function getStyleLoaders(ext, options, userConfig) { const cssLoaders = { loader: 'css-loader', options: { importLoaders: 1 } }; const postCssLoader = { loader: 'postcss-loader', options: { plugins: [ autoprefixer({ browsers: userConfig.postCss.browsers, add: true, remove: true }) ] } }; return [{ test: new RegExp(`\.${ext}$`), include: [ path.join(options.projectPath, 'src') ], exclude: [ path.join(options.projectPath, 'node_modules'), path.join(options.cliPath, 'node_modules') ], oneOf: [{ issuer: /\.js$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [cssLoaders, { loader: 'sprite-loader' }, postCssLoader].concat(ext === 'css' ? [] : [{ loader: `${ext}-loader` }]) }) }, { issuer: /\.(html|tpl)$/, oneOf: [ { resourceQuery: /inline/, use: [{ loader: 'style-loader' }, cssLoaders, { loader: 'sprite-loader' }, postCssLoader].concat(ext === 'css' ? [] : [{ loader: `${ext}-loader` }]) }, { use: [{ loader: 'file-loader', options: { name: fixFileLoaderPath(`styles/[name]_${ext}.[hash:8].css`) } }, { loader: 'extract-loader' }, cssLoaders, { loader: 'sprite-loader' }, postCssLoader].concat(ext === 'css' ? [] : [{ loader: `${ext}-loader` }]) } ] }] }]; } function getScriptLoaders(options) { let babelLoaderConfig = { loader: 'babel-loader', options: { presets: [ require('babel-preset-react') ] } }; return [{ test: /\.js/, include: [path.join(options.projectPath, 'src')], exclude: [path.join(options.projectPath, 'node_modules'), path.join(options.cliPath, 'node_modules')], oneOf: [{ issuer: /\.(html|tpl)$/, oneOf: [{ resourceQuery: /source/, use: [{ loader: 'file-loader', options: { name: fixFileLoaderPath('scripts/[name].[hash:8].js') } }] }, { use: [{ loader: 'entry-loader', options: { name: fixFileLoaderPath('scripts/[name].[hash:8].js'), projectPath: options.projectPath } }, babelLoaderConfig] }] }, { use: [babelLoaderConfig] }] }, { test: /\.jsx$/, use: [babelLoaderConfig] }]; } function throttle(fn, interval = 300) { let canRun = true; return function () { if (!canRun) return; canRun = false; setTimeout(() => { fn.apply(this, arguments); canRun = true; }, interval); }; } module.exports = { getPath, buildEntriesAndPlugins, getStyleLoaders, getScriptLoaders, fixFileLoaderPath, throttle };
IveChen/saber-cli
build/util.js
JavaScript
mit
6,228
<?php /** * UserFrosting (http://www.userfrosting.com) * * @link https://github.com/userfrosting/UserFrosting * @license https://github.com/userfrosting/UserFrosting/blob/master/licenses/UserFrosting.md (MIT License) */ namespace UserFrosting\Sprinkle\Core\Throttle; /** * ThrottleRule Class * * Represents a request throttling rule. * @author Alex Weissman (https://alexanderweissman.com) */ class ThrottleRule { /** @var string Set to 'ip' for ip-based throttling, 'data' for request-data-based throttling. */ protected $method; /** @var int The amount of time, in seconds, to look back in determining attempts to consider. */ protected $interval; /** * @var int[] A mapping of minimum observation counts (x) to delays (y), in seconds. * Any throttleable event that has occurred more than x times in this rule's interval, * must wait y seconds after the last occurrence before another attempt is permitted. */ protected $delays; /** * Create a new ThrottleRule object. * * @param string $method Set to 'ip' for ip-based throttling, 'data' for request-data-based throttling. * @param int $interval The amount of time, in seconds, to look back in determining attempts to consider. * @param int[] $delays A mapping of minimum observation counts (x) to delays (y), in seconds. */ public function __construct($method, $interval, $delays) { $this->setMethod($method); $this->setInterval($interval); $this->setDelays($delays); } /** * Get the current delay on this rule for a particular number of event counts. * * @param Carbon\Carbon $lastEventTime The timestamp for the last countable event. * @param int $count The total number of events which have occurred in an interval. */ public function getDelay($lastEventTime, $count) { // Zero occurrences always maps to a delay of 0 seconds. if ($count == 0) { return 0; } foreach ($this->delays as $observations => $delay) { // Skip any delay rules for which we haven't met the requisite number of observations if ($count < $observations) { continue; } // If this rule meets the observed number of events, and violates the required delay, then return the remaining time left if ($lastEventTime->diffInSeconds() < $delay) { return $lastEventTime->addSeconds($delay)->diffInSeconds(); } } return 0; } /** * Gets the current mapping of attempts (int) to delays (seconds). * * @return int[] */ public function getDelays() { return $this->delays; } /** * Gets the current throttling interval (seconds). * * @return int */ public function getInterval() { return $this->interval; } /** * Gets the current throttling method ('ip' or 'data'). * * @return string */ public function getMethod() { return $this->method; } /** * Sets the current mapping of attempts (int) to delays (seconds). * * @param int[] A mapping of minimum observation counts (x) to delays (y), in seconds. */ public function setDelays($delays) { // Sort the array by key, from highest to lowest value $this->delays = $delays; krsort($this->delays); return $this; } /** * Sets the current throttling interval (seconds). * * @param int The amount of time, in seconds, to look back in determining attempts to consider. */ public function setInterval($interval) { $this->interval = $interval; return $this; } /** * Sets the current throttling method ('ip' or 'data'). * * @param string Set to 'ip' for ip-based throttling, 'data' for request-data-based throttling. */ public function setMethod($method) { $this->method = $method; return $this; } }
splitt3r/UserFrosting
app/sprinkles/core/src/Throttle/ThrottleRule.php
PHP
mit
4,106
import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; import java.util.List; /** * Created by liuxz on 17-3-19. */ public class Leet54SpiralMatrix { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<>(); int n = matrix.length; if (n == 0){ return res; } int m = matrix[0].length; int left =0; int right = m-1; int up = 0; int down = n-1; while(true){ for(int i = left ; i <= right ; i ++){ res.add(matrix[up][i]); } if (res.size() == m*n){break;} up ++; for (int i = up; i <= down ; i ++){ res.add(matrix[i][right]); } if (res.size() == m*n){break;} right --; for (int i = right; i >= left; i --){ res.add(matrix[down][i]); } if (res.size() == m*n){break;} down -- ; for (int i = down; i >= up ; i --){ res.add(matrix[i][left]); } if (res.size() == m*n){break;} left ++; } return res; } public static void main(String[] args){ Leet54SpiralMatrix xx = new Leet54SpiralMatrix(); int[][] input = new int[][]{ // new int[]{1,2,3}, // new int[]{4,5,6}, // new int[]{7,8,9}, // new int[]{10,11,12} }; System.out.println(xx.spiralOrder(input)); } }
LiuXiaozeeee/OnlineJudge
src/Leet54SpiralMatrix.java
Java
mit
1,600
<?php require_once("support/config.php"); if(!isLoggedIn()){ toLogin(); die(); } if(!AllowUser(array(1))){ redirect("index.php"); } $to_do=""; // var_dump($_GET['id']); // die; if(!empty($_GET['id'])){ $to_do=$con->myQuery("SELECT ev.stat_id,ev.event_stat,ev.atype_id,ev.activity_type,ev.priority_id,ev.priority,ev.location,ev.event_place,ev.description,ev.subjects,DATE(ev.start_date) AS start_date,TIME(ev.start_date) AS start_time,DATE(ev.end_date) AS end_date,TIME(ev.start_date) AS end_time,ev.opp_name,ev.assigned_to,ev.due_date,ev.id FROM vw_calendar ev WHERE ev.is_deleted=0 AND ev.id=?",array($_GET['id']))->fetch(PDO::FETCH_ASSOC); if(empty($to_do)){ redirect("calendar_list.php"); die(); } } $to_do_stat=$con->myQuery("SELECT id,name FROM event_status where type=1 or type=3")->fetchAll(PDO::FETCH_ASSOC); $activity_type=$con->myQuery("SELECT id,name FROM act_types")->fetchAll(PDO::FETCH_ASSOC); $org_name=$con->myQuery("SELECT id,org_name FROM organizations")->fetchAll(PDO::FETCH_ASSOC); $prod=$con->myQuery("SELECT id,product_name,unit_price from products")->fetchAll(PDO::FETCH_ASSOC); $prior=$con->myQuery("SELECT id,name FROM priorities")->fetchAll(PDO::FETCH_ASSOC); $contact=$con->myQuery("SELECT id,CONCAT(fname,' ',lname) as name from contacts")->fetchAll(PDO::FETCH_ASSOC); $user=$con->myQuery("SELECT id,CONCAT(last_name,' ',first_name,' ',middle_name) as name FROM users")->fetchAll(PDO::FETCH_ASSOC); makeHead("Calendar"); ?> <?php require_once("template/header.php"); require_once("template/sidebar.php"); ?> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Create New To Do </h1> </section> <!-- Main content --> <section class="content"> <!-- Main row --> <div class="row"> <div class='col-md-10 col-md-offset-1'> <?php Alert(); ?> <div class="box box-primary"> <div class="box-body"> <div class="row"> <div class='col-sm-12 col-md-8 col-md-offset-1'> <form class='form-horizontal' method='POST' action='save_to_do.php'> <input type='hidden' name='id' value='<?php echo !empty($to_do)?$to_do['id']:""?>'> <!-- <input type='hidden' name='to_do_id' value='<?php echo $to_do['id']?>'> --> <div class='form-group'> <label for="" class="col-sm-4 control-label"> Subject *</label> <div class='col-sm-8'> <input type='text' class='form-control' name='subject' placeholder='Enter Subject Name' value='<?php echo !empty($to_do)?$to_do['subjects']:"" ?>' required> </div> </div> <div class="form-group"> <label for="" class="col-sm-4 control-label">Start Date*</label> <div class="col-sm-8"> <?php $start_date=""; if(!empty($to_do)){ $start_date=$to_do['start_date']; if($start_date=="0000-00-00"){ $start_date=""; } } ?> <input type='date' class='form-control' name='start_date' value='<?php echo $start_date; ?>' required> </div> <label for="" class="col-sm-4 control-label">Time*</label> <div class="col-sm-3"> <input type="time" class="form-control" value='<?php echo !empty($to_do)?$to_do['start_time']:"" ?>' id="until_t" name="start_time" required/> </div> </div> <div class="form-group"> <label for="" class="col-sm-4 control-label">Due Date*</label> <div class="col-sm-8"> <?php $due_date=""; if(!empty($to_do)){ $due_date=$to_do['due_date']; if($due_date=="0000-00-00"){ $due_date=""; } } ?> <input type='date' class='form-control' name='due_date' value='<?php echo $due_date; ?>' required> </div> </div> <div class='form-group'> <label for="" class="col-md-4 control-label">Status*</label> <div class="col-sm-8"> <select class='form-control' name='status' data-placeholder="Select an option" <?php echo!(empty($to_do))?"data-selected='".$to_do['stat_id']."'":NULL ?> required> <?php echo makeOptions($to_do_stat,'Select Contact Name',NULL,'',!(empty($to_do))?$to_do['stat_id']:NULL) ?> </select> </div> </div> <!-- <div class='form-group'> <label class='col-sm-4 control-label' > User *</label> <div class='col-sm-6'> <div class='row'> <div class='col-sm-11'> <select id="disabledSelect" class='form-control' name='assigned_to' data-placeholder="Select a user" <?php echo!(empty($opportunity))?"data-selected='".$opportunity['assigned_to']."'":"data-selected='".$_SESSION[WEBAPP]['user']['id']."'" ?> required> <?php echo makeOptions($user); ?> </select> </div> <?php if($_SESSION[WEBAPP]['user']['user_type']==1): ?> <div class='col-ms-1'> <a href='frm_users.php' class='btn btn-sm btn-success'><span class='fa fa-plus'></span></a> </div> <?php endif; ?> </div> </div> </div> --> <div class='form-group'> <label class='col-sm-4 control-label' > Priority</label> <div class='col-sm-8'> <select class='form-control' name='priority' data-placeholder="Select an option" <?php echo!(empty($to_do))?"data-selected='".$event['priority_id']."'":NULL ?>> <?php echo makeOptions($prior,'Select Contact Name',NULL,'',!(empty($to_do))?$to_do['priority_id']:NULL) ?> </select> </div> </div> <div class='form-group'> <label for="" class="col-sm-4 control-label"> Location</label> <div class='col-sm-8'> <input type='text' class='form-control' name='event_place' placeholder='Enter Location' value='<?php echo !empty($to_do)?$to_do['event_place']:"" ?>'> </div> </div> <div class='form-group'> <label for="" class="col-sm-4 control-label"> Description</label> <div class='col-sm-8'> <textarea class='form-control' placeholder="Enter Description" name='description' value=''><?php echo !empty($to_do)?$to_do['description']:"" ?></textarea> </div> </div> <div class='form-group'> <div class='col-sm-12 col-md-9 col-md-offset-3 '> <a href='calendar_list.php' class='btn btn-default'>Cancel</a> <button type='submit' class='btn btn-brand'> <span class='fa fa-check'></span> Save</button> </div> </div> </form> </div> </div><!-- /.row --> </div><!-- /.box-body --> </div><!-- /.box --> </div> </div><!-- /.row --> </section><!-- /.content --> </div> <script type="text/javascript"> $(function () { $('#ResultTable').DataTable(); }); </script> <?php makeFoot(); ?>
sgtsi-jenny/crmv2
frm_to_do.php
PHP
mit
10,845
import React from 'react'; import { Image, Text, View } from 'react-native'; import Example from '../../shared/example'; const Spacer = () => <View style={{ height: '1rem' }} />; const Heading = ({ children }) => ( <Text accessibilityRole="heading" children={children} style={{ fontSize: '1rem', fontWeight: 'bold', marginBottom: '0.5rem' }} /> ); function Color() { return ( <View> <Heading>color</Heading> <Text style={{ color: 'red' }}>Red color</Text> <Text style={{ color: 'blue' }}>Blue color</Text> </View> ); } function FontFamily() { return ( <View> <Heading>fontFamily</Heading> <Text style={{ fontFamily: 'Cochin' }}>Cochin</Text> <Text style={{ fontFamily: 'Cochin', fontWeight: 'bold' }} > Cochin bold </Text> <Text style={{ fontFamily: 'Helvetica' }}>Helvetica</Text> <Text style={{ fontFamily: 'Helvetica', fontWeight: 'bold' }}>Helvetica bold</Text> <Text style={{ fontFamily: 'Verdana' }}>Verdana</Text> <Text style={{ fontFamily: 'Verdana', fontWeight: 'bold' }} > Verdana bold </Text> </View> ); } function FontSize() { return ( <View> <Heading>fontSize</Heading> <Text style={{ fontSize: 23 }}>Size 23</Text> <Text style={{ fontSize: 8 }}>Size 8</Text> </View> ); } function FontStyle() { return ( <View> <Heading>fontStyle</Heading> <Text style={{ fontStyle: 'normal' }}>Normal text</Text> <Text style={{ fontStyle: 'italic' }}>Italic text</Text> </View> ); } function FontVariant() { return ( <View> <Heading>fontVariant</Heading> <Text style={{ fontVariant: ['small-caps'] }}>Small Caps{'\n'}</Text> <Text style={{ fontVariant: ['oldstyle-nums'] }} > Old Style nums 0123456789{'\n'} </Text> <Text style={{ fontVariant: ['lining-nums'] }} > Lining nums 0123456789{'\n'} </Text> <Text style={{ fontVariant: ['tabular-nums'] }}> Tabular nums{'\n'} 1111{'\n'} 2222{'\n'} </Text> <Text style={{ fontVariant: ['proportional-nums'] }}> Proportional nums{'\n'} 1111{'\n'} 2222{'\n'} </Text> </View> ); } function FontWeight() { return ( <View> <Heading>fontWeight</Heading> <Text style={{ fontSize: 20, fontWeight: '100' }}>Move fast and be ultralight</Text> <Text style={{ fontSize: 20, fontWeight: '200' }}>Move fast and be light</Text> <Text style={{ fontSize: 20, fontWeight: 'normal' }}>Move fast and be normal</Text> <Text style={{ fontSize: 20, fontWeight: 'bold' }}>Move fast and be bold</Text> <Text style={{ fontSize: 20, fontWeight: '900' }}>Move fast and be ultrabold</Text> </View> ); } function LetterSpacing() { return ( <View> <Heading>letterSpacing</Heading> <Text style={{ letterSpacing: 0 }}>letterSpacing = 0</Text> <Text style={{ letterSpacing: 2, marginTop: 5 }}>letterSpacing = 2</Text> <Text style={{ letterSpacing: 9, marginTop: 5 }}>letterSpacing = 9</Text> <View style={{ flexDirection: 'row' }}> <Text style={{ fontSize: 12, letterSpacing: 2, backgroundColor: 'fuchsia', marginTop: 5 }}> With size and background color </Text> </View> <Text style={{ letterSpacing: -1, marginTop: 5 }}>letterSpacing = -1</Text> <Text style={{ letterSpacing: 3, backgroundColor: '#dddddd', marginTop: 5 }}> [letterSpacing = 3] <Text style={{ letterSpacing: 0, backgroundColor: '#bbbbbb' }}> [Nested letterSpacing = 0] </Text> <Text style={{ letterSpacing: 6, backgroundColor: '#eeeeee' }}> [Nested letterSpacing = 6] </Text> </Text> </View> ); } function LineHeight() { return ( <View> <Heading>lineHeight</Heading> <Text style={{ lineHeight: 35 }}> A lot of space should display between the lines of this long passage as they wrap across several lines. A lot of space should display between the lines of this long passage as they wrap across several lines. </Text> </View> ); } function TextAlign() { return ( <View> <Heading>textAlign</Heading> <Text>auto (default) - english LTR</Text> <Text> {'\u0623\u062D\u0628 \u0627\u0644\u0644\u063A\u0629 ' + '\u0627\u0644\u0639\u0631\u0628\u064A\u0629 auto (default) - arabic ' + 'RTL'} </Text> <Text style={{ textAlign: 'left' }}> left left left left left left left left left left left left left left left </Text> <Text style={{ textAlign: 'center' }}> center center center center center center center center center center center </Text> <Text style={{ textAlign: 'right' }}> right right right right right right right right right right right right right </Text> <Text style={{ textAlign: 'justify' }}> justify: this text component{"'"}s contents are laid out with "textAlign: justify" and as you can see all of the lines except the last one span the available width of the parent container. </Text> </View> ); } function TextDecoration() { return ( <View> <Heading>textDecoration</Heading> <Text style={{ textDecorationLine: 'underline', textDecorationStyle: 'solid' }} > Solid underline </Text> <Text style={{ textDecorationLine: 'underline', textDecorationStyle: 'double', textDecorationColor: '#ff0000' }} > Double underline with custom color </Text> <Text style={{ textDecorationLine: 'underline', textDecorationStyle: 'dashed', textDecorationColor: '#9CDC40' }} > Dashed underline with custom color </Text> <Text style={{ textDecorationLine: 'underline', textDecorationStyle: 'dotted', textDecorationColor: 'blue' }} > Dotted underline with custom color </Text> <Text style={{ textDecorationLine: 'none' }}>None textDecoration</Text> <Text style={{ textDecorationLine: 'line-through', textDecorationStyle: 'solid' }} > Solid line-through </Text> <Text style={{ textDecorationLine: 'line-through', textDecorationStyle: 'double', textDecorationColor: '#ff0000' }} > Double line-through with custom color </Text> <Text style={{ textDecorationLine: 'line-through', textDecorationStyle: 'dashed', textDecorationColor: '#9CDC40' }} > Dashed line-through with custom color </Text> <Text style={{ textDecorationLine: 'line-through', textDecorationStyle: 'dotted', textDecorationColor: 'blue' }} > Dotted line-through with custom color </Text> <Text style={{ textDecorationLine: 'underline line-through' }}> Both underline and line-through </Text> </View> ); } function TextShadow() { return ( <View> <Heading>textShadow*</Heading> <Text style={{ fontSize: 20, textShadowOffset: { width: 2, height: 2 }, textShadowRadius: 1, textShadowColor: '#00cccc' }} > Text shadow example </Text> </View> ); } function LineExample({ description, children }) { return ( <View style={{ marginTop: 20 }}> <Text style={{ color: 'gray', marginBottom: 5 }}>{description}</Text> <View style={{ borderWidth: 2, borderColor: 'black', width: 200 }} > {children} </View> </View> ); } export default function TextPage() { return ( <Example title="Text"> <View style={{ maxWidth: 500 }}> <Text> Text wraps across multiple lines by default. Text wraps across multiple lines by default. Text wraps across multiple lines by default. Text wraps across multiple lines by default. </Text> <Spacer /> <Text> (Text inherits styles from parent Text elements, <Text style={{ fontWeight: 'bold' }}> {'\n '} (for example this text is bold <Text style={{ fontSize: 11, color: '#527fe4' }}> {'\n '} (and this text inherits the bold while setting size and color) </Text> {'\n '}) </Text> {'\n'}) </Text> <Spacer /> <Text style={{ opacity: 0.7 }}> (Text opacity <Text> {'\n '} (is inherited <Text style={{ opacity: 0.7 }}> {'\n '} (and accumulated <Text style={{ backgroundColor: '#ffaaaa' }}> {'\n '} (and also applies to the background) </Text> {'\n '}) </Text> {'\n '}) </Text> {'\n'}) </Text> <Spacer /> <Text> This text contains an inline blue view{' '} <View style={{ width: 25, height: 25, backgroundColor: 'steelblue' }} /> and an inline image{' '} <Image source={{ uri: 'http://lorempixel.com/30/11' }} style={{ width: 30, height: 11, resizeMode: 'cover' }} /> . </Text> <Spacer /> <Text> This text contains a view{' '} <View style={{ borderColor: 'red', borderWidth: 1 }}> <Text style={{ borderColor: 'blue', borderWidth: 1 }}>which contains</Text> <Text style={{ borderColor: 'green', borderWidth: 1 }}>another text.</Text> <Text style={{ borderColor: 'yellow', borderWidth: 1 }}> And contains another view <View style={{ borderColor: 'red', borderWidth: 1 }}> <Text style={{ borderColor: 'blue', borderWidth: 1 }}> which contains another text! </Text> </View> </Text> </View>{' '} And then continues as text. </Text> <Text selectable={true}> This text is <Text style={{ fontWeight: 'bold' }}>selectable</Text> if you click-and-hold. </Text> <Text selectable={false}> This text is <Text style={{ fontWeight: 'bold' }}>not selectable</Text> if you click-and-hold. </Text> <View style={{ paddingVertical: 20 }}> <LineExample description="With no line breaks, text is limited to 2 lines."> <Text numberOfLines={2}> { 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } </Text> </LineExample> <LineExample description="With line breaks, text is limited to 2 lines."> <Text numberOfLines={2}> { 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\nExcepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } </Text> </LineExample> <LineExample description="With no line breaks, text is limited to 1 line."> <Text numberOfLines={1}> { 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } </Text> </LineExample> <LineExample description="With line breaks, text is limited to 1 line."> <Text numberOfLines={1}> { 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\nExcepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } </Text> </LineExample> <LineExample description="With very long word, text is limited to 1 line and long word is truncated."> <Text numberOfLines={1}>goal aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</Text> </LineExample> <LineExample description="With space characters within adjacent truncated lines"> <View style={{ display: 'flex', flexDirection: 'row' }}> <Text numberOfLines={1}> <Text>Spaces </Text> <Text>between</Text> <Text> words</Text> </Text> </View> <View style={{ display: 'flex', flexDirection: 'row' }}> <Text>Spaces </Text> <Text>between</Text> <Text> words</Text> </View> </LineExample> </View> <View> <Color /> <Spacer /> <FontFamily /> <Spacer /> <FontSize /> <Spacer /> <FontStyle /> <Spacer /> <FontVariant /> <Spacer /> <FontWeight /> <Spacer /> <LetterSpacing /> <Spacer /> <LineHeight /> <Spacer /> <TextAlign /> <Spacer /> <TextDecoration /> <Spacer /> <TextShadow /> </View> </View> </Example> ); }
necolas/react-native-web
packages/examples/pages/text/index.js
JavaScript
mit
15,012
package org.wycliffeassociates.translationrecorder.project; import android.os.Parcel; import android.os.Parcelable; /** * Created by sarabiaj on 4/17/2017. */ public class TakeInfo implements Parcelable { ProjectSlugs mSlugs; int mChapter; int mStartVerse; int mEndVerse; int mTake; public TakeInfo(ProjectSlugs slugs, int chapter, int startVerse, int endVerse, int take) { mSlugs = slugs; mChapter = chapter; mStartVerse = startVerse; mEndVerse = endVerse; mTake = take; } public TakeInfo(ProjectSlugs slugs, String chapter, String startVerse, String endVerse, String take) { mSlugs = slugs; //If there is only one chapter in the book, set default the chapter to 1 if(chapter != null && !chapter.equals("")) { mChapter = Integer.parseInt(chapter); } else { mChapter = 1; } mStartVerse = Integer.parseInt(startVerse); if(endVerse != null) { mEndVerse = Integer.parseInt(endVerse); } else { mEndVerse = -1; } if(take != null) { mTake = Integer.parseInt(take); } else { mTake = 0; } } public ProjectSlugs getProjectSlugs() { return mSlugs; } public int getChapter() { return mChapter; } public int getStartVerse() { return mStartVerse; } public int getTake() { return mTake; } public int getEndVerse() { //if there is no end verse, there is no verse range, so the end verse is the start verse if(mEndVerse == -1) { return mStartVerse; } return mEndVerse; } // public String getNameWithoutTake() { // if (mSlugs.anthology != null && mSlugs.anthology.compareTo("obs") == 0) { // return mSlugs.language + "_obs_c" + String.format("%02d", mChapter) + "_v" + String.format("%02d", mStartVerse); // } else { // String name; // String end = (mEndVerse != -1 && mStartVerse != mEndVerse) ? String.format("-%02d", mEndVerse) : ""; // if (mSlugs.book.compareTo("psa") == 0 && mChapter != 119) { // name = mSlugs.language + "_" + mSlugs.version + "_b" + String.format("%02d", mSlugs.bookNumber) + "_" + mSlugs.book + "_c" + String.format("%03d", mChapter) + "_v" + String.format("%02d", mStartVerse) + end; // } else if (mSlugs.book.compareTo("psa") == 0) { // end = (mEndVerse != -1) ? String.format("-%03d", mEndVerse) : ""; // name = mSlugs.language + "_" + mSlugs.version + "_b" + String.format("%02d", mSlugs.bookNumber) + "_" + mSlugs.book + "_c" + ProjectFileUtils.chapterIntToString(mSlugs.book, mChapter) + "_v" + String.format("%03d", mStartVerse) + end; // } else { // name = mSlugs.language + "_" + mSlugs.version + "_b" + String.format("%02d", mSlugs.bookNumber) + "_" + mSlugs.book + "_c" + ProjectFileUtils.chapterIntToString(mSlugs.book, mChapter) + "_v" + String.format("%02d", mStartVerse) + end; // } // return name; // } // } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeParcelable(mSlugs, flags); dest.writeInt(mChapter); dest.writeInt(mStartVerse); dest.writeInt(mEndVerse); dest.writeInt(mTake); } public static final Parcelable.Creator<TakeInfo> CREATOR = new Parcelable.Creator<TakeInfo>() { public TakeInfo createFromParcel(Parcel in) { return new TakeInfo(in); } public TakeInfo[] newArray(int size) { return new TakeInfo[size]; } }; public TakeInfo(Parcel in) { mSlugs = in.readParcelable(ProjectSlugs.class.getClassLoader()); mChapter = in.readInt(); mStartVerse = in.readInt(); mEndVerse = in.readInt(); mTake = in.readInt(); } // @Override // public boolean equals(Object takeInfo){ // if(takeInfo == null) { // return false; // } // if(!(takeInfo instanceof TakeInfo)) { // return false; // } else { // return (getProjectSlugs().equals(((TakeInfo) takeInfo).getProjectSlugs()) // && getChapter() == ((TakeInfo) takeInfo).getChapter() // && getStartVerse() == ((TakeInfo) takeInfo).getStartVerse() // && getEndVerse() == ((TakeInfo) takeInfo).getEndVerse() // && getTake() == ((TakeInfo) takeInfo).getTake()); // } // } public boolean equalBaseInfo(TakeInfo takeInfo) { if(takeInfo == null) { return false; } if(!(takeInfo instanceof TakeInfo)) { return false; } else { return (getProjectSlugs().equals(takeInfo.getProjectSlugs()) && getChapter() == takeInfo.getChapter() && getStartVerse() == takeInfo.getStartVerse() && getEndVerse() == takeInfo.getEndVerse()); } } }
WycliffeAssociates/translationRecorder
translationRecorder/app/src/main/java/org/wycliffeassociates/translationrecorder/project/TakeInfo.java
Java
mit
5,206
def ReadLines(filename): content = [] with open(filename) as f: content = [x.rstrip() for x in f.readlines()] return content
aawc/cryptopals
sets/1/challenges/common/read_lines.py
Python
mit
136
const ACCOUNTS = [ 'all', 'default', 'kai-tfsa', 'kai-rrsp', 'kai-spouse-rrsp', 'kai-non-registered', 'kai-charles-schwab', 'crystal-non-registered', 'crystal-tfsa', 'crystal-rrsp', 'crystal-spouse-rrsp' ]; export default ACCOUNTS;
kaiguogit/growfolio
client/src/constants/accounts.js
JavaScript
mit
276
package charlotte.tools; import java.util.Arrays; import java.util.List; public class QueueData<T> { private LinkNode<T> _top; private LinkNode<T> _last; private int _count; public QueueData(T[] entries) { this(Arrays.asList(entries)); } public QueueData(List<T> entries) { this(); for(T entry : entries) { add(entry); } } public QueueData() { _top = new LinkNode<T>(); _last = _top; } public void add(T element) { _last.element = element; _last.next = new LinkNode<T>(); _last = _last.next; _count++; } public T poll() { if(_count <= 0) { return null; } T ret = _top.element; _top = _top.next; _count--; return ret; } public int size() { return _count; } private class LinkNode<U> { public U element; public LinkNode<U> next; } public void clear() { _top = new LinkNode<T>(); _last = _top; _count = 0; } public ValueStore<T> toValueStore() { return new ValueStore<T>() { @Override public T get() { return poll(); } @Override public void set(T element) { add(element); } }; } }
stackprobe/Java
charlotte/tools/QueueData.java
Java
mit
1,092
import React from 'react'; import PropTypes from 'prop-types'; import serialize from 'serialize-javascript'; import filterWithRules from '../../internal/utils/objects/filterWithRules'; import values from '../values'; // Filter the config down to the properties that are allowed to be included // in the HTML response. const clientConfig = filterWithRules( // These are the rules used to filter the config. values.clientConfigFilter, // The config values to filter. values, ); const serializedClientConfig = serialize(clientConfig); /** * A react component that generates a script tag that binds the allowed * values to the window so that config values can be read within the * browser. * * They get bound to window.__CLIENT_CONFIG__ */ function ClientConfig({ addHash }) { return ( <script type="text/javascript" // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: addHash(`window.__CLIENT_CONFIG__=${serializedClientConfig}`), }} /> ); } ClientConfig.propTypes = { addHash: PropTypes.func.isRequired, }; export default ClientConfig;
ueno-llc/starter-kit-universally
config/components/ClientConfig.js
JavaScript
mit
1,126
using Nucleus.Logs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Nucleus.Game { /// <summary> /// Interface for components, status effects, items etc. that /// modify critical hit chance /// </summary> public interface ICritChanceModifier { /// <summary> /// Modify a critical success chance /// </summary> /// <param name="critChance"></param> /// <returns></returns> double ModifyCritChance(double critChance, IActionLog log, EffectContext context); } }
pnjeffries/Nucleus
Nucleus/Nucleus.Game/Components/ICritChanceModifier.cs
C#
mit
617
<?php /** * This file is part of Student-List application. * * @author foobar1643 <foobar76239@gmail.com> * @copyright 2016 foobar1643 * @package Students\Utility * @license https://github.com/foobar1643/student-list/blob/master/LICENSE.md MIT License */ namespace Students\Utility; use Students\Interfaces\ConfigurationInterface; class Configuration implements ConfigurationInterface { /** * Array with configuration values. * * @var array */ protected $config = []; /** * Retains immutability. * This method does nothing. */ public function __set($name, $value) { } /** * Loads configuration from .ini file. * * If $preserveValues equals TRUE, this method will merge any existing * values with the loaded ones. If both configurations have the same string keys, * then the later value for that key will overwrite the previous one. * If, however, the configurations contain numeric keys, the later value will not * overwrite the original value, but will be appended. * * @param string $filename Name of the file to load. * @param bool $preserveValues If true, any existing values will be merged * with loaded ones. If false - any existing values will be overwritten * with the loaded ones. Default value is false. * * @throws \InvalidArgumentException If configuration file is invalid or not found. * @throws \RuntimeException If an error occured while loading the configuration file. * * @return void */ public function loadFromFile($filename, $preserveValues = false) { // Throws an exception if file with a given name does not exist. if(!file_exists($filename)) { throw new InvalidArgumentException("Configuration file '{$filename}' does not exists."); } // Attempts to parse INI file $data = parse_ini_file($filename, true); // Throws an exception if an error occured while parsing INI file. if($data === false) { throw new RuntimeException("Failed to read configuration file '{$filename}'."); } $this->loadFromArray($data, $preserveValues); } /** * Loads configuration from PHP array. * * If $preserveValues equals TRUE, this method will merge any existing * values with the loaded ones. If both configurations have the same string keys, * then the later value for that key will overwrite the previous one. * If, however, the configurations contain numeric keys, the later value will not * overwrite the original value, but will be appended. * * @param array $data Configuration in a form of associative array. * @param bool $preserveValues If true, any existing values will be merged * with loaded ones. If false - any existing values will be overwritten * with the loaded ones. Default value is false. * * @return void */ public function loadFromArray(array $data, $preserveValues = false) { // If preserveValues is set to true and current config is not empty - // merges existing configuration array with the loaded one. $this->config = ($preserveValues === true && !empty($this->config)) ? array_merge($data, $this->config) : $data; } /** * Returns a value for given key. * * @param string $section Case-sensetive section name in the configuration. * @param string $key Case-sensetive key name in the configuration. * * @throws \InvalidArgumentException If given section or key is not in the config. * * @return mixed Value for given key. */ public function getValue($section, $key) { return $this->config[$section][$key]; } /** * Returns an array with section values. * * @param string $section Case-sensetive section name to fetch. * * @throws \InvalidArgumentException If section with a given name is not in the config. * * @return array Associative array with section values. */ public function getSection($section) { if(!$this->hasSection($section)) { throw new \InvalidArgumentException("Can't find section {$section} in the configuration."); } return $this->config[$section]; } /** * Returns all sections with their values in a form of associative array. * * @return array Associative array with all sections and their values. */ public function getAll() { return $this->config; } /** * Checks if a section with given name exists in the config. * * @param string $section Case-sensetive section name to check. * * @return boolean True if section exists, false otherwise. */ public function hasSection($section) { return array_key_exists($section, $this->config); } /** * Checks if a key with given name exists in the config. * * @param string $section Case-sensetive section name that contains the key. * @param string $key Case-sensetive key name to check. * * @return boolean True if key exists, false otherwise. */ public function hasKey($section, $key) { return ($this->hasSection($section) && array_key_exists($key, $this->config[$section])); } }
foobar1643/student-list
src/Utility/Configuration.php
PHP
mit
5,398
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, browserHistory } from 'react-router'; import * as firebase from "firebase"; import './css/index.css'; import PetPage from './pet'; import Welcome from './welcome'; import AddPet from './add-pet'; import MainLayout from './main-layout'; // Initialize Firebase var config = { apiKey: "AIzaSyCy8OwL_E1rrYfutk5vqLygz20RmGW-GBE", authDomain: "petland-4b867.firebaseapp.com", databaseURL: "https://petland-4b867.firebaseio.com", storageBucket: "gs://petland-4b867.appspot.com/", messagingSenderId: "784140166304" }; firebase.initializeApp(config); ReactDOM.render( <Router history={browserHistory}> <Route component={MainLayout}> <Route path="/" component={Welcome} /> <Route path="/pet/:id" component={PetPage} /> <Route path="/add-pet" component={AddPet} /> </Route> </Router>, document.getElementById('root') );
beleidy/Pet-Land
src/index.js
JavaScript
mit
986
// ----------------------------------------------------------------------- // Licensed to The .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ----------------------------------------------------------------------- // This is a generated file. // The generation template has been modified from .NET Runtime implementation using System; using System.Security.Cryptography.Asn1; namespace Kerberos.NET.Entities { public partial class KrbAsRep : KrbKdcRep { /* AS-REP ::= [APPLICATION 11] KDC-REP */ private static readonly Asn1Tag ApplicationTag = new Asn1Tag(TagClass.Application, 11); public override ReadOnlyMemory<byte> EncodeApplication() { return EncodeApplication(ApplicationTag); } public static KrbAsRep DecodeApplication(ReadOnlyMemory<byte> encoded) { AsnReader reader = new AsnReader(encoded, AsnEncodingRules.DER); var sequence = reader.ReadSequence(ApplicationTag); KrbAsRep decoded; Decode(sequence, out decoded); sequence.ThrowIfNotEmpty(); reader.ThrowIfNotEmpty(); return decoded; } } }
SteveSyfuhs/Kerberos.NET
Kerberos.NET/Entities/Krb/KrbAsRep.generated.cs
C#
mit
1,321
package com.dranawhite.mybatis.Service; /** * @author dranawhite 2017/9/30 * @version 1.0 */ public class PersonService { }
dranawhite/test-java
test-framework/test-mybatis/src/main/java/com/dranawhite/mybatis/Service/PersonService.java
Java
mit
129
from wdom.server import start from wdom.document import set_app from wdom.tag import Div, H1, Input class MyElement(Div): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.h1 = H1(parent=self) self.h1.textContent = 'Hello, WDOM' self.input = Input(parent=self) self.input.addEventListener('input', self.update) def update(self, event): self.h1.textContent = event.target.value if __name__ == '__main__': set_app(MyElement()) start()
miyakogi/wdom
docs/guide/samples/wdom2.py
Python
mit
526
#include<iostream> int* f(int* fst, int* lst, int v) { std::cout << "in f function, pointers are copied" << std::endl; std::cout << "&fst == " << &fst << ", &lst == " << &lst << std::endl; std::cout << "fst == " << fst << ", lst == " << lst << std::endl; while(fst != lst && *fst != v) { ++fst; } return fst; } void g(int* p, int*q) { std::cout << "in g function, pointers are copied" << std::endl; std::cout << "&p == " << &p << ", &q == " << &q << std::endl; std::cout << "p == " << p << ", q == " << q << std::endl; int* pp = f(p, q, 10); } int main() { int a[10] {1, 2, 5, 10, 9, 8, 7}; int* p = a; int* q = p+9; std::cout << "initialized pointers" << std::endl; std::cout << "&p == " << &p << ", &q == " << &q << std::endl; std::cout << "p == " << p << ", q == " << q << std::endl; g(p, q); }
sylsaint/cpp_learning
tcpppl/arguments_passing.cc
C++
mit
881
const { ArgumentError } = require('rest-facade'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** * Abstracts interaction with the stats endpoint. */ class StatsManager { /** * @param {object} options The client options. * @param {string} options.baseUrl The URL of the API. * @param {object} [options.headers] Headers to be included in all requests. * @param {object} [options.retry] Retry Policy Config */ constructor(options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide manager options'); } if (options.baseUrl === null || options.baseUrl === undefined) { throw new ArgumentError('Must provide a base URL for the API'); } if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { throw new ArgumentError('The provided base URL is invalid'); } const clientOptions = { errorFormatter: { message: 'message', name: 'error' }, headers: options.headers, query: { repeatParams: false }, }; /** * Provides an abstraction layer for consuming the * {@link https://auth0.com/docs/api/v2#!/Stats Stats endpoint}. * * @type {external:RestClient} */ const auth0RestClient = new Auth0RestClient( `${options.baseUrl}/stats/:type`, clientOptions, options.tokenProvider ); this.resource = new RetryRestClient(auth0RestClient, options.retry); } /** * Get the daily stats. * * @example * var params = { * from: '{YYYYMMDD}', // First day included in the stats. * to: '{YYYYMMDD}' // Last day included in the stats. * }; * * management.stats.getDaily(params, function (err, stats) { * if (err) { * // Handle error. * } * * console.log(stats); * }); * @param {object} params Stats parameters. * @param {string} params.from The first day in YYYYMMDD format. * @param {string} params.to The last day in YYYYMMDD format. * @param {Function} [cb] Callback function. * @returns {Promise|undefined} */ getDaily(params, cb) { params = params || {}; params.type = 'daily'; if (cb && cb instanceof Function) { return this.resource.get(params, cb); } return this.resource.get(params); } /** * Get a the active users count. * * @example * management.stats.getActiveUsersCount(function (err, usersCount) { * if (err) { * // Handle error. * } * * console.log(usersCount); * }); * @param {Function} [cb] Callback function. * @returns {Promise|undefined} */ getActiveUsersCount(cb) { const options = { type: 'active-users' }; if (cb && cb instanceof Function) { return this.resource.get(options, cb); } // Return a promise. return this.resource.get(options); } } module.exports = StatsManager;
auth0/node-auth0
src/management/StatsManager.js
JavaScript
mit
3,012
const initialState = { minimoPalpite: 2, valorMaximoAposta: 500, valorMinimoAposta: 5, } function BancaReducer(state= initialState, action) { return state; } export default BancaReducer
sysbet/sysbet-mobile
src/reducers/sistema/banca.js
JavaScript
mit
205
// Package acceptlang provides a Martini handler and primitives to parse // the Accept-Language HTTP header values. // // See the HTTP header fields specification for more details // (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4). // // Example // // Use the handler to automatically parse the Accept-Language header and // return the results as response: // m.Get("/", acceptlang.Languages(), func(languages acceptlang.AcceptLanguages) string { // return fmt.Sprintf("Languages: %s", languages) // }) // package acceptlang import ( "bytes" "fmt" "github.com/go-martini/martini" "net/http" "sort" "strconv" "strings" ) const ( acceptLanguageHeader = "Accept-Language" ) // A single language from the Accept-Language HTTP header. type AcceptLanguage struct { Language string Quality float32 } // A slice of sortable AcceptLanguage instances. type AcceptLanguages []AcceptLanguage // Returns the total number of items in the slice. Implemented to satisfy // sort.Interface. func (al AcceptLanguages) Len() int { return len(al) } // Swaps the items at position i and j. Implemented to satisfy sort.Interface. func (al AcceptLanguages) Swap(i, j int) { al[i], al[j] = al[j], al[i] } // Determines whether or not the item at position i is "less than" the item // at position j. Implemented to satisfy sort.Interface. func (al AcceptLanguages) Less(i, j int) bool { return al[i].Quality > al[j].Quality } // Returns the parsed languages in a human readable fashion. func (al AcceptLanguages) String() string { output := bytes.NewBufferString("") for i, language := range al { output.WriteString(fmt.Sprintf("%s (%1.1f)", language.Language, language.Quality)) if i != len(al)-1 { output.WriteString(", ") } } if output.Len() == 0 { output.WriteString("[]") } return output.String() } // Creates a new handler that parses the Accept-Language HTTP header. // // The parsed structure is a slice of Accept-Language values stored in an // AcceptLanguages instance, sorted based on the language qualifier. func Languages() martini.Handler { return func(context martini.Context, request *http.Request) { header := request.Header.Get(acceptLanguageHeader) if header != "" { acceptLanguageHeaderValues := strings.Split(header, ",") acceptLanguages := make(AcceptLanguages, len(acceptLanguageHeaderValues)) for i, languageRange := range acceptLanguageHeaderValues { // Check if a given range is qualified or not if qualifiedRange := strings.Split(languageRange, ";q="); len(qualifiedRange) == 2 { quality, error := strconv.ParseFloat(qualifiedRange[1], 32) if error != nil { // When the quality is unparseable, assume it's 1 acceptLanguages[i] = AcceptLanguage{trimLanguage(qualifiedRange[0]), 1} } else { acceptLanguages[i] = AcceptLanguage{trimLanguage(qualifiedRange[0]), float32(quality)} } } else { acceptLanguages[i] = AcceptLanguage{trimLanguage(languageRange), 1} } } sort.Sort(acceptLanguages) context.Map(acceptLanguages) } else { // If we have no Accept-Language header just map an empty slice context.Map(make(AcceptLanguages, 0)) } } } func trimLanguage(language string) string { return strings.Trim(language, " ") }
martini-contrib/acceptlang
handler.go
GO
mit
3,280
context 'LPUSH' do include CompatibilityTesting setup do @original = Redis.new @compatible = Moneta.new :Memory mirror :lpush, 'test:lpush', 'foo' end test 'when list does not exist' do assert_compatible :lpush, 'test:nx', 'foo' end test 'when list has items already' do assert_compatible :lpush, 'test:lpush', 'foo' end teardown do @original.del 'test:lpush', 'test:nx' @original.disconnect! @compatible.close end end
colstrom/redislike
tests/compatibility/redislike/lists/lpush.rb
Ruby
mit
473
using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended; using MonoGame.Extended.ViewportAdapters; using LudumDare38.Managers; namespace LudumDare38.Scenes { public abstract class SceneBase { //-------------------------------------------------- // Some stuff private SpriteFont _debugFont; public ContentManager Content; public Dictionary<string, string> DebugValues; //-------------------------------------------------- // FPS counter private FramesPerSecondCounter _fpsCounter; //----------------------//------------------------// public virtual void LoadContent() { Content = new ContentManager(SceneManager.Instance.Content.ServiceProvider, "Content"); _fpsCounter = new FramesPerSecondCounter(); _debugFont = Content.Load<SpriteFont>("fonts/DebugFont"); DebugValues = new Dictionary<string, string>(); } public virtual void UnloadContent() { Content.Unload(); } public virtual void Update(GameTime gameTime) { InputManager.Instace.Update(); } public void UpdateFpsCounter(GameTime gameTime) { _fpsCounter.Update(gameTime); } public void DrawDebugValues(SpriteBatch spriteBatch) { if (!SceneManager.Instance.DebugMode) return; spriteBatch.DrawString(_debugFont, string.Format("FPS: {0}", _fpsCounter.AverageFramesPerSecond), new Vector2(5, 5), Color.Gray); var i = 0; foreach (KeyValuePair<string, string> value in DebugValues) spriteBatch.DrawString(_debugFont, value.Key + ": " + value.Value, new Vector2(5, 25 + 20 * i++), Color.Gray); } public virtual void Draw(SpriteBatch spriteBatch, Matrix transformMatrix) { } } }
Phantom-Ignition/LudumDare38
LudumDare38/Scenes/SceneBase.cs
C#
mit
2,014
export default { "hljs-comment": { "color": "#776977" }, "hljs-quote": { "color": "#776977" }, "hljs-variable": { "color": "#ca402b" }, "hljs-template-variable": { "color": "#ca402b" }, "hljs-attribute": { "color": "#ca402b" }, "hljs-tag": { "color": "#ca402b" }, "hljs-name": { "color": "#ca402b" }, "hljs-regexp": { "color": "#ca402b" }, "hljs-link": { "color": "#ca402b" }, "hljs-selector-id": { "color": "#ca402b" }, "hljs-selector-class": { "color": "#ca402b" }, "hljs-number": { "color": "#a65926" }, "hljs-meta": { "color": "#a65926" }, "hljs-built_in": { "color": "#a65926" }, "hljs-builtin-name": { "color": "#a65926" }, "hljs-literal": { "color": "#a65926" }, "hljs-type": { "color": "#a65926" }, "hljs-params": { "color": "#a65926" }, "hljs-string": { "color": "#918b3b" }, "hljs-symbol": { "color": "#918b3b" }, "hljs-bullet": { "color": "#918b3b" }, "hljs-title": { "color": "#516aec" }, "hljs-section": { "color": "#516aec" }, "hljs-keyword": { "color": "#7b59c0" }, "hljs-selector-tag": { "color": "#7b59c0" }, "hljs": { "display": "block", "overflowX": "auto", "background": "#f7f3f7", "color": "#695d69", "padding": "0.5em" }, "hljs-emphasis": { "fontStyle": "italic" }, "hljs-strong": { "fontWeight": "bold" } }
conorhastings/react-syntax-highlighter
src/styles/hljs/atelier-heath-light.js
JavaScript
mit
1,709
package org.analogweb.core; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.analogweb.InvocationMetadata; import org.analogweb.RequestContext; import org.analogweb.RequestPath; import org.analogweb.RequestPathMetadata; import org.junit.Before; import org.junit.Test; /** * @author snowgoose */ public class PathVariableValueResolverTest { private PathVariableValueResolver resolver; private InvocationMetadata metadata; private RequestContext context; @Before public void setUp() throws Exception { resolver = new PathVariableValueResolver(); metadata = mock(InvocationMetadata.class); context = mock(RequestContext.class); } @Test public void testResolveAttributeValue() { RequestPath requestedPath = mock(RequestPath.class); when(context.getRequestPath()).thenReturn(requestedPath); when(requestedPath.getActualPath()).thenReturn("/mock/do/any/else"); RequestPathMetadata definedPath = mock(RequestPathMetadata.class); when(metadata.getDefinedPath()).thenReturn(definedPath); when(definedPath.getActualPath()).thenReturn( "/mock/do/{something}/else"); when(definedPath.match(requestedPath)).thenReturn(true); String actual = (String) resolver.resolveValue(context, metadata, "something", null, null); assertThat(actual, is("any")); actual = (String) resolver.resolveValue(context, metadata, "anything", null, null); assertThat(actual, is(nullValue())); } @Test public void testResolveAttributeValueWithRegexVariable() { RequestPath requestedPath = mock(RequestPath.class); when(context.getRequestPath()).thenReturn(requestedPath); when(requestedPath.getActualPath()).thenReturn("/mock/do/any/e"); RequestPathMetadata definedPath = mock(RequestPathMetadata.class); when(metadata.getDefinedPath()).thenReturn(definedPath); when(definedPath.getActualPath()).thenReturn( "/mock/do/{something}/else$<[a-z]>"); when(definedPath.match(requestedPath)).thenReturn(true); String actual = (String) resolver.resolveValue(context, metadata, "something", null, null); assertThat(actual, is("any")); actual = (String) resolver.resolveValue(context, metadata, "else", null, null); assertThat(actual, is("e")); actual = (String) resolver.resolveValue(context, metadata, "anything", null, null); assertThat(actual, is(nullValue())); } @Test public void testResolveRegexVariable() { RequestPath requestedPath = mock(RequestPath.class); when(context.getRequestPath()).thenReturn(requestedPath); when(requestedPath.getActualPath()).thenReturn("/mock/do/any/3"); RequestPathMetadata definedPath = mock(RequestPathMetadata.class); when(metadata.getDefinedPath()).thenReturn(definedPath); when(definedPath.getActualPath()).thenReturn( "/mock/do/any/else$<[0-9]>"); when(definedPath.match(requestedPath)).thenReturn(true); String actual = (String) resolver.resolveValue(context, metadata, "something", null, null); assertThat(actual, is(nullValue())); actual = (String) resolver.resolveValue(context, metadata, "else", null, null); assertThat(actual, is("3")); actual = (String) resolver.resolveValue(context, metadata, "anything", null, null); assertThat(actual, is(nullValue())); } @Test public void testResolveAttributeValueWithRegexVariableNotMatched() { RequestPath requestedPath = mock(RequestPath.class); when(context.getRequestPath()).thenReturn(requestedPath); when(requestedPath.getActualPath()).thenReturn("/mock/do/any/1"); RequestPathMetadata definedPath = mock(RequestPathMetadata.class); when(metadata.getDefinedPath()).thenReturn(definedPath); when(definedPath.getActualPath()).thenReturn( "/mock/do/{something}/else$<[a-z]>"); when(definedPath.match(requestedPath)).thenReturn(true); String actual = (String) resolver.resolveValue(context, metadata, "something", null, null); assertThat(actual, is("any")); actual = (String) resolver.resolveValue(context, metadata, "else", null, null); assertThat(actual, is(nullValue())); actual = (String) resolver.resolveValue(context, metadata, "anything", null, null); assertThat(actual, is(nullValue())); } @Test public void testResolveAttributeValueWithoutPlaceHolder() { RequestPath requestedPath = mock(RequestPath.class); when(context.getRequestPath()).thenReturn(requestedPath); when(requestedPath.getActualPath()).thenReturn("/mock/do/any/else"); RequestPathMetadata definedPath = mock(RequestPathMetadata.class); when(metadata.getDefinedPath()).thenReturn(definedPath); when(definedPath.getActualPath()).thenReturn("/mock/do/any/else"); when(definedPath.match(requestedPath)).thenReturn(true); String actual = (String) resolver.resolveValue(context, metadata, "something", null, null); assertThat(actual, is(nullValue())); } }
analogweb/core
src/test/java/org/analogweb/core/PathVariableValueResolverTest.java
Java
mit
4,964
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using MySql.Data.MySqlClient; using Jam; using System.IO; public partial class UIControls_ImageCover : JamUIControl { public UIControls_ImageCover() { m_Code = 56; } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { FillForm(); } } public string DefaultImgUrl { get { return (string)ViewState["DefaultImgUrl"]; } set { ViewState["DefaultImgUrl"] = value; } } public string ImgId { get { return (string)ViewState["ImgId"]; } set { ViewState["ImgId"] = value; } } public string BandId { get { return (string)ViewState["BandId"]; } set { ViewState["BandId"] = value; } } public string Visibility { get { return (string)ViewState["Visibility"]; } set { ViewState["Visibility"] = value; } } private string NewImgFile { get { return (uplImg.Visible && uplImg.HasFile) ? "~/images/" + JamTypes.User.GetUserFromSession(Session).Id + "/" + uplImg.FileName : null; } } public bool Deleted { get { return ViewState["Deleted"] != null ? (bool)ViewState["Deleted"] : false; } private set { ViewState["Deleted"] = value; } } protected void btnChangeCover_Click(object sender, EventArgs e) { if (btnChangeCover.Text == "Change") { lbImgCoverFile.Visible = false; uplImg.Visible = true; btnChangeCover.Text = "Cancel"; } else { lbImgCoverFile.Visible = true; uplImg.Visible = false; btnChangeCover.Text = "Change"; } } private void FillForm() { lbImgCoverFile.Text = ""; imgCover.ImageUrl = DefaultImgUrl; if (!String.IsNullOrEmpty(ImgId)) { uplImg.Visible = false; lbImgCoverFile.Visible = true; trCoverBtn.Visible = true; imgCover.ImageUrl = "~/GetImage.aspx?id=" + ImgId; FillImageName(ImgId); } else { uplImg.Visible = true; lbImgCoverFile.Visible = false; trCoverBtn.Visible = false; } } private void FillImageName(string sImgId) { MySqlConnection con = Utils.GetSqlConnection(); if (con != null) { try { MySqlCommand cmd = new MySqlCommand("select FileName from images where Id=?Id", con); cmd.Parameters.Add("?Id", MySqlDbType.UInt64).Value = UInt64.Parse(sImgId); string sImgFile = cmd.ExecuteScalar().ToString(); if (!String.IsNullOrEmpty(sImgFile)) { sImgFile = sImgFile.Substring(("~/images/" + JamTypes.User.GetUserFromSession(Session).Id + "/").Length); lbImgCoverFile.Text = sImgFile; } } catch (Exception ex) { JamLog.log(JamLog.enEntryType.error, "ImageCover", "FillImageName: " + ex.Message); } finally { con.Close(); } } } //return Id in tables images public string Save(MySqlConnection con, MySqlTransaction trans) { if(!String.IsNullOrEmpty(ImgId))//update { if (!Deleted) { MySqlCommand cmd = new MySqlCommand("", con, trans); cmd.CommandText = "update images set "; if (!String.IsNullOrEmpty(NewImgFile)) { cmd.CommandText += " FileName = ?FileName,"; cmd.Parameters.Add("?FileName", MySqlDbType.VarChar, 100).Value = NewImgFile; } cmd.CommandText += @"BandId=?BandId, Visibility=?Visibility, Updated=?Updated where Id=?Id;"; cmd.Parameters.Add("?BandId", MySqlDbType.UInt64).Value = null; if (!String.IsNullOrEmpty(BandId)) cmd.Parameters.Add("?BandId", MySqlDbType.UInt64).Value = UInt64.Parse(BandId); cmd.Parameters.Add("?Visibility", MySqlDbType.Int16).Value = Int16.Parse(Visibility); cmd.Parameters.Add("?Updated", MySqlDbType.DateTime).Value = DateTime.UtcNow; cmd.Parameters.Add("?Id", MySqlDbType.UInt64).Value = UInt64.Parse(ImgId); cmd.ExecuteNonQuery(); if (!String.IsNullOrEmpty(NewImgFile)) { uplImg.SaveAs(MapPath(NewImgFile)); if (!String.IsNullOrEmpty(lbImgCoverFile.Text)) { //delete previous path string sDeletePath = this.MapPath("~/images/") + JamTypes.User.GetUserFromSession(Session).Id + "/" + lbImgCoverFile.Text.Trim(); File.Delete(sDeletePath); } } return ImgId; } else //delete { MySqlCommand cmd = new MySqlCommand("delete from images where Id=?Id", con, trans); cmd.Parameters.Add("?Id", MySqlDbType.UInt64).Value = UInt64.Parse(ImgId); cmd.ExecuteNonQuery(); if (!String.IsNullOrEmpty(lbImgCoverFile.Text)) { //delete previous path string sDeletePath = this.MapPath("~/images/") + JamTypes.User.GetUserFromSession(Session).Id + "/" + lbImgCoverFile.Text.Trim(); File.Delete(sDeletePath); } return null; } } else if(!String.IsNullOrEmpty(NewImgFile)) //create { MySqlCommand cmd = new MySqlCommand("", con, trans); cmd.CommandText = @"insert into images (FileName, BandId, Visibility, Updated) values(?FileName, ?BandId, ?Visibility, ?Updated); SELECT LAST_INSERT_ID();"; cmd.Parameters.Add("?FileName", MySqlDbType.VarChar, 100).Value = NewImgFile; if (!String.IsNullOrEmpty(BandId)) cmd.Parameters.Add("?BandId", MySqlDbType.UInt64).Value = UInt64.Parse(BandId); else cmd.Parameters.Add("?BandId", MySqlDbType.UInt64).Value = null; cmd.Parameters.Add("?Visibility", MySqlDbType.Int16).Value = Int16.Parse(Visibility); cmd.Parameters.Add("?Updated", MySqlDbType.DateTime).Value = DateTime.UtcNow; string sRet = cmd.ExecuteScalar().ToString(); uplImg.SaveAs(MapPath(NewImgFile)); return sRet; } return null; } protected void btnDelete_Click(object sender, EventArgs e) { Deleted = true; imgCover.ImageUrl = DefaultImgUrl; uplImg.Visible = true; lbImgCoverFile.Visible = false; trCoverBtn.Visible = false; } }
hardsky/music-head
web/UIControls/ImageCover.ascx.cs
C#
mit
7,390
require 'test_helper' # silence_warnings trick around require can be removed once # https://github.com/hipchat/hipchat-rb/pull/174 # gets merged and released silence_warnings do require 'hipchat' end class HipchatNotifierTest < ActiveSupport::TestCase test "should send hipchat notification if properly configured" do options = { :api_token => 'good_token', :room_name => 'room_name', :color => 'yellow', } HipChat::Room.any_instance.expects(:send).with('Exception', fake_body, { :color => 'yellow' }) hipchat = ExceptionNotifier::HipchatNotifier.new(options) hipchat.call(fake_exception) end test "should call pre/post_callback if specified" do pre_callback_called, post_callback_called = 0,0 options = { :api_token => 'good_token', :room_name => 'room_name', :color => 'yellow', :pre_callback => proc { |*| pre_callback_called += 1}, :post_callback => proc { |*| post_callback_called += 1} } HipChat::Room.any_instance.expects(:send).with('Exception', fake_body, { :color => 'yellow' }.merge(options.except(:api_token, :room_name))) hipchat = ExceptionNotifier::HipchatNotifier.new(options) hipchat.call(fake_exception) assert_equal(1, pre_callback_called) assert_equal(1, post_callback_called) end test "should send hipchat notification without backtrace info if properly configured" do options = { :api_token => 'good_token', :room_name => 'room_name', :color => 'yellow', } HipChat::Room.any_instance.expects(:send).with('Exception', fake_body_without_backtrace, { :color => 'yellow' }) hipchat = ExceptionNotifier::HipchatNotifier.new(options) hipchat.call(fake_exception_without_backtrace) end test "should allow custom from value if set" do options = { :api_token => 'good_token', :room_name => 'room_name', :from => 'TrollFace', } HipChat::Room.any_instance.expects(:send).with('TrollFace', fake_body, { :color => 'red' }) hipchat = ExceptionNotifier::HipchatNotifier.new(options) hipchat.call(fake_exception) end test "should not send hipchat notification if badly configured" do wrong_params = { :api_token => 'bad_token', :room_name => 'test_room' } HipChat::Client.stubs(:new).with('bad_token', {:api_version => 'v1'}).returns(nil) hipchat = ExceptionNotifier::HipchatNotifier.new(wrong_params) assert_nil hipchat.room end test "should not send hipchat notification if api_key is missing" do wrong_params = {:room_name => 'test_room'} HipChat::Client.stubs(:new).with(nil, {:api_version => 'v1'}).returns(nil) hipchat = ExceptionNotifier::HipchatNotifier.new(wrong_params) assert_nil hipchat.room end test "should not send hipchat notification if room_name is missing" do wrong_params = {:api_token => 'good_token'} HipChat::Client.stubs(:new).with('good_token', {:api_version => 'v1'}).returns({}) hipchat = ExceptionNotifier::HipchatNotifier.new(wrong_params) assert_nil hipchat.room end test "should send hipchat notification with message_template" do options = { :api_token => 'good_token', :room_name => 'room_name', :color => 'yellow', :message_template => ->(exception) { "This is custom message: '#{exception.message}'" } } HipChat::Room.any_instance.expects(:send).with('Exception', "This is custom message: '#{fake_exception.message}'", { :color => 'yellow' }) hipchat = ExceptionNotifier::HipchatNotifier.new(options) hipchat.call(fake_exception) end test "should send hipchat notification with HTML-escaped meessage if using default message_template" do options = { :api_token => 'good_token', :room_name => 'room_name', :color => 'yellow', } exception = fake_exception_with_html_characters body = "A new exception occurred: '#{Rack::Utils.escape_html(exception.message)}' on '#{exception.backtrace.first}'" HipChat::Room.any_instance.expects(:send).with('Exception', body, { :color => 'yellow' }) hipchat = ExceptionNotifier::HipchatNotifier.new(options) hipchat.call(exception) end test "should use APIv1 if api_version is not specified" do options = { :api_token => 'good_token', :room_name => 'room_name', } HipChat::Client.stubs(:new).with('good_token', {:api_version => 'v1'}).returns({}) hipchat = ExceptionNotifier::HipchatNotifier.new(options) hipchat.call(fake_exception) end test "should use APIv2 when specified" do options = { :api_token => 'good_token', :room_name => 'room_name', :api_version => 'v2', } HipChat::Client.stubs(:new).with('good_token', {:api_version => 'v2'}).returns({}) hipchat = ExceptionNotifier::HipchatNotifier.new(options) hipchat.call(fake_exception) end private def fake_body "A new exception occurred: '#{fake_exception.message}' on '#{fake_exception.backtrace.first}'" end def fake_exception begin 5/0 rescue Exception => e e end end def fake_exception_with_html_characters begin raise StandardError.new('an error with <html> characters') rescue Exception => e e end end def fake_body_without_backtrace "A new exception occurred: '#{fake_exception_without_backtrace.message}'" end def fake_exception_without_backtrace StandardError.new('my custom error') end end
trevorturk/exception_notification
test/exception_notifier/hipchat_notifier_test.rb
Ruby
mit
5,526
module Log2irc class Channel class << self # hostname or ip def move(to, hostname_ip) if channels[to].nil? channels[to] = {} Log2irc.bot.join(to) end ip, hostname = remove(hostname_ip) channels[to][ip] = { hostname: hostname, last_log: Time.now.to_i } save_config end # hostname or ip def rename(hostname_ip, hostname) channels.each do |channel, hosts| hosts.each do |ip, data| next unless ip == hostname_ip || data[:hostname] == hostname_ip channels[channel][ip][:hostname] = hostname save_config return true end end false end # hostname or ip def refresh(hostname_ip) channels.each do |channel, hosts| hosts.each do |ip, data| next unless ip == hostname_ip || data[:hostname] == hostname_ip channels[channel][ip][:hostname] = resolv(ip) save_config return channels[channel][ip][:hostname] end end false end # hostname or ip def remove(hostname_ip) channels.each do |channel, hosts| hosts.each do |ip, data| next unless ip == hostname_ip || data[:hostname] == hostname_ip channels[channel].delete(ip) if channels[channel].empty? channels.delete(channel) Log2irc.bot.part(channel) end return [ip, data[:hostname]] end end nil end # hostname or ip def watchdog(hostname_ip, time) channels.each do |channel, hosts| hosts.each do |ip, data| next unless ip == hostname_ip || data[:hostname] == hostname_ip data[:watchdog] = time return [ip, data[:hostname]] end end nil end # ip def find(host_ip) channels.each do |channel, hosts| hosts.each do |ip, data| if ip == host_ip data[:last_log] = Time.now.to_i return [channel, data[:hostname]] end end end [Log2irc.settings['irc']['channel'], add_new_host(host_ip)] end def channels return @channels if @channels if File.exist?(file_path) @channels = YAML.load_file(file_path) else @channels = {} end @channels.each do |ch, _list| Log2irc.bot.join(ch) end end def add_new_host(host_ip) ch = Log2irc.settings['irc']['channel'] channels[ch] = {} unless channels[ch] channels[ch][host_ip] = { hostname: resolv(host_ip), last_log: Time.now.to_i } save_config channels[ch][host_ip][:hostname] end def resolv(host_ip) Resolv.getname(host_ip) rescue host_ip end def save_config File.open(file_path, 'w') do |f| f.write channels.to_yaml end end def file_path File.join(Log2irc.path, '../config/channels.yml') end end end end
l3akage/log2irc
lib/log2irc/channel.rb
Ruby
mit
3,230
class DropFactualPages < ActiveRecord::Migration[5.0] def up drop_table :factual_pages end def down raise ActiveRecord::IrreversibleMigration end end
artsy/bearden
db/migrate/20170223222333_drop_factual_pages.rb
Ruby
mit
167
/** * @license * Based on https://github.com/lodash/lodash/blob/master/perf/perf.js * Available under MIT license <https://lodash.com/license> */ var Benchmark = require('benchmark') var formatNumber = Benchmark.formatNumber var tcParser = require('type-check').parseType var tcChecker = require('type-check').parsedTypeCheck var yatcParser = require('../src/parser') var yatcChecker = require('../src/checker').check var score = {a: [], b: []} var suites = [] function getGeometricMean(array) { return Math.pow(Math.E, array.reduce(function(sum, x) { return sum + Math.log(x) }, 0) / array.length) || 0 } function getHz(bench) { var result = 1 / (bench.stats.mean + bench.stats.moe) return isFinite(result) ? result : 0 } Benchmark.extend(Benchmark.Suite.options, { 'onStart': function () { console.log('\n' + this.name + ':') }, 'onCycle': function (event) { console.log(event.target.toString()) }, 'onComplete': function () { var errored = Object.keys(this).some(function (index) { return !!this[index].error }.bind(this)) if (errored) { console.log('There was a problem, skipping...') } else { var fastest = this.filter('fastest') var fastestHz = getHz(fastest[0]) var slowest = this.filter('slowest') var slowestHz = getHz(slowest[0]) var aHz = getHz(this[0]) var bHz = getHz(this[1]) var percent = ((fastestHz / slowestHz) - 1) * 100 percent = percent < 1 ? percent.toFixed(2) : Math.round(percent) percent = formatNumber(percent) if (fastest.length > 1) { console.log('It\'s too close to call.') aHz = bHz = slowestHz } else { console.log(fastest[0].name + ' is ' + percent + '% faster.') } score.a.push(aHz) score.b.push(bHz) } suites.shift() if (suites.length > 0) { suites[0].run() } else { var aMeanHz = getGeometricMean(score.a) var bMeanHz = getGeometricMean(score.b) var fastestMeanHz = Math.max(aMeanHz, bMeanHz) var slowestMeanHz = Math.min(aMeanHz, bMeanHz) var xFaster = fastestMeanHz / slowestMeanHz var percentFaster = formatNumber(Math.round((xFaster - 1) * 100)) xFaster = xFaster === 1 ? '' : '(' + formatNumber(xFaster.toFixed(2)) + 'x)' var message = 'is ' + percentFaster + '% ' + xFaster + ' faster than' if (aMeanHz > bMeanHz) { console.log('\nyatc ' + message + ' type-check.') } else { console.log('\ntype-check ' + message + ' yatc.') } } } }) function addSuite(benchType, type, input, customTypes) { var tcFn, yatcFn switch (benchType) { case 'parse': tcFn = function () { tcParser(type) } yatcFn = function () { yatcParser(type) } break case 'check': var tcType = tcParser(type) var yatcType = yatcParser(type) tcFn = function () { tcChecker(tcType, customTypes) } yatcFn = function () { yatcChecker(yatcType, customTypes) } break case 'parse&check': tcFn = function () { tcChecker(tcParser(type), input, customTypes) } yatcFn = function () { yatcChecker(yatcParser(type), input, customTypes) } break default: throw new TypeError('Unknow benchType: ' + benchType) } suites.push( Benchmark.Suite(benchType + ' ' + type) .add('yatc', yatcFn) .add('type-check', tcFn) ) } var rawSuites = [ ['Number', 1], ['Number|String', ''], ['Maybe Number', null], ['[Number]', [1, 2]], ['(Int, Float)', [1, 0.1]], ['{a: String}', {a: 'hi'}], ['{a: (Number), ...}', {a: [0], b: 0.1}], ['[{lat: Float, long: Float}]', [{lat: 15.42, long: 42.15}]], ] rawSuites.forEach(function (rawSuite) { var args = ['parse&check'].concat(rawSuite) addSuite.apply(null, args) }) console.log('Make a cup of tea and relax') suites[0].run()
fanatid/yatc
perf/perf.js
JavaScript
mit
3,879
package server import ( "bytes" "context" "net/http" "net/http/httptest" "testing" "github.com/influxdata/influxdb/chronograf" "github.com/influxdata/influxdb/chronograf/mocks" "github.com/julienschmidt/httprouter" ) func TestService_Queries(t *testing.T) { tests := []struct { name string SourcesStore chronograf.SourcesStore ID string w *httptest.ResponseRecorder r *http.Request want string }{ { name: "bad json", SourcesStore: &mocks.SourcesStore{ GetF: func(ctx context.Context, ID int) (chronograf.Source, error) { return chronograf.Source{ ID: ID, }, nil }, }, ID: "1", w: httptest.NewRecorder(), r: httptest.NewRequest("POST", "/queries", bytes.NewReader([]byte(`howdy`))), want: `{"code":400,"message":"unparsable JSON"}`, }, { name: "bad id", ID: "howdy", w: httptest.NewRecorder(), r: httptest.NewRequest("POST", "/queries", bytes.NewReader([]byte{})), want: `{"code":422,"message":"error converting ID howdy"}`, }, { name: "query with no template vars", SourcesStore: &mocks.SourcesStore{ GetF: func(ctx context.Context, ID int) (chronograf.Source, error) { return chronograf.Source{ ID: ID, }, nil }, }, ID: "1", w: httptest.NewRecorder(), r: httptest.NewRequest("POST", "/queries", bytes.NewReader([]byte(`{ "queries": [ { "query": "SELECT \"pingReq\" FROM db.\"monitor\".\"httpd\" WHERE time > now() - 1m", "id": "82b60d37-251e-4afe-ac93-ca20a3642b11" } ]}`))), want: `{"queries":[{"durationMs":59999,"id":"82b60d37-251e-4afe-ac93-ca20a3642b11","query":"SELECT \"pingReq\" FROM db.\"monitor\".\"httpd\" WHERE time \u003e now() - 1m","queryConfig":{"id":"82b60d37-251e-4afe-ac93-ca20a3642b11","database":"db","measurement":"httpd","retentionPolicy":"monitor","fields":[{"value":"pingReq","type":"field","alias":""}],"tags":{},"groupBy":{"time":"","tags":[]},"areTagsAccepted":false,"rawText":null,"range":{"upper":"","lower":"now() - 1m"},"shifts":[]},"queryAST":{"condition":{"expr":"binary","op":"\u003e","lhs":{"expr":"reference","val":"time"},"rhs":{"expr":"binary","op":"-","lhs":{"expr":"call","name":"now"},"rhs":{"expr":"literal","val":"1m","type":"duration"}}},"fields":[{"column":{"expr":"reference","val":"pingReq"}}],"sources":[{"database":"db","retentionPolicy":"monitor","name":"httpd","type":"measurement"}]}}]} `, }, { name: "query with unparsable query", SourcesStore: &mocks.SourcesStore{ GetF: func(ctx context.Context, ID int) (chronograf.Source, error) { return chronograf.Source{ ID: ID, }, nil }, }, ID: "1", w: httptest.NewRecorder(), r: httptest.NewRequest("POST", "/queries", bytes.NewReader([]byte(`{ "queries": [ { "query": "SHOW DATABASES", "id": "82b60d37-251e-4afe-ac93-ca20a3642b11" } ]}`))), want: `{"queries":[{"durationMs":0,"id":"82b60d37-251e-4afe-ac93-ca20a3642b11","query":"SHOW DATABASES","queryConfig":{"id":"82b60d37-251e-4afe-ac93-ca20a3642b11","database":"","measurement":"","retentionPolicy":"","fields":[],"tags":{},"groupBy":{"time":"","tags":[]},"areTagsAccepted":false,"rawText":"SHOW DATABASES","range":null,"shifts":[]}}]} `, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.r = tt.r.WithContext(context.WithValue( context.TODO(), httprouter.ParamsKey, httprouter.Params{ { Key: "id", Value: tt.ID, }, })) s := &Service{ Store: &mocks.Store{ SourcesStore: tt.SourcesStore, }, Logger: &mocks.TestLogger{}, } s.Queries(tt.w, tt.r) got := tt.w.Body.String() if got != tt.want { t.Errorf("got:\n%s\nwant:\n%s\n", got, tt.want) } }) } }
mark-rushakoff/influxdb
chronograf/server/queries_test.go
GO
mit
3,837
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenORPG.Database.DAL; using Server.Game.Combat; using Server.Game.Database; using Server.Game.Database.Models.ContentTemplates; using Server.Game.Entities; using Server.Infrastructure.Logging; namespace Server.Game.Items { /// <summary> /// A <see cref="SkillbookItem"/> is capable of granting a user a skill permanently when used. /// The item will be consumed when used, typically. /// </summary> public class SkillbookItem : Item { public SkillbookItem(ItemTemplate itemTemplate) : base(itemTemplate) { } public override bool Consumable { get { return true; } } public override void UseItemOn(Character character, Character user) { var player = character as Player; if (player != null) { using (var context = new GameDatabaseContext()) { var skillRepo = new SkillRepository(context); var skillTemplate = skillRepo.Get(ItemTemplate.LearntSkillId); player.AddSkill(new Skill(skillTemplate)); } } else { Logger.Instance.Warn("You cannot use a skillbook on a non-player target."); } } } }
hilts-vaughan/OpenORPG
OpenORPG.Server/Game/Items/SkillbookItem.cs
C#
mit
1,487
module Gandi class Domain class Host include Gandi::GandiObjectMethods #The hostname of the Host attr_reader :hostname def initialize(hostname, attributes = nil) @hostname = hostname @attributes = attributes || info end #Delete a host. #Returns a Gandi::Operation object. def delete operation_hash = self.class.call('domain.host.delete', @hostname) Gandi::Operation.new(operation_hash['id'], operation_hash) end #Display host information for a given domain. def info self.class.call('domain.host.info', @hostname) end #Return the host IP adresses. def ips @attributes['ips'] end #Update a host. #Return a Gandi::Operation object. def update(ips) operation_hash = self.class.call('domain.host.update', @hostname, ips) Gandi::Operation.new(operation_hash['id'], operation_hash) end class << self #Create a host. #Returns a Gandi::Operation object. def create(hostname, ips) operation_hash = call('domain.host.create', hostname, ips) Gandi::Operation.new(operation_hash['id'], operation_hash) end #Count the glue records / hosts of a domain. #TODO: accept a Domain object. def count(fqdn, opts = {}) call('domain.host.count', fqdn, opts) end #List the glue records / hosts for a given domain. #Return an array of Host objects. #TODO: accept a Domain object. def list(fqdn, opts = {}) call('domain.host.list', fqdn, opts).map do |host| self.new(host['name'], host) end end end end end end
pickabee/gandi
lib/gandi/domain/host.rb
Ruby
mit
1,820
#!/bin/python3 import sys time = input().strip() # 12AM = 00:00 # 12PM = 12:00 # 01PM = 13:00 meridian = time[-2:] time = time[:-2] hour, minute, second = time.split(":") hour = int(hour, 10) if meridian == "PM": if hour != 12: hour += 12 else: if hour == 12: hour = 0 print("{:0>2d}:{}:{}".format(hour, minute, second))
costincaraivan/hackerrank
algorithms/warmup/python3/time_conversion.py
Python
mit
351
""" Test suite for the cppext library. The script can be executed on its own or incorporated into a larger test suite. However the tests are run, be aware of which version of the package is actually being tested. If the package is installed in site-packages, that version takes precedence over the version in this project directory. Use a virtualenv test environment or setuptools develop mode to test against the development version. """ import pytest from cppext import * def test_pyhello(): """ Test the pyhello() function. """ assert pyhello() == "Greetings from Python!" return def test_cpphello(): """ Test the cpphello() function. """ assert cpphello() == "Greetings from C++!" return class CppGreetingTest(object): """ Test suite for the CppGreeting class. """ def test_hello(self): """ Test the hello() method. """ name = "CppGreetingTest" greeting = CppGreeting(name) assert greeting.hello() == "Greetings from C++, {:s}!".format(name) return # Make the module executable. if __name__ == "__main__": raise SystemExit(pytest.main([__file__]))
mdklatt/cppext-python
test/test_cppext.py
Python
mit
1,176
/* * Copyright (c) 2017 Andrew Kelley * * This file is part of zig, which is MIT licensed. * See http://opensource.org/licenses/MIT */ #include "bigfloat.hpp" #include "bigint.hpp" #include "buffer.hpp" #include "softfloat.hpp" #include <stdio.h> #include <math.h> #include <errno.h> void bigfloat_init_128(BigFloat *dest, float128_t x) { dest->value = x; } void bigfloat_init_16(BigFloat *dest, float16_t x) { f16_to_f128M(x, &dest->value); } void bigfloat_init_32(BigFloat *dest, float x) { float32_t f32_val; memcpy(&f32_val, &x, sizeof(float)); f32_to_f128M(f32_val, &dest->value); } void bigfloat_init_64(BigFloat *dest, double x) { float64_t f64_val; memcpy(&f64_val, &x, sizeof(double)); f64_to_f128M(f64_val, &dest->value); } void bigfloat_init_bigfloat(BigFloat *dest, const BigFloat *x) { memcpy(&dest->value, &x->value, sizeof(float128_t)); } void bigfloat_init_bigint(BigFloat *dest, const BigInt *op) { ui32_to_f128M(0, &dest->value); if (op->digit_count == 0) return; float128_t base; ui64_to_f128M(UINT64_MAX, &base); const uint64_t *digits = bigint_ptr(op); for (size_t i = op->digit_count - 1;;) { float128_t digit_f128; ui64_to_f128M(digits[i], &digit_f128); f128M_mulAdd(&dest->value, &base, &digit_f128, &dest->value); if (i == 0) { if (op->is_negative) { float128_t zero_f128; ui32_to_f128M(0, &zero_f128); f128M_sub(&zero_f128, &dest->value, &dest->value); } return; } i -= 1; } } int bigfloat_init_buf_base10(BigFloat *dest, const uint8_t *buf_ptr, size_t buf_len) { char *str_begin = (char *)buf_ptr; char *str_end; errno = 0; double value = strtod(str_begin, &str_end); // TODO actual f128 parsing if (errno) { return ErrorOverflow; } float64_t value_f64; memcpy(&value_f64, &value, sizeof(double)); f64_to_f128M(value_f64, &dest->value); assert(str_end <= ((char*)buf_ptr) + buf_len); return 0; } void bigfloat_add(BigFloat *dest, const BigFloat *op1, const BigFloat *op2) { f128M_add(&op1->value, &op2->value, &dest->value); } void bigfloat_negate(BigFloat *dest, const BigFloat *op) { float128_t zero_f128; ui32_to_f128M(0, &zero_f128); f128M_sub(&zero_f128, &op->value, &dest->value); } void bigfloat_sub(BigFloat *dest, const BigFloat *op1, const BigFloat *op2) { f128M_sub(&op1->value, &op2->value, &dest->value); } void bigfloat_mul(BigFloat *dest, const BigFloat *op1, const BigFloat *op2) { f128M_mul(&op1->value, &op2->value, &dest->value); } void bigfloat_div(BigFloat *dest, const BigFloat *op1, const BigFloat *op2) { f128M_div(&op1->value, &op2->value, &dest->value); } void bigfloat_div_trunc(BigFloat *dest, const BigFloat *op1, const BigFloat *op2) { f128M_div(&op1->value, &op2->value, &dest->value); f128M_roundToInt(&dest->value, softfloat_round_minMag, false, &dest->value); } void bigfloat_div_floor(BigFloat *dest, const BigFloat *op1, const BigFloat *op2) { f128M_div(&op1->value, &op2->value, &dest->value); f128M_roundToInt(&dest->value, softfloat_round_min, false, &dest->value); } void bigfloat_rem(BigFloat *dest, const BigFloat *op1, const BigFloat *op2) { f128M_rem(&op1->value, &op2->value, &dest->value); } void bigfloat_mod(BigFloat *dest, const BigFloat *op1, const BigFloat *op2) { f128M_rem(&op1->value, &op2->value, &dest->value); f128M_add(&dest->value, &op2->value, &dest->value); f128M_rem(&dest->value, &op2->value, &dest->value); } void bigfloat_append_buf(Buf *buf, const BigFloat *op) { const size_t extra_len = 100; size_t old_len = buf_len(buf); buf_resize(buf, old_len + extra_len); // TODO actually print f128 float64_t f64_value = f128M_to_f64(&op->value); double double_value; memcpy(&double_value, &f64_value, sizeof(double)); int len = snprintf(buf_ptr(buf) + old_len, extra_len, "%f", double_value); assert(len > 0); buf_resize(buf, old_len + len); } Cmp bigfloat_cmp(const BigFloat *op1, const BigFloat *op2) { if (f128M_lt(&op1->value, &op2->value)) { return CmpLT; } else if (f128M_eq(&op1->value, &op2->value)) { return CmpEQ; } else { return CmpGT; } } float16_t bigfloat_to_f16(const BigFloat *bigfloat) { return f128M_to_f16(&bigfloat->value); } float bigfloat_to_f32(const BigFloat *bigfloat) { float32_t f32_value = f128M_to_f32(&bigfloat->value); float result; memcpy(&result, &f32_value, sizeof(float)); return result; } double bigfloat_to_f64(const BigFloat *bigfloat) { float64_t f64_value = f128M_to_f64(&bigfloat->value); double result; memcpy(&result, &f64_value, sizeof(double)); return result; } float128_t bigfloat_to_f128(const BigFloat *bigfloat) { return bigfloat->value; } Cmp bigfloat_cmp_zero(const BigFloat *bigfloat) { float128_t zero_float; ui32_to_f128M(0, &zero_float); if (f128M_lt(&bigfloat->value, &zero_float)) { return CmpLT; } else if (f128M_eq(&bigfloat->value, &zero_float)) { return CmpEQ; } else { return CmpGT; } } bool bigfloat_has_fraction(const BigFloat *bigfloat) { float128_t floored; f128M_roundToInt(&bigfloat->value, softfloat_round_minMag, false, &floored); return !f128M_eq(&floored, &bigfloat->value); } void bigfloat_sqrt(BigFloat *dest, const BigFloat *op) { f128M_sqrt(&op->value, &dest->value); }
Dimenus/zig
src/bigfloat.cpp
C++
mit
5,573
<?php namespace Doctrineum\Tests\Entity\TestsOfTests; use Doctrine\ORM\EntityManager; use Doctrineum\Tests\Entity\AbstractDoctrineEntitiesTest; /** * @codeCoverageIgnore */ class DoctrineEntityUnknownSqlDriverNegativeTest extends AbstractDoctrineEntitiesTest { protected function getSqlExtensionName(): string { return 'nonsenseSql'; } protected function getDirsWithEntities() { throw new \LogicException('Should not reach this code'); } protected function createEntitiesToPersist(): array { throw new \LogicException('Should not reach this code'); } protected function fetchEntitiesByOriginals(array $originalEntities, EntityManager $entityManager): array { throw new \LogicException('Should not reach this code'); } }
jaroslavtyc/doctrineum-entity
Doctrineum/Tests/Entity/TestsOfTests/DoctrineEntityUnknownSqlDriverNegativeTest.php
PHP
mit
807
<?php class Bug extends Eloquent { public $table = 'bugs'; public static $rules = array( 'page'=>'required', 'prio'=>'required', 'message'=>'required' ); public function user() { return $this->belongsTo('User'); } }
murum/baxacykel
app/models/Bug.php
PHP
mit
243
require 'thread_safe' module ActiveModel class Serializer extend ActiveSupport::Autoload autoload :Configuration autoload :ArraySerializer autoload :Adapter include Configuration class << self attr_accessor :_attributes attr_accessor :_attributes_keys attr_accessor :_associations attr_accessor :_urls attr_accessor :_cache attr_accessor :_fragmented attr_accessor :_cache_key attr_accessor :_cache_only attr_accessor :_cache_except attr_accessor :_cache_options end def self.inherited(base) base._attributes = self._attributes.try(:dup) || [] base._attributes_keys = self._attributes_keys.try(:dup) || {} base._associations = self._associations.try(:dup) || {} base._urls = [] end def self.attributes(*attrs) attrs = attrs.first if attrs.first.class == Array @_attributes.concat attrs @_attributes.uniq! attrs.each do |attr| define_method attr do object && object.read_attribute_for_serialization(attr) end unless method_defined?(attr) || _fragmented.respond_to?(attr) end end def self.attribute(attr, options = {}) key = options.fetch(:key, attr) @_attributes_keys[attr] = {key: key} if key != attr @_attributes << key unless @_attributes.include?(key) define_method key do object.read_attribute_for_serialization(attr) end unless method_defined?(key) || _fragmented.respond_to?(attr) end def self.fragmented(serializer) @_fragmented = serializer end # Enables a serializer to be automatically cached def self.cache(options = {}) @_cache = ActionController::Base.cache_store if Rails.configuration.action_controller.perform_caching @_cache_key = options.delete(:key) @_cache_only = options.delete(:only) @_cache_except = options.delete(:except) @_cache_options = (options.empty?) ? nil : options end # Defines an association in the object should be rendered. # # The serializer object should implement the association name # as a method which should return an array when invoked. If a method # with the association name does not exist, the association name is # dispatched to the serialized object. def self.has_many(*attrs) associate(:has_many, attrs) end # Defines an association in the object that should be rendered. # # The serializer object should implement the association name # as a method which should return an object when invoked. If a method # with the association name does not exist, the association name is # dispatched to the serialized object. def self.belongs_to(*attrs) associate(:belongs_to, attrs) end # Defines an association in the object should be rendered. # # The serializer object should implement the association name # as a method which should return an object when invoked. If a method # with the association name does not exist, the association name is # dispatched to the serialized object. def self.has_one(*attrs) associate(:has_one, attrs) end def self.associate(type, attrs) #:nodoc: options = attrs.extract_options! self._associations = _associations.dup attrs.each do |attr| unless method_defined?(attr) define_method attr do object.send attr end end self._associations[attr] = {type: type, association_options: options} end end def self.url(attr) @_urls.push attr end def self.urls(*attrs) @_urls.concat attrs end def self.serializer_for(resource, options = {}) if resource.respond_to?(:serializer_class) resource.serializer_class elsif resource.respond_to?(:to_ary) config.array_serializer else options .fetch(:association_options, {}) .fetch(:serializer, get_serializer_for(resource.class)) end end def self.adapter adapter_class = case config.adapter when Symbol ActiveModel::Serializer::Adapter.adapter_class(config.adapter) when Class config.adapter end unless adapter_class valid_adapters = Adapter.constants.map { |klass| ":#{klass.to_s.downcase}" } raise ArgumentError, "Unknown adapter: #{config.adapter}. Valid adapters are: #{valid_adapters}" end adapter_class end def self._root @@root ||= false end def self._root=(root) @@root = root end def self.root_name name.demodulize.underscore.sub(/_serializer$/, '') if name end attr_accessor :object, :root, :meta, :meta_key, :scope def initialize(object, options = {}) @object = object @options = options @root = options[:root] || (self.class._root ? self.class.root_name : false) @meta = options[:meta] @meta_key = options[:meta_key] @scope = options[:scope] scope_name = options[:scope_name] if scope_name && !respond_to?(scope_name) self.class.class_eval do define_method scope_name, lambda { scope } end end end def json_key if root == true || root.nil? self.class.root_name else root end end def id object.id if object end def type object.class.to_s.demodulize.underscore.pluralize end def attributes(options = {}) attributes = if options[:fields] self.class._attributes & options[:fields] else self.class._attributes.dup end attributes += options[:required_fields] if options[:required_fields] attributes.each_with_object({}) do |name, hash| unless self.class._fragmented hash[name] = send(name) else hash[name] = self.class._fragmented.public_send(name) end end end def each_association(&block) self.class._associations.dup.each do |name, association_options| next unless object association_value = send(name) serializer_class = ActiveModel::Serializer.serializer_for(association_value, association_options) if serializer_class serializer = serializer_class.new( association_value, options.merge(serializer_from_options(association_options)) ) elsif !association_value.nil? && !association_value.instance_of?(Object) association_options[:association_options][:virtual_value] = association_value end if block_given? block.call(name, serializer, association_options[:association_options]) end end end def serializer_from_options(options) opts = {} serializer = options.fetch(:association_options, {}).fetch(:serializer, nil) opts[:serializer] = serializer if serializer opts end def self.serializers_cache @serializers_cache ||= ThreadSafe::Cache.new end private attr_reader :options def self.get_serializer_for(klass) serializers_cache.fetch_or_store(klass) do serializer_class_name = "#{klass.name}Serializer" serializer_class = serializer_class_name.safe_constantize if serializer_class serializer_class elsif klass.superclass get_serializer_for(klass.superclass) end end end end end
Yakrware/active_model_serializers
lib/active_model/serializer.rb
Ruby
mit
7,560
@extends('app') @section('title',$profile->user->name.'的主页') {{--@section('header-css') <link rel="stylesheet" href="/css/profile.css"> <link rel="stylesheet" href="/css/search.css"> @endsection--}} {{--@section('header-js') <script src="/js/source/vue.js"></script> <script src="/js/source/vue-resource.min.js"></script> @endsection--}} @section('content') <div class="profile" id="app"> @include('common.profile_header') <div class="container"> <div class="profile-main row"> @include('common.profile_left_navbar') <div class="profile-posts col-md-9 profile-my-content"> <h3 class="ui horizontal divider header"> <i class="bar chart icon"></i> @if(!\Auth::check()) 他的帖子 @elseif(\Auth::check()&&\Auth::user()->owns($profile)) 我的帖子 @else 他的帖子 @endif </h3> <ul class="profile-list"> @foreach($posts as $post) <li> <div class="row"> <div class="col-md-1 col-xs-1"> <span class="label label-success profile-label">{{$post->comment_count}}回复</span> </div> <div class="col-md-8 col-xs-8"> <a class="profile-article-title" href="/discussion/{{$post->id}}">{{$post->title}}</a> </div> <div class="col-md-3 col-xs-3" style="font-size: 16px"> <span class="profile-article-time">帖子发表于{{$post->created_at->diffForHumans()}}</span> </div> </div> </li> @endforeach </ul> </div> </div> </div> </div> @endsection @section('footer-js') <script> $(document).ready(function () { $('#profile-posts-list').addClass('active'); }); </script> @include('common.profile_follow_user') @endsection
GeekGhc/ISpace
resources/views/profile/post.blade.php
PHP
mit
2,510
import { types } from './types'; interface FetchCafeRequested { type: types.FETCH_CAFE_REQUESTED; payload: number; } interface FetchCafeSucceeded { type: types.FETCH_CAFE_SUCCEEDED; payload: any; } interface FetchCafeFailed { type: types.FETCH_CAFE_FAILED; payload: any; } export type FetchCafeAction = | FetchCafeRequested | FetchCafeSucceeded | FetchCafeFailed; export const fetchCafe = (id: number) => ({ type: types.FETCH_CAFE_REQUESTED, payload: id, }); export const fetchCafeSucceeded = (cafe: any) => ({ type: types.FETCH_CAFE_SUCCEEDED, payload: cafe, }); export const fetchCafeFailed = (err: any) => ({ type: types.FETCH_CAFE_FAILED, payload: err.message, });
mjlaufer/cafe-tour-client
src/client/components/screens/CafeDetail/actions/index.ts
TypeScript
mit
691
namespace E06_BirthdayCelebrations.Models { public class Robot : SocietyMember { private string model; public Robot(string id, string model) : base(id) { this.Model = model; } public string Model { get { return this.model; } private set { this.model = value; } } } }
Rusev12/Software-University-SoftUni
C# OOP Advanced/01-Interfaces-and-Abstraction/E06-BirthdayCelebrations/Models/Robot.cs
C#
mit
397
# flake8: noqa # -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Event.is_published' db.add_column('event_rsvp_event', 'is_published', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) def backwards(self, orm): # Deleting field 'Event.is_published' db.delete_column('event_rsvp_event', 'is_published') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'event_rsvp.event': { 'Meta': {'object_name': 'Event'}, 'allow_anonymous_rsvp': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'available_seats': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'contact_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'contact_person': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'contact_phone': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'country': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'creation_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'max_length': '1000', 'null': 'True', 'blank': 'True'}), 'end': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 17, 0, 0)'}), 'hide_available_seats': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'max_seats_per_guest': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'required_fields': ('event_rsvp.models.MultiSelectField', [], {'max_length': '250', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '256'}), 'start': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 16, 0, 0)'}), 'street': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'template_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '256'}), 'venue': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'zip': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}) }, 'event_rsvp.guest': { 'Meta': {'object_name': 'Guest'}, 'creation_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'event': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'guests'", 'to': "orm['event_rsvp.Event']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_attending': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'message': ('django.db.models.fields.TextField', [], {'max_length': '4000', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'number_of_seats': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}) } } complete_apps = ['event_rsvp']
bitmazk/django-event-rsvp
event_rsvp/migrations/0008_auto__add_field_event_is_published.py
Python
mit
7,470
<?php namespace Bit3\FakerCli\Command; use Faker\Factory; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class GenerateCommand extends Command { protected function configure() { $this ->setName('faker:generate') ->addOption( 'locale', 'l', InputOption::VALUE_REQUIRED, 'The locale to use.', Factory::DEFAULT_LOCALE ) ->addOption( 'seed', 's', InputOption::VALUE_REQUIRED, 'The generators seed.' ) ->addOption( 'pattern', 'p', InputOption::VALUE_REQUIRED, 'The printf pattern.', '%s' ) ->addOption( 'delimiter', 'd', InputOption::VALUE_REQUIRED, 'The delimiter is used by the csv and printf format.', ',' ) ->addOption( 'enclosure', 'e', InputOption::VALUE_REQUIRED, 'The enclosure is used by the csv and printf format.' ) ->addOption( 'escape', 'E', InputOption::VALUE_REQUIRED, 'The escape character is used by the printf format.', '\\' ) ->addOption( 'format', 'f', InputOption::VALUE_REQUIRED, 'The output format (json, xml, csv, php, printf, vprintf)', 'printf' ) ->addOption( 'count', 'c', InputArgument::OPTIONAL, 'The count of generated data.', 10 ) ->addArgument( 'type', InputArgument::REQUIRED, 'The data type to generate (e.g. "randomDigit", "words", "name", "city")' ) ->addArgument( 'args', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Arguments for the type, e.g. "words 5" will generate 5 words.' ); } protected function execute(InputInterface $input, OutputInterface $output) { $locale = $input->getOption('locale'); $seed = $input->getOption('seed'); $format = $input->getOption('format'); $count = $input->getOption('count'); $type = $input->getArgument('type'); $args = $input->getArgument('args'); $data = array(); $faker = Factory::create($locale); if ($seed) { $faker->seed($seed); } for ($i = 0; $i < $count; $i++) { $data[] = $faker->format($type, $args); } switch ($format) { case 'json': $this->outputJson($output, $data); break; case 'xml': $this->outputXml($output, $data); break; case 'csv': $this->outputCsv($input, $output, $data); break; case 'php': $this->outputPhp($output, $data); break; case 'printf': $this->outputPrintf($input, $output, $data); break; case 'vprintf': $this->outputVprintf($input, $output, $data); break; default: throw new \RuntimeException('Unknown output format ' . $format); } } /** * Generate and output the data as JSON. * * @param OutputInterface $output * @param mixed $data */ protected function outputJson(OutputInterface $output, $data) { $json = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); $output->write($json); } /** * Generate and output the data as XML. * * @param OutputInterface $output * @param mixed $data */ protected function outputXml(OutputInterface $output, $data) { $doc = new \DOMDocument(); $doc->formatOutput = true; $doc->appendChild($this->generateXml($doc, $data)); $xml = $doc->saveXML(); $output->write($xml); } /** * Generate a xml element from the input data. * * @param \DOMDocument $doc * @param mixed $data * * @return \DOMElement */ protected function generateXml(\DOMDocument $doc, $data) { if (is_array($data) && range(0, count($data) - 1) == array_keys($data)) { // $data is a regular indexed array $array = $doc->createElement('array'); foreach ($data as $value) { $entry = $doc->createElement('item'); $entry->appendChild($this->generateXml($doc, $value)); $array->appendChild($entry); } return $array; } else if (is_array($data) || is_object($data)) { // $data is an associative array or object $map = $doc->createElement('map'); foreach ($data as $key => $value) { $entry = $doc->createElement('item'); $entry->setAttribute('key', $key); $entry->appendChild($this->generateXml($doc, $value)); $map->appendChild($entry); } return $map; } else { // $data is a primitive type return $doc->createTextNode($data); } } /** * Generate and output the data as CSV. * * @param OutputInterface $output * @param mixed $data */ protected function outputCsv(InputInterface $input, OutputInterface $output, $data) { $delimiter = $input->getOption('delimiter'); $enclosure = $input->getOption('enclosure'); $stream = fopen('php://temp', 'w+'); foreach ($data as $row) { if ($enclosure === null) { fputcsv($stream, $this->flattenArray($row), $delimiter); } else { fputcsv($stream, $this->flattenArray($row), $delimiter, $enclosure); } } fseek($stream, 0); $csv = stream_get_contents($stream); $output->write($csv); } /** * Flatten an array. * * @param $data * * @return array */ protected function flattenArray($data) { if (is_array($data) || is_object($data)) { $buffer = array(); foreach ($data as $item) { $buffer = array_merge($buffer, $this->flattenArray($item)); } return $buffer; } else { return (array) $data; } } /** * Generate and output the data as PHP. * * @param OutputInterface $output * @param mixed $data */ protected function outputPhp(OutputInterface $output, $data) { $php = var_export($data, true); $output->write($php); } /** * Generate and output the data as PHP. * * @param OutputInterface $output * @param mixed $data */ protected function outputPrintf(InputInterface $input, OutputInterface $output, $data) { $pattern = $input->getOption('pattern'); $delimiter = $input->getOption('delimiter'); $enclosure = $input->getOption('enclosure'); $escape = $input->getOption('escape'); foreach ($data as $value) { $value = $this->flattenArray($value); $value = implode($delimiter, $value); if ($enclosure) { $value = $enclosure . str_replace($enclosure, $escape . $enclosure, $value) . $enclosure; } $output->writeln(sprintf($pattern, $value)); } } /** * Generate and output the data as PHP. * * @param OutputInterface $output * @param mixed $data */ protected function outputVprintf(InputInterface $input, OutputInterface $output, $data) { $pattern = $input->getOption('pattern'); $enclosure = $input->getOption('enclosure'); $escape = $input->getOption('escape'); foreach ($data as $values) { $values = $this->flattenArray((array) $values); if ($enclosure) { foreach ($values as $key => $value) { $values[$key] = $enclosure . str_replace($enclosure, $escape . $enclosure, $value) . $enclosure; } } $output->writeln(vsprintf($pattern, $values)); } } }
bit3/faker-cli
src/Command/GenerateCommand.php
PHP
mit
7,146
<h4><b>Statistics Summary</b></h4> <br> <p><b>A) Gender Student Distribution</b></p> <hr> <table class="table table-striped table-responsive table-hover"> <thead id="gender_table_head"> </thead> <tbody id="gender_table_body"> </tbody> </table> <br> <p><b>B) Muslim Student Distribution</b></p> <hr> <table class="table table-striped table-responsive table-hover"> <thead id="muslim_table_head"> </thead> <tbody id="muslim_table_body"> </tbody> </table> <br> <p><b>C) CGPA Category Student Distribution</b></p> <hr> <table class="table table-striped table-responsive table-hover"> <thead id="cgpa_category_student_table_head"> </thead> <tbody id="cgpa_category_student_table_body"> </tbody> </table> <br> <p><b>D) Program Student Distribution</b></p> <hr> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="program_student_table_head"> </thead> <tbody id="program_student_table_body"> </tbody> </table> </div> <br> <p><b>D) CGPA Category Program Distribution</b></p> <hr> <p><b>1) Excellent </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_excellent_student_table_head"> </thead> <tbody id="cgpa_category_program_excellent_student_table_body"> </tbody> </table> </div> <br> <p><b>2) Superior </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_superior_student_table_head"> </thead> <tbody id="cgpa_category_program_superior_student_table_body"> </tbody> </table> </div> <br> <p><b>3) Very Good </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_verygood_student_table_head"> </thead> <tbody id="cgpa_category_program_verygood_student_table_body"> </tbody> </table> </div> <br> <p><b>4) Good </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_good_student_table_head"> </thead> <tbody id="cgpa_category_program_good_student_table_body"> </tbody> </table> </div> <br> <p><b>5) Very Satisfactory </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_verysatisfactory_student_table_head"> </thead> <tbody id="cgpa_category_program_verysatisfactory_student_table_body"> </tbody> </table> </div> <br> <p><b>6) High Average </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_highaverage_student_table_head"> </thead> <tbody id="cgpa_category_program_highaverage_student_table_body"> </tbody> </table> </div> <br> <p><b>7) Average </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_average_student_table_head"> </thead> <tbody id="cgpa_category_program_average_student_table_body"> </tbody> </table> </div> <br> <p><b>8) Fair </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_fair_student_table_head"> </thead> <tbody id="cgpa_category_program_fair_student_table_body"> </tbody> </table> </div> <br> <p><b>9) Pass </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_pass_student_table_head"> </thead> <tbody id="cgpa_category_program_pass_student_table_body"> </tbody> </table> </div> <br> <p><b>10) Fail </b></p> <div class="scrollable-div-table-container"> <table class="table table-striped table-responsive table-hover" > <thead id="cgpa_category_program_fail_student_table_head"> </thead> <tbody id="cgpa_category_program_fail_student_table_body"> </tbody> </table> </div> <script> $(document).ready(function() { var table_headers = ['Data Label', 'Frequency']; var gender_pop_route = "{{ route('gender_population') }}"; var muslim_pop_route = "{{ route('muslim_population') }}"; var course_pop_route = "{{ route('course_population') }}"; var cgpa_student_pop_route = "{{ route('cgpa_cluster_pop_count') }}"; var cgpa_program_student_excellent_route = "{{ route('cgpa_cluster_count') }}"+"?category=Excellent"; var cgpa_program_student_superior_route = "{{ route('cgpa_cluster_count') }}"+"?category=Superior"; var cgpa_program_student_verygood_route = "{{ route('cgpa_cluster_count') }}"+"?category=Very Good"; var cgpa_program_student_good_route = "{{ route('cgpa_cluster_count') }}"+"?category=Good"; var cgpa_program_student_verysatisfactory_route = "{{ route('cgpa_cluster_count') }}"+"?category=Very Satisfactory"; var cgpa_program_student_highaverage_route = "{{ route('cgpa_cluster_count') }}"+"?category=High Average"; var cgpa_program_student_average_route = "{{ route('cgpa_cluster_count') }}"+"?category=Average"; var cgpa_program_student_fair_route = "{{ route('cgpa_cluster_count') }}"+"?category=Fair"; var cgpa_program_student_pass_route = "{{ route('cgpa_cluster_count') }}"+"?category=Pass"; var cgpa_program_student_fail_route = "{{ route('cgpa_cluster_count') }}"+"?category=Fail"; populate_frequency_table(gender_pop_route, "gender_table_body", table_headers, "gender_table_head"); populate_frequency_table(muslim_pop_route, "muslim_table_body", table_headers, "muslim_table_head"); populate_frequency_table(course_pop_route, "program_student_table_body", table_headers, "program_student_table_head"); populate_frequency_table(cgpa_student_pop_route, "cgpa_category_student_table_body", table_headers, "cgpa_category_student_table_head"); populate_frequency_table(cgpa_program_student_excellent_route, "cgpa_category_program_excellent_student_table_body", table_headers , "cgpa_category_program_excellent_student_table_head"); populate_frequency_table(cgpa_program_student_superior_route, "cgpa_category_program_superior_student_table_body", table_headers , "cgpa_category_program_superior_student_table_head"); populate_frequency_table(cgpa_program_student_verygood_route, "cgpa_category_program_verygood_student_table_body", table_headers , "cgpa_category_program_verygood_student_table_head"); populate_frequency_table(cgpa_program_student_good_route, "cgpa_category_program_good_student_table_body", table_headers , "cgpa_category_program_good_student_table_head"); populate_frequency_table(cgpa_program_student_verysatisfactory_route, "cgpa_category_program_verysatisfactory_student_table_body", table_headers , "cgpa_category_program_verysatisfactory_student_table_head"); populate_frequency_table(cgpa_program_student_highaverage_route, "cgpa_category_program_highaverage_student_table_body", table_headers , "cgpa_category_program_highaverage_student_table_head"); populate_frequency_table(cgpa_program_student_highaverage_route, "cgpa_category_program_highaverage_student_table_body", table_headers , "cgpa_category_program_highaverage_student_table_head"); populate_frequency_table(cgpa_program_student_highaverage_route, "cgpa_category_program_average_student_table_body", table_headers , "cgpa_category_program_average_student_table_head"); populate_frequency_table(cgpa_program_student_fair_route, "cgpa_category_program_fair_student_table_body", table_headers , "cgpa_category_program_fair_student_table_head"); populate_frequency_table(cgpa_program_student_pass_route, "cgpa_category_program_pass_student_table_body", table_headers , "cgpa_category_program_pass_student_table_head"); populate_frequency_table(cgpa_program_student_fail_route, "cgpa_category_program_fail_student_table_body", table_headers , "cgpa_category_program_fail_student_table_head"); }); </script>
stinkymonkeyph/Studenizer
resources/views/components/tables/data_summary.blade.php
PHP
mit
9,401
import { generate } from "randomstring" import { NON_EXECUTABLE_FILE_MODE, EXECUTABLE_FILE_MODE, } from "../src/patch/parse" import { assertNever } from "../src/assertNever" export interface File { contents: string mode: number } export interface Files { [filePath: string]: File } export interface TestCase { cleanFiles: Files modifiedFiles: Files } const fileCharSet = ` \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789!@£$%^&*()-=_+[]{};'i\\:"|<>?,./\`~§± 0123456789!@£$%^&*()-=_+[]{};'i\\:"|<>?,./\`~§± \r\r\r\r\t\t\t\t ` function makeFileContents(): File { return { contents: generate({ length: Math.floor(Math.random() * 1000), charset: fileCharSet, }) || "", mode: Math.random() > 0.5 ? 0o644 : 0o755, } } function makeFileName(ext?: boolean) { const name = generate({ length: Math.ceil(Math.random() * 10), charset: "abcdefghijklmnopqrstuvwxyz-_0987654321", }) return ext ? name + "." + generate(Math.ceil(Math.random() * 4)) : name } function makeFilePath() { const numParts = Math.floor(Math.random() * 3) const parts = [] for (let i = 0; i < numParts; i++) { parts.push(makeFileName()) } parts.push(makeFileName(true)) return parts.join("/") } function makeFiles(): Files { const fileSystem: Files = {} const numFiles = Math.random() * 3 + 1 for (let i = 0; i < numFiles; i++) { fileSystem[makeFilePath()] = makeFileContents() } return fileSystem } type MutationKind = | "deleteFile" | "createFile" | "deleteLine" | "insertLine" | "renameFile" | "changeFileMode" const mutationKindLikelihoods: Array<[MutationKind, number]> = [ ["deleteFile", 1], ["createFile", 1], ["renameFile", 1], ["changeFileMode", 1], ["deleteLine", 10], ["insertLine", 10], ] const liklihoodSum = mutationKindLikelihoods.reduce((acc, [_, n]) => acc + n, 0) function getNextMutationKind(): MutationKind { const n = Math.random() * liklihoodSum let sum = 0 for (const [kind, likelihood] of mutationKindLikelihoods) { sum += likelihood if (n < sum) { return kind } } return "insertLine" } function selectRandomElement<T>(ts: T[]): T { return ts[Math.floor(Math.random() * ts.length)] } function deleteLinesFromFile(file: File): File { const numLinesToDelete = Math.ceil(Math.random() * 1) const lines = file.contents.split("\n") const index = Math.max(Math.random() * (lines.length - numLinesToDelete), 0) lines.splice(index, numLinesToDelete) return { ...file, contents: lines.join("\n") } } function insertLinesIntoFile(file: File): File { const lines = file.contents.split("\n") const index = Math.floor(Math.random() * lines.length) const length = Math.ceil(Math.random() * 5) lines.splice(index, 0, generate({ length, charset: fileCharSet })) return { ...file, contents: lines.join("\n") } } function getUniqueFilename(files: Files) { let filename = makeFileName() const ks = Object.keys(files) while (ks.some(k => k.startsWith(filename))) { filename = makeFileName() } return filename } function mutateFiles(files: Files): Files { const mutatedFiles = { ...files } const numMutations = Math.ceil(Math.random() * 1000) for (let i = 0; i < numMutations; i++) { const mutationKind = getNextMutationKind() switch (mutationKind) { case "deleteFile": { if (Object.keys(mutatedFiles).length === 1) { break } // select a file at random and delete it const pathToDelete = selectRandomElement(Object.keys(mutatedFiles)) delete mutatedFiles[pathToDelete] break } case "createFile": { mutatedFiles[getUniqueFilename(mutatedFiles)] = makeFileContents() break } case "deleteLine": { const pathToDeleteFrom = selectRandomElement(Object.keys(mutatedFiles)) mutatedFiles[pathToDeleteFrom] = deleteLinesFromFile( mutatedFiles[pathToDeleteFrom], ) break } case "insertLine": const pathToInsertTo = selectRandomElement(Object.keys(mutatedFiles)) mutatedFiles[pathToInsertTo] = insertLinesIntoFile( mutatedFiles[pathToInsertTo], ) // select a file at random and insert some text in there break case "renameFile": const pathToRename = selectRandomElement(Object.keys(mutatedFiles)) mutatedFiles[getUniqueFilename(mutatedFiles)] = mutatedFiles[pathToRename] delete mutatedFiles[pathToRename] break case "changeFileMode": const pathToChange = selectRandomElement(Object.keys(mutatedFiles)) const { mode, contents } = mutatedFiles[pathToChange] mutatedFiles[pathToChange] = { contents, mode: mode === NON_EXECUTABLE_FILE_MODE ? EXECUTABLE_FILE_MODE : NON_EXECUTABLE_FILE_MODE, } break default: assertNever(mutationKind) } } return { ...mutatedFiles } } export function generateTestCase(): TestCase { const cleanFiles = makeFiles() return { cleanFiles, modifiedFiles: mutateFiles(cleanFiles), } }
ds300/patch-package
property-based-tests/testCases.ts
TypeScript
mit
5,362
using System.Collections.Generic; namespace CSharp2nem.ResponseObjects.Account { public class ExistingAccount { public class Cosignatory { public string Address { get; set; } public int HarvestedBlocks { get; set; } public long Balance { get; set; } public double Importance { get; set; } public long VestedBalance { get; set; } public string PublicKey { get; set; } public object Label { get; set; } public MultisigInfo MultisigInfo { get; set; } } public class MultisigInfo { public int CosignatoriesCount { get; set; } public int MinCosignatories { get; set; } } public class MultisigInfo2 { public int CosignatoriesCount { get; set; } public int MinCosignatories { get; set; } } public class CosignatoryOf { public string Address { get; set; } public int HarvestedBlocks { get; set; } public long Balance { get; set; } public double Importance { get; set; } public long VestedBalance { get; set; } public string PublicKey { get; set; } public object Label { get; set; } public MultisigInfo MultisigInfo { get; set; } } public class Account { public string Address { get; set; } public int HarvestedBlocks { get; set; } public long Balance { get; set; } public double Importance { get; set; } public long VestedBalance { get; set; } public string PublicKey { get; set; } public object Label { get; set; } public MultisigInfo2 MultisigInfo2 { get; set; } } public class Meta { public List<Cosignatory> Cosignatories { get; set; } public List<CosignatoryOf> CosignatoryOf { get; set; } public string Status { get; set; } public string RemoteStatus { get; set; } } public class Data { public Meta Meta { get; set; } public Account Account { get; set; } } } }
NemProject/csharp2nem
NemApi/Wrapper/ResponseObjects/Account/ExistingAccountData.cs
C#
mit
2,257
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("05.FormattingNumbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("05.FormattingNumbers")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7c48106b-f751-4dca-b69b-8094e8ef7c83")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
helena999/SoftUni-Assignments
00. Programming Basics/05. Console-Input-Output-Homework/05.FormattingNumbers/Properties/AssemblyInfo.cs
C#
mit
1,416
# coding: utf-8 from numpy import matrix from oneVsAll import oneVsAll from numpy import loadtxt, savetxt from predictOneVsAll import predictOneVsAll def train(): num_labels = 34 print '... Training' X = matrix(loadtxt('X.dat')) / 255.0 y = matrix(loadtxt('y.dat')).transpose() the_lambda = 0.1 all_theta = oneVsAll(X, y, num_labels, the_lambda) savetxt('theta.dat', all_theta) def test(): print '... Testing' all_theta = matrix(loadtxt('theta.dat')) X_test = matrix(loadtxt('X_test.dat')) / 255.0 y_test = matrix(loadtxt('y_test.dat')).transpose() acc, pred = predictOneVsAll(all_theta, X_test) single_acc = sum(pred == y_test) / (len(y_test) * 1.0) max_acc = pow(single_acc, 4) min_acc = single_acc*4 - 3 print 'Theoretical accuracy:' print '\tSingle accuracy: %2.2f%%' % (single_acc*100) print '\tTotal accuracy: %2.2f%% ~ %2.2f%%' % (min_acc*100, max_acc*100) test()
skyduy/zfverify
Verify-Manual-python/train/core/train.py
Python
mit
950
#!/usr/bin/env python import queue class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None self.size = 1 self.self_count = 1 def treeBuilder(nodeString): nodeList = nodeString[1:-1].split(',') nodeQueue = queue.Queue() if nodeList[0] == '': return None root = TreeNode(int(nodeList[0])) currNode = root leftDone, rightDone = 0, 0 for val in nodeList[1:]: print('processing %s' % val) print('leftDone,', leftDone, 'rightDone,', rightDone) if val != 'null': newNode = TreeNode(int(val)) print("create new node: %d" % newNode.val) nodeQueue.put(newNode) else: newNode = None if leftDone == 0: currNode.left, leftDone = newNode, 1 elif rightDone == 0: currNode.right, rightDone = newNode, 1 leftDone, rightDone = 0, 0 currNode = nodeQueue.get() return root def traverse(node): if node == None: return print('Node: %d' % node.val) if node.left != None: print('Left: %d' % node.left.val) if node.right != None: print('Right: %d' % node.right.val) if node.left != None: traverse(node.left) if node.right != None: traverse(node.right) def treeToString(root): if root == None: return None nodeQueue = [root] currStr = '' # print(nodeQueue) while len(nodeQueue) > 0: node = nodeQueue[0] nodeQueue = nodeQueue[1:] # print(nodeQueue) if node == None: currStr += 'null,' # print(None) else: # print(node.val, node.left, node.right) nodeQueue += [node.left] nodeQueue += [node.right] currStr += str(node.val)+',' # print(nodeQueue) # print(currStr) stringList = currStr[:-1].split(',') while stringList[-1] == 'null': stringList = stringList[:-1] currStr = ','.join(stringList) return currStr
eroicaleo/LearningPython
interview/leet/tree.py
Python
mit
2,092
using System; using LanguageExt.Common; using System.Threading.Tasks; using static LanguageExt.Prelude; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using LanguageExt.Effects.Traits; using LanguageExt.Pipes; using LanguageExt.Thunks; namespace LanguageExt { /// <summary> /// Synchronous IO monad /// </summary> public readonly struct Eff<RT, A> where RT : struct { internal Thunk<RT, A> Thunk => thunk ?? Thunk<RT, A>.Fail(Errors.Bottom); readonly Thunk<RT, A> thunk; /// <summary> /// Constructor /// </summary> [MethodImpl(Opt.Default)] internal Eff(Thunk<RT, A> thunk) => this.thunk = thunk ?? throw new ArgumentNullException(nameof(thunk)); /// <summary> /// Invoke the effect /// </summary> [Pure, MethodImpl(Opt.Default)] public Fin<A> Run(RT env) => Thunk.Value(env); /// <summary> /// Invoke the effect /// </summary> [Pure, MethodImpl(Opt.Default)] public Fin<A> ReRun(RT env) => Thunk.ReValue(env); /// <summary> /// Clone the effect /// </summary> /// <remarks> /// If the effect had already run, then this state will be wiped in the clone, meaning it can be re-run /// </remarks> [Pure, MethodImpl(Opt.Default)] public Eff<RT, A> Clone() => new Eff<RT, A>(Thunk.Clone()); /// <summary> /// Invoke the effect /// </summary> /// <remarks> /// Throws on error /// </remarks> [MethodImpl(Opt.Default)] public Unit RunUnit(RT env) => Thunk.Value(env).Case switch { A _ => unit, Error e => e.Throw(), _ => throw new NotSupportedException() }; /// <summary> /// Lift a synchronous effect into the IO monad /// </summary> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> EffectMaybe(Func<RT, Fin<A>> f) => new Eff<RT, A>(Thunk<RT, A>.Lazy(f)); /// <summary> /// Lift a synchronous effect into the IO monad /// </summary> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> Effect(Func<RT, A> f) => new Eff<RT, A>(Thunk<RT, A>.Lazy(e => Fin<A>.Succ(f(e)))); /// <summary> /// Lift a value into the IO monad /// </summary> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> Success(A value) => new Eff<RT, A>(Thunk<RT, A>.Success(value)); /// <summary> /// Lift a failure into the IO monad /// </summary> [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> Fail(Error error) => new Eff<RT, A>(Thunk<RT, A>.Fail(error)); [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> operator |(Eff<RT, A> ma, Eff<RT, A> mb) => new Eff<RT, A>(Thunk<RT, A>.Lazy( env => { var ra = ma.ReRun(env); return ra.IsSucc ? ra : mb.ReRun(env); })); [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> operator |(Eff<RT, A> ma, Eff<A> mb) => new Eff<RT, A>(Thunk<RT, A>.Lazy( e => { var ra = ma.ReRun(e); return ra.IsSucc ? ra : mb.ReRun(); })); [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> operator |(Eff<A> ma, Eff<RT, A> mb) => new Eff<RT, A>(Thunk<RT, A>.Lazy( e => { var ra = ma.ReRun(); return ra.IsSucc ? ra : mb.ReRun(e); })); [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> operator |(Eff<RT, A> ma, EffCatch<RT, A> mb) => new Eff<RT, A>(Thunk<RT, A>.Lazy( env => { var ra = ma.ReRun(env); return ra.IsSucc ? ra : mb.Run(env, ra.Error); })); [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> operator |(Eff<RT, A> ma, EffCatch<A> mb) => new Eff<RT, A>(Thunk<RT, A>.Lazy( env => { var ra = ma.ReRun(env); return ra.IsSucc ? ra : mb.Run(ra.Error); })); [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> operator |(Eff<RT, A> ma, CatchValue<A> value) => new Eff<RT, A>(Thunk<RT, A>.Lazy( env => { var ra = ma.ReRun(env); return ra.IsSucc ? ra : value.Match(ra.Error) ? FinSucc(value.Value(ra.Error)) : ra; })); [Pure, MethodImpl(Opt.Default)] public static Eff<RT, A> operator |(Eff<RT, A> ma, CatchError value) => new Eff<RT, A>(Thunk<RT, A>.Lazy( env => { var ra = ma.ReRun(env); return ra.IsSucc ? ra : value.Match(ra.Error) ? FinFail<A>(value.Value(ra.Error)) : ra; })); /// <summary> /// Implicit conversion from pure Eff /// </summary> public static implicit operator Eff<RT, A>(Eff<A> ma) => EffectMaybe(env => ma.ReRun()); } }
louthy/language-ext
LanguageExt.Core/Effects/Eff/Eff.cs
C#
mit
6,359
using MathSite.BasicAdmin.ViewModels.SharedModels.Posts; namespace MathSite.BasicAdmin.ViewModels.News { public class NewsViewModel : PostViewModel { } }
YarGU-Demidov/math-site
src/MathSite.BasicAdmin.ViewModels/News/NewsViewModel.cs
C#
mit
169
<?php if (!is_array($module)): ?> <p>404. No such module.</p> <?php else: ?> <h1>Module: <?= $module['name'] ?></h1> <h2>Description</h2> <p>File: <code><?= $module['filename'] ?></code></p> <p><?= nl2br($module['doccomment']) ?></p> <h2>Details</h2> <table> <caption>Details of module.</caption> <thead><tr><th>Characteristics</th><th>Applies to module</th></tr></thead> <tbody> <tr><td>Part of Siteshop Core modules</td><td><?= $module['isSiteshopCore'] ? 'Yes' : 'No' ?></td></tr> <tr><td>Part of Siteshop CMF modules</td><td><?= $module['isSiteshopCMF'] ? 'Yes' : 'No' ?></td></tr> <tr><td>Implements interface(s)</td><td><?= empty($module['interface']) ? 'No' : implode(', ', $module['interface']) ?></td></tr> <tr><td>Controller</td><td><?= $module['isController'] ? 'Yes' : 'No' ?></td></tr> <tr><td>Model</td><td><?= $module['isModel'] ? 'Yes' : 'No' ?></td></tr> <tr><td>Has SQL</td><td><?= $module['hasSQL'] ? 'Yes' : 'No' ?></td></tr> <tr><td>Manageable as a module</td><td><?= $module['isManageable'] ? 'Yes' : 'No' ?></td></tr> </tbody> </table> <?php if (!empty($module['publicMethods'])): ?> <h2>Public methods</h2> <?php foreach ($module['methods'] as $method): ?> <?php if ($method['isPublic']): ?> <h3><?= $method['name'] ?></h3> <p><?= nl2br($method['doccomment']) ?></p> <p>Implemented through lines: <?= $method['startline'] ?> - <?= $method['endline'] ?>.</p> <?php endif; ?> <?php endforeach; ?> <?php endif; ?> <?php if (!empty($module['protectedMethods'])): ?> <h2>Protected methods</h2> <?php foreach ($module['methods'] as $method): ?> <?php if ($method['isProtected']): ?> <h3><?= $method['name'] ?></h3> <p><?= nl2br($method['doccomment']) ?></p> <p>Implemented through lines: <?= $method['startline'] ?> - <?= $method['endline'] ?>.</p> <?php endif; ?> <?php endforeach; ?> <?php endif; ?> <?php if (!empty($module['privateMethods'])): ?> <h2>Private methods</h2> <?php foreach ($module['methods'] as $method): ?> <?php if ($method['isPrivate']): ?> <h3><?= $method['name'] ?></h3> <p><?= nl2br($method['doccomment']) ?></p> <p>Implemented through lines: <?= $method['startline'] ?> - <?= $method['endline'] ?>.</p> <?php endif; ?> <?php endforeach; ?> <?php endif; ?> <?php if (!empty($module['staticMethods'])): ?> <h2>Static methods</h2> <?php foreach ($module['methods'] as $method): ?> <?php if ($method['isStatic']): ?> <h3><?= $method['name'] ?></h3> <p><?= nl2br($method['doccomment']) ?></p> <p>Implemented through lines: <?= $method['startline'] ?> - <?= $method['endline'] ?>.</p> <?php endif; ?> <?php endforeach; ?> <?php endif; ?> <?php endif; ?>
guni12/siteshop
src/CCModules/view.tpl.php
PHP
mit
3,244
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Fluent; using Microsoft.Azure.Management.KeyVault.Fluent.Models; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.Samples.Common; using System; namespace ManageKeyVault { public class Program { /** * Azure Key Vault sample for managing key vaults - * - Create a key vault * - Authorize an application * - Update a key vault * - alter configurations * - change permissions * - Create another key vault * - List key vaults * - Delete a key vault. */ public static void RunSample(IAzure azure) { string vaultName1 = SdkContext.RandomResourceName("vault1", 20); string vaultName2 = SdkContext.RandomResourceName("vault2", 20); string rgName = SdkContext.RandomResourceName("rgNEMV", 24); try { //============================================================ // Create a key vault with empty access policy Utilities.Log("Creating a key vault..."); var vault1 = azure.Vaults .Define(vaultName1) .WithRegion(Region.USWest) .WithNewResourceGroup(rgName) .WithEmptyAccessPolicy() .Create(); Utilities.Log("Created key vault"); Utilities.PrintVault(vault1); //============================================================ // Authorize an application Utilities.Log("Authorizing the application associated with the current service principal..."); vault1 = vault1.Update() .DefineAccessPolicy() .ForServicePrincipal(SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION")).ClientId) .AllowKeyAllPermissions() .AllowSecretPermissions(SecretPermissions.Get) .AllowSecretPermissions(SecretPermissions.List) .Attach() .Apply(); Utilities.Log("Updated key vault"); Utilities.PrintVault(vault1); //============================================================ // Update a key vault Utilities.Log("Update a key vault to enable deployments and add permissions to the application..."); vault1 = vault1.Update() .WithDeploymentEnabled() .WithTemplateDeploymentEnabled() .UpdateAccessPolicy(vault1.AccessPolicies[0].ObjectId) .AllowSecretAllPermissions() .Parent() .Apply(); Utilities.Log("Updated key vault"); // Print the network security group Utilities.PrintVault(vault1); //============================================================ // Create another key vault var vault2 = azure.Vaults .Define(vaultName2) .WithRegion(Region.USEast) .WithExistingResourceGroup(rgName) .DefineAccessPolicy() .ForServicePrincipal(SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION")).ClientId) .AllowKeyPermissions(KeyPermissions.List) .AllowKeyPermissions(KeyPermissions.Get) .AllowKeyPermissions(KeyPermissions.Decrypt) .AllowSecretPermissions(SecretPermissions.Get) .Attach() .Create(); Utilities.Log("Created key vault"); // Print the network security group Utilities.PrintVault(vault2); //============================================================ // List key vaults Utilities.Log("Listing key vaults..."); foreach (var vault in azure.Vaults.ListByResourceGroup(rgName)) { Utilities.PrintVault(vault); } //============================================================ // Delete key vaults Utilities.Log("Deleting the key vaults"); azure.Vaults.DeleteById(vault1.Id); azure.Vaults.DeleteById(vault2.Id); Utilities.Log("Deleted the key vaults"); } finally { try { Utilities.Log("Deleting Resource Group: " + rgName); azure.ResourceGroups.DeleteByName(rgName); Utilities.Log("Deleted Resource Group: " + rgName); } catch (NullReferenceException) { Utilities.Log("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { Utilities.Log(g); } } } public static void Main(string[] args) { try { //================================================================= // Authenticate AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION")); var azure = Azure .Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithDefaultSubscription(); // Print selected subscription Utilities.Log("Selected subscription: " + azure.SubscriptionId); RunSample(azure); } catch (Exception e) { Utilities.Log(e); } } } }
hovsepm/azure-libraries-for-net
Samples/KeyVault/ManageKeyVault.cs
C#
mit
6,663
class Solution { public int solution (String S) { int length = S.length(); // Such index only exists if the length of the string is odd if (length % 2 == 0) { return -1; } int middle = length / 2; for (int i = middle - 1, j = middle + 1; i >= 0 && j < length; i--, j++) { if (S.charAt(i) != S.charAt(j)) { return -1; } } return middle; } } /** * @author shengmin */ public class Driver { public static void main(String[] args) { Solution sol = new Solution(); System.out.println(sol.solution("")); System.out.println(sol.solution("a")); System.out.println(sol.solution("aa")); System.out.println(sol.solution("aba")); System.out.println(sol.solution("abc")); System.out.println(sol.solution("racecar")); } }
shengmin/coding-problem
codility/task-1/Driver.java
Java
mit
810
package fsb.semantics.empeagerpso; import java.util.Set; import ags.constraints.AtomicPredicateDictionary; import ags.constraints.Formula; import fsb.ast.MProgram; import fsb.ast.Statement; import fsb.ast.Statement.StatType; import fsb.ast.tvl.ArithValue; import fsb.ast.tvl.DeterArithValue; import fsb.explore.Action; import fsb.explore.SBState; import fsb.explore.State; import fsb.explore.Validator; import fsb.semantics.BufVal; import fsb.semantics.SharedResMap; public class EmpEagerAbsState extends SBState { SharedResMap<SharedResVal> shared; protected Validator validator; public EmpEagerAbsState(MProgram program, Validator validator, int numProcs) { super(program, validator, numProcs); this.shared = new SharedResMap<SharedResVal>(); for(String var : program.getShared()) addShared(var, DeterArithValue.getInstance(0)); } @SuppressWarnings("unchecked") public EmpEagerAbsState(EmpEagerAbsState s) { super(s); //this.shared = s.shared; //if (!Options.LAZY_COPY) //{ this.shared = (SharedResMap) s.shared.clone(); //} } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof EmpEagerAbsState)) return false; EmpEagerAbsState other = (EmpEagerAbsState) obj; if (!shared.equals(other.shared)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + shared.hashCode(); return result; } public String toString() { StringBuffer sb = new StringBuffer(); for (int i = 0; i < numProcs; i++) { sb.append(i); sb.append(" : "); sb.append("PC = " + (pc[i] + 1) + " "); sb.append(locals[i].toString()); sb.append("\\n"); } sb.append(shared.toString()); return sb.toString(); } public boolean isFinal() { for (int pid = 0; pid < numProcs; pid++) { if (program.getListing(pid).get(pc[pid]).isLast() == false) return false; } //TODO: Is this required here? I think not, because END is only enabled when the buffer is empty... for (SharedResVal resval : shared.values()) { for (int pid = 0; pid < numProcs; pid++) if (!resval.isEmpty(pid)) return false; } return true; } @Override public void addShared(String str, ArithValue initval) { shared.put(str, new SharedResVal(numProcs, 0)); } @Override public boolean join(State s) { if(!equals(s)) throw new RuntimeException("Trying to join inappropriate states!"); EmpEagerAbsState other = (EmpEagerAbsState) s; boolean changed = false; for (String res : shared.keySet()) { SharedResVal resval = shared.get(res); changed |= resval.join(other.shared.get(res)); } return changed; } @Override public Set<Formula> getPredicates(Action taken) { throw new RuntimeException("Should not be used for this type of state, use getAvoidFormula() instead!"); } protected boolean isAvoidableType(Action taken) { Statement st = taken.getStatement(); if (st == null || taken.getPid() == -1 || st.isLocal() || st.getType() == StatType.END || inAtomicSection() != -1) return false; return true; } @Override public boolean isAvoidable(Action taken) { if(!isAvoidableType(taken)) return false; int pid = taken.getPid(); for (String res : shared.keySet()) { SharedResVal sharedval = shared.get(res); if (!(sharedval.isEmpty(pid))) return true; } return false; } protected void addPredicate(Set<Formula> model, BufVal buf, Statement st) { model.add(AtomicPredicateDictionary.makeAtomicPredicate(buf.writingLabel, st.getLabel())); } public boolean disjPredicates() { return false; } @Override public Formula getAvoidFormula(Action taken) { Formula avoidFormula = Formula.falseValue(); //avoidFormula = avoidFormula.and(Formula.makeDisjunction()); if (!isAvoidableType(taken)) return avoidFormula; Statement st = taken.getStatement(); int pid = taken.getPid(); Formula common = Formula.falseValue(); for (String res : shared.keySet()) { SharedResVal sharedval = shared.get(res); for(BufVal buf : sharedval.buffer[pid].head) { common = common.or(AtomicPredicateDictionary.makeAtomicPredicate(buf.writingLabel, st.getLabel())); } } Formula allSets = Formula.falseValue(); //allSets = allSets.and(Formula.makeDisjunction()); for (String res : shared.keySet()) { //Unfortunately, within a set we need to avoid everything. SharedResVal sharedval = shared.get(res); if (!sharedval.buffer[pid].set.isEmpty()) { Formula setFormula = Formula.trueValue(); for(BufVal buf : sharedval.buffer[pid].set) { Formula disj = Formula.falseValue(); Formula ap = AtomicPredicateDictionary.makeAtomicPredicate(buf.writingLabel, st.getLabel()); disj = disj.or(ap); //System.out.println("DISJ : " + disj); setFormula = setFormula.and(disj); } //System.out.println("setFormula : " + setFormula + " --- " + setFormula.getClass()); //System.out.println("ALLSETS : " + allSets + " --- " + allSets.getClass()); allSets = allSets.or(setFormula); } } avoidFormula = avoidFormula.or(common); avoidFormula = avoidFormula.or(allSets); return avoidFormula; } @Override public ArithValue getShared(String res) { SharedResVal val = shared.get(res); if (val == null) throw new RuntimeException("Local " + res + " not found"); return DeterArithValue.getInstance(val.getGlobalVal()); } }
hetmeter/awmm
fender-sb-bdd/branches/three valued logic branch/fender-sb-bdd/src/fsb/semantics/empeagerpso/EmpEagerAbsState.java
Java
mit
5,589
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jenkins.plugins.pivot.render; import java.util.ArrayList; import java.util.List; /** * 2-dimension matrix utility * @author zijiang */ public final class Matrix2D { private int[][] data; private int rowSize; private int colSize; public Matrix2D(int rowsize, int colsize){ init(rowsize, colsize); } public Matrix2D(int[][] datasource){ throw new UnsupportedOperationException(); } public Matrix2D(List<int[]> datasource){ if(datasource.isEmpty()){ this.init(0, 0); return; } int rowsize = datasource.size(); int colsize = datasource.get(0).length; init(rowsize, colsize); // fill data for(int i = 0 ; i < rowsize; i++){ int[] row = datasource.get(i); for(int j = 0; j < row.length; j++){ set(i, j, row[j]); } } } public Matrix2D transpose(){ Matrix2D m = new Matrix2D(this.colSize, this.rowSize); for(int i = 0; i < m.rowSize; i++){ for(int j = 0; j < m.colSize; j++){ m.set(i, j, this.get(j, i)); } } return m; } // Fill all cells with single value public void unifiy(int value){ for(int i = 0; i < this.rowSize; i++){ for(int j = 0; j < this.colSize; j++){ this.set(i, j, value); } } } public int getRowSize(){ return this.rowSize; } public int getColumnSize(){ return this.colSize; } private void init(int row, int col){ this.rowSize = row; this.colSize = col; this.data = new int[row][col]; } public void set(int rowIndex, int colIndex, int value) { this.data[rowIndex][colIndex] = value; } public int get(int rowIndex, int colIndex){ return this.data[rowIndex][colIndex]; } public void dump(){ for(int i = 0; i < this.getRowSize(); i++){ for(int j = 0; j < this.getColumnSize(); j++){ System.out.print(this.get(i, j)); System.out.print(" "); } System.out.println(); } System.out.println(); } }
gougoujiang/programmable-section
src/main/java/jenkins/plugins/pivot/render/Matrix2D.java
Java
mit
2,516
<?php /** * This file is part of Git-Live * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. * * @category GitCommand * @package Git-Live * @subpackage Core * @author akito<akito-artisan@five-foxes.com> * @author suzunone<suzunone.eleven@gmail.com> * @copyright Project Git Live * @license MIT * @version GIT: $Id\$ * @link https://github.com/Git-Live/git-live * @see https://github.com/Git-Live/git-live */ namespace Tests\GitLive\Command\Hotfix; use App; use GitLive\Application\Application; use JapaneseDate\DateTime; use Tests\GitLive\Tester\CommandTestCase as TestCase; use Tests\GitLive\Tester\CommandTester; use Tests\GitLive\Tester\CommandTestTrait; use Tests\GitLive\Tester\MakeGitTestRepoTrait; /** * @internal * @coversNothing */ class HotfixPushCommandTest extends TestCase { use CommandTestTrait; use MakeGitTestRepoTrait; protected function setUp() { parent::setUp(); $this->execCmdToLocalRepo($this->git_live . ' feature start suzunone_branch'); $this->execCmdToLocalRepo('echo "# new file" > new_text.md'); $this->execCmdToLocalRepo('git add ./'); $this->execCmdToLocalRepo('git commit -am "add new file"'); $this->execCmdToLocalRepo('echo "\n\n * something text" >> README.md'); $this->execCmdToLocalRepo('git add ./'); $this->execCmdToLocalRepo('git commit -am "edit readme"'); $this->execCmdToLocalRepo($this->git_live . ' feature publish'); $this->execCmdToLocalRepo($this->git_live . ' feature start suzunone_branch_2'); $this->execCmdToLocalRepo('git checkout develop'); $this->execCmdToLocalRepo('git merge feature/suzunone_branch'); $this->execCmdToLocalRepo('git push upstream develop'); } /** * @throws \Exception * @covers \GitLive\Application\Application * @covers \GitLive\Command\CommandBase * @covers \GitLive\Command\Hotfix\HotfixPushCommand * @covers \GitLive\Driver\DeployBase * @covers \GitLive\Driver\HotfixDriver * @covers \GitLive\Service\CommandLineKernelService */ public function testExecute() { $this->execCmdToLocalRepo($this->git_live . ' hotfix open unit_test_deploy'); $application = App::make(Application::class); DateTime::setTestNow(DateTime::factory('2018-12-01 22:33:45')); $command = $application->find('hotfix:push'); $commandTester = new CommandTester($command); $commandTester->execute([ 'command' => $command->getName(), // pass arguments to the helper // prefix the key with two dashes when passing options, // e.g: '--some-option' => 'option_value', ]); // the output of the command in the console $output = $commandTester->getDisplay(); dump($output); //$this->assertContains('Already up to date.', $output); //$this->assertContains('new branch', $output); //$this->assertContains('hotfix/unit_test_deploy -> hotfix/unit_test_deploy', $output); $this->assertNotContains('fatal', $output); dump($this->spy); dump(data_get($this->spy, '*.0')); dump($output); $this->assertEquals([ 0 => 'git rev-parse --git-dir 2> /dev/null', 1 => 'git config --get gitlive.deploy.remote', 2 => 'git rev-parse --git-dir 2> /dev/null', 3 => 'git config --get gitlive.branch.develop.name', 4 => 'git rev-parse --git-dir 2> /dev/null', 5 => 'git config --get gitlive.branch.master.name', 6 => 'git rev-parse --git-dir 2> /dev/null', 7 => 'git config --get gitlive.branch.hotfix.prefix.name', 8 => 'git fetch --all', 9 => 'git fetch -p', 10 => 'git fetch upstream', 11 => 'git fetch -p upstream', 12 => 'git fetch deploy', 13 => 'git fetch -p deploy', 14 => 'git remote', 15 => 'git branch -a', 16 => 'git branch -a', 17 => 'git branch', 18 => 'git checkout hotfix/unit_test_deploy', 19 => 'git pull upstream hotfix/unit_test_deploy', 20 => 'git pull deploy hotfix/unit_test_deploy', 21 => 'git status hotfix/unit_test_deploy', 22 => 'git push upstream hotfix/unit_test_deploy', ], data_get($this->spy, '*.0')); $this->assertContains('* hotfix/unit_test_deploy', $this->execCmdToLocalRepo('git branch')); // ... } }
Git-Live/git-live
tests/Tests/GitLive/Command/Hotfix/HotfixPushCommandTest.php
PHP
mit
4,654
package com.jinwen.thread.multithread.synchronize.example2; public class HasSelfPrivateNum { private int num = 0; synchronized public void addI(String username) { try { if (username.equals("a")) { num = 100; System.out.println("a set over"); Thread.sleep(2000); } else { num = 200; System.out.println("b set over"); } System.out.println(username + " num= " + num); } catch (InterruptedException e) { e.printStackTrace(); } } }
jinchen92/JavaBasePractice
src/com/jinwen/thread/multithread/synchronize/example2/HasSelfPrivateNum.java
Java
mit
611
package app_error import "log" func Fatal(err error) { if err != nil { log.Fatal(err) } }
Jurevic/FaceGrinder
pkg/api/v1/helper/app_error/app_error.go
GO
mit
96