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
<?php namespace Mapbender\ActivityIndicatorBundle\Element; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; /** * */ class ActivityIndicatorAdminType extends AbstractType { /** * @inheritdoc */ public function getName() { return 'activityindicator'; } /** * @inheritdoc */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'application' => null )); } /** * @inheritdoc */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('tooltip', 'text', array('required' => false)) ->add('activityClass', 'text', array('required' => false)) ->add('ajaxActivityClass', 'text', array('required' => false)) ->add('tileActivityClass', 'text', array('required' => false)); } }
mapbender/mapbender-activityindicator
src/Mapbender/ActivityIndicatorBundle/Element/ActivityIndicatorAdminType.php
PHP
mit
1,022
/** * The Furnace namespace * * @module furnace * @class Furnace * @static */ import Validation from 'furnace/packages/furnace-validation'; import I18n from 'furnace/packages/furnace-i18n'; import Forms from 'furnace/packages/furnace-forms'; export default { /** * * @property Forms * @type Furnace.Forms */ Forms : Forms, /** * @property I18n * @type Furnace.I18n */ I18n : I18n, /** * @property Validation * @type Furnace.Validation */ Validation: Validation };
ember-furnace/ember-cli-furnace
addon/index.js
JavaScript
mit
503
import cx from 'clsx' import PropTypes from 'prop-types' import React from 'react' import { customPropTypes, getElementType, getUnhandledProps, useKeyOnly } from '../../lib' /** * A placeholder can contain an image. */ function PlaceholderImage(props) { const { className, square, rectangular } = props const classes = cx( useKeyOnly(square, 'square'), useKeyOnly(rectangular, 'rectangular'), 'image', className, ) const rest = getUnhandledProps(PlaceholderImage, props) const ElementType = getElementType(PlaceholderImage, props) return <ElementType {...rest} className={classes} /> } PlaceholderImage.propTypes = { /** An element type to render as (string or function). */ as: PropTypes.elementType, /** Additional classes. */ className: PropTypes.string, /** An image can modify size correctly with responsive styles. */ square: customPropTypes.every([customPropTypes.disallow(['rectangular']), PropTypes.bool]), /** An image can modify size correctly with responsive styles. */ rectangular: customPropTypes.every([customPropTypes.disallow(['square']), PropTypes.bool]), } export default PlaceholderImage
Semantic-Org/Semantic-UI-React
src/elements/Placeholder/PlaceholderImage.js
JavaScript
mit
1,162
(function (angular) { "use strict"; var appFooter = angular.module('myApp.footer', []); appFooter.controller("footerCtrl", ['$scope', function ($scope) { }]); myApp.directive("siteFooter",function(){ return { restrict: 'A', templateUrl:'app/components/footer/footer.html' }; }); } (angular));
kevinczhang/kevinczhang.github.io
src/app/components/footer/footer.js
JavaScript
mit
376
<?php namespace App\Http\Controllers\API\V2; use App\Beacon; use App\Http\Requests\BeaconRequest; use Illuminate\Http\Request; class BeaconController extends Controller { /** * Return a list of items. * * @param Request $request * * @return json */ public function index(Request $request) { return $this->filteredAndOrdered($request, new Beacon())->paginate($this->pageSize); } /** * Save a new item. * * @param Request $request * * @return json */ public function store(BeaconRequest $request) { return response(Beacon::create($request->all()), 201); } /** * Return a single item. * * @param Request $request * @param Beacon $beacon * * @return json */ public function show(Request $request, Beacon $beacon) { return $this->attachResources($request, $beacon); } /** * Update a single item. * * @param BeaconRequest $request * @param Beacon $beacon * * @return json */ public function update(BeaconRequest $request, Beacon $beacon) { $beacon->update($request->all()); return $beacon; } /** * Delete a single item. * * @param Beacon $beacon * * @return empty */ public function destroy(Beacon $beacon) { $beacon->delete(); return response('', 204); } /** * Return a list of deleted items. * * @return json */ public function deleted() { return Beacon::onlyTrashed()->get(); } }
nosuchagency/beacon-bacon
app/Http/Controllers/API/V2/BeaconController.php
PHP
mit
1,627
import {IDetailsService} from '../services/details.service'; class DetailsController implements ng.IComponentController { private detailsService: IDetailsService; private detailsData: any; private previousState: any; constructor($stateParams: any, detailsService: IDetailsService) { console.log('details controller'); console.log("$stateParams.id=", $stateParams.id); console.log("this.previousState=", this.previousState); let id = $stateParams.id; detailsService.searchByIMDbID(id, 'full').then((result) => { console.log("detailsData = ", result.data); this.detailsData = result.data; }); } } export default DetailsController; DetailsController.$inject = ['$stateParams', 'detailsService'];
andyyusydney/open-movie
src/details/details.controller.ts
TypeScript
mit
788
package main import ( "bufio" "fmt" "os" "os/exec" "strings" "sync" ) func checkError(err error, prefix string) { if err != nil { panic(fmt.Sprintf("%s %s", prefix, err.Error())) } } func cleanFeedbackLine(s string) (out string) { out = s out = strings.TrimSpace(out) out = strings.Replace(out, "\r", "", -1) out = strings.Replace(out, "\n", "\\n", -1) return } func runCommand(wg *sync.WaitGroup, resultCollector *ResultCollector, commandIndex int, phase *nodeData, cmd *exec.Cmd) { if wg != nil { defer wg.Done() } defer func() { if r := recover(); r != nil { errMsg := fmt.Sprintf("%s", r) if !phase.ContinueOnFailure { logger.Fatallnf(errMsg) } else { logger.Errorlnf(errMsg) } resultCollector.AppendResult(&result{Cmd: cmd, Successful: false}) } else { resultCollector.AppendResult(&result{Cmd: cmd, Successful: true}) } }() stdout, err := cmd.StdoutPipe() checkError(err, "cmd.StdoutPipe") stderr, err := cmd.StderrPipe() checkError(err, "cmd.StderrPipe") outLines := []string{} stdoutScanner := bufio.NewScanner(stdout) go func() { for stdoutScanner.Scan() { txt := cleanFeedbackLine(stdoutScanner.Text()) outLines = append(outLines, txt) logger.Tracelnf("COMMAND %d STDOUT: %s", commandIndex, txt) } }() errLines := []string{} stderrScanner := bufio.NewScanner(stderr) go func() { for stderrScanner.Scan() { txt := cleanFeedbackLine(stderrScanner.Text()) errLines = append(errLines, txt) logger.Warninglnf("COMMAND %d STDERR: %s", commandIndex, txt) } }() err = cmd.Start() checkError(err, "cmd.Start") err = cmd.Wait() if err != nil { newErr := fmt.Errorf("%s - lines: %s", err.Error(), strings.Join(errLines, "\\n")) outCombined := cleanFeedbackLine(strings.Join(outLines, "\n")) errMsg := fmt.Sprintf("FAILED COMMAND %d. Continue: %t. ERROR: %s. OUT: %s", commandIndex, phase.ContinueOnFailure, newErr.Error(), outCombined) panic(errMsg) } } func runPhase(setup *setup, phaseName string, phase *nodeData) { var wg sync.WaitGroup resultCollector := &ResultCollector{} cmds, err := phase.GetExecCommandsFromSteps(setup.StringVariablesOnly(), setup.Variables) if err != nil { logger.Fatallnf(err.Error()) } if phase.RunParallel { wg.Add(len(cmds)) } logger.Infolnf("Running step %s", phaseName) for ind, c := range cmds { logger.Tracelnf(strings.TrimSpace(fmt.Sprintf(`INDEX %d = %s`, ind, execCommandToDisplayString(c)))) var wgToUse *sync.WaitGroup = nil if phase.RunParallel { wgToUse = &wg go runCommand(wgToUse, resultCollector, ind, phase, c) } else { runCommand(wgToUse, resultCollector, ind, phase, c) } } if phase.RunParallel { wg.Wait() } if resultCollector.FailedCount() == 0 { logger.Infolnf("There were no failures - %d/%d successful", resultCollector.SuccessCount(), resultCollector.TotalCount()) } else { logger.Errorlnf("There were %d/%d failures: ", resultCollector.FailedCount(), resultCollector.TotalCount()) for _, failure := range resultCollector.FailedDisplayList() { logger.Errorlnf("- %s", failure) } } } func main() { logger.Infolnf("Running version '%s'", Version) if len(os.Args) < 2 { logger.Fatallnf("The first command-line argument must be the YAML file path.") } yamlFilePath := os.Args[1] setup, err := ParseYamlFile(yamlFilePath) if err != nil { logger.Fatallnf(err.Error()) } for _, phase := range setup.Phases { runPhase(setup, phase.Name, phase.Data) } }
golang-devops/yaml-script-runner
main.go
GO
mit
3,494
<html> <head> <title>Progmia | Game | Level Selection</title> <link href="<?php echo base_url(); ?>assets/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/levels.css"> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/stars.css"> <script type="text/javascript" src="<?php echo base_url();?>assets/js/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="<?php echo base_url();?>assets/js/bootstrap.min.js""></script> <script type="text/javascript" src="<?php echo base_url();?>assets/js/bootstrap.min.js"></script> <link rel="icon" href="<?php echo base_url(); ?>assets/images/icon_jFd_icon.ico"> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/fonts/font-awesome-4.7.0/css/font-awesome.min.css"> <script type="text/javascript" src="<?php echo base_url();?>assets/js/drag-on.js"></script> </head> <body> <nav id="primary-nav" class="primary-nav"> <div class="container-fluid"> <div class="row" style="display: flex;align-items: center;"> <div class="col-md-3 col-lg-3 col-xs-4 col-sm-4" style="text-align: center;"> <a class="back" href="<?php echo base_url(); ?>Game/MainMenu"><i class="fa fa-arrow-left"></i></a> </div> <div class="col-md-6 col-lg-6 col-xs-4 col-sm-4"> </div> <div class="col-md-3 col-lg-3 col-xs-4 col-sm-4"> <ul class="nav-left"> <li class="music-control"> <button id="playpausebtn" class="playpausebtn"><i class="fa fa-music"></i></button> <input id="volumeslider" class="volumeslider" type="range" min="0" max="100" value="100" step="1"> </li> </ul> </div> </div> </div> </nav> <script> $(document).ready(function(){ $("button.playpausebtn").click(function() { if(jQuery('#playpausebtn').hasClass('paused')){ $("button").removeClass("paused"); } else { $(this).addClass("paused"); } }); $("button#back").click(function() { }); }); var audio, playbtn, mutebtn, seekslider, volumeslider, seeking=false, seekto; function initAudioPlayer(){ audio = new Audio(); audio.src = "<?php echo base_url();?>/assets/sounds/bgm/03 Civil (Explore).mp3"; audio.loop = true; audio.play(); // Set object references playbtn = document.getElementById("playpausebtn"); volumeslider = document.getElementById("volumeslider"); // Add Event Handling playbtn.addEventListener("click",playPause); volumeslider.addEventListener("mousemove", setvolume); // Functions function playPause(){ if(audio.paused){ audio.play(); } else { audio.pause(); } } function setvolume(){ audio.volume = volumeslider.value / 100; } } window.addEventListener("load", initAudioPlayer); </script>
timpquerubin/Progmia
application/views/templates/menu_levels_header.php
PHP
mit
2,910
import base64 try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.3, 2.4 fallback. from django import http, template from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.shortcuts import render_to_response from django.utils.translation import ugettext_lazy, ugettext as _ ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.") LOGIN_FORM_KEY = 'this_is_the_login_form' def _display_login_form(request, error_message=''): request.session.set_test_cookie() return render_to_response('admin/login.html', { 'title': _('Log in'), 'app_path': request.get_full_path(), 'error_message': error_message }, context_instance=template.RequestContext(request)) def staff_member_required(view_func): """ Decorator for views that checks that the user is logged in and is a staff member, displaying the login page if necessary. """ def _checklogin(request, *args, **kwargs): if request.user.is_authenticated() and request.user.is_staff: # The user is valid. Continue to the admin page. return view_func(request, *args, **kwargs) assert hasattr(request, 'session'), "The Django admin requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'." # If this isn't already the login page, display it. if LOGIN_FORM_KEY not in request.POST: if request.POST: message = _("Please log in again, because your session has expired.") else: message = "" return _display_login_form(request, message) # Check that the user accepts cookies. if not request.session.test_cookie_worked(): message = _("Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.") return _display_login_form(request, message) else: request.session.delete_test_cookie() # Check the password. username = request.POST.get('username', None) password = request.POST.get('password', None) user = authenticate(username=username, password=password) if user is None: message = ERROR_MESSAGE if '@' in username: # Mistakenly entered e-mail address instead of username? Look it up. users = list(User.all().filter('email =', username)) if len(users) == 1 and users[0].check_password(password): message = _("Your e-mail address is not your username. Try '%s' instead.") % users[0].username else: # Either we cannot find the user, or if more than 1 # we cannot guess which user is the correct one. message = _("Usernames cannot contain the '@' character.") return _display_login_form(request, message) # The user data is correct; log in the user in and continue. else: if user.is_active and user.is_staff: login(request, user) return http.HttpResponseRedirect(request.get_full_path()) else: return _display_login_form(request, ERROR_MESSAGE) return wraps(view_func)(_checklogin)
isaac-philip/loolu
common/django/contrib/admin/views/decorators.py
Python
mit
3,535
<?php /** * wCMF - wemove Content Management Framework * Copyright (C) 2005-2020 wemove digital solutions GmbH * * Licensed under the terms of the MIT License. * * See the LICENSE file distributed with this work for * additional information. */ namespace wcmf\lib\core; /** * A session that requires clients to send a token for authentication. * * @author ingo herwig <ingo@wemove.com> */ interface TokenBasedSession extends Session { /** * Get the name of the auth token header. * @return String */ public function getHeaderName(); /** * Get the name of the auth token cookie. * @return String */ public function getCookieName(); }
iherwig/wcmf
src/wcmf/lib/core/TokenBasedSession.php
PHP
mit
673
export default function formatList(xs, { ifEmpty = 'нет', joint = ', ' } = {}) { return (!xs || xs.length === 0) ? ifEmpty : xs.join(joint) }
whitescape/react-admin-components
src/ui/format/list.js
JavaScript
mit
147
// $Author: benine $ // $Date$ // $Log$ // Contains the mismatch class for afin #ifndef MISMATCH_H #define MISMATCH_H //////////////////////////////////////////////\ // Mismatch Class: ////////////////////////////> ////////////////////////////////////////////// // // Mismatch object, contains all classes, methods, data, and data references necessary for processing mismatches for contig fusion // There will be only one Process object needed per iteration of this program class Mismatch{ private: double score; int length; int index_i; int index_j; int end_i; int end_j; public: Mismatch(); Mismatch( double score, int length, int index_i, int index_j, int end_i, int end_j ); // set mismatch score void set_score( double score ); // set length void set_length( int length ); // set index_i void set_index_i( int index ); // set index_j void set_index_j( int index ); // set index void set_indices( int index_i, int index_j ); // set end_i void set_end_i( int end_i ); // set end_j void set_end_j( int end_j ); // return mismatch score double get_score(); // return length int get_length(); // return index i int get_index_i(); // return index j int get_index_j(); // return end_i int get_end_i(); // return end_j int get_end_j(); }; #endif
mrmckain/Fast-Plast
afin/mismatch.hpp
C++
mit
1,405
<?php /* * 注意:此文件由itpl_engine编译型模板引擎编译生成。 * 如果您的模板要进行修改,请修改 templates/default/shop/map.html * 如果您的模型要进行修改,请修改 models/shop/map.php * * 修改完成之后需要您进入后台重新编译,才会重新生成。 * 如果您开启了debug模式运行,那么您可以省去上面这一步,但是debug模式每次都会判断程序是否更新,debug模式只适合开发调试。 * 如果您正式运行此程序时,请切换到service模式运行! * * 如您有问题请到官方论坛()提问,谢谢您的支持。 */ ?><?php /* * 此段代码由debug模式下生成运行,请勿改动! * 如果debug模式下出错不能再次自动编译时,请进入后台手动编译! */ /* debug模式运行生成代码 开始 */ if (!function_exists("tpl_engine")) { require("foundation/ftpl_compile.php"); } if(filemtime("templates/default/shop/map.html") > filemtime(__file__) || (file_exists("models/shop/map.php") && filemtime("models/shop/map.php") > filemtime(__file__)) ) { tpl_engine("default", "shop/map.html", 1); include(__file__); } else { /* debug模式运行生成代码 结束 */ ?><?php if (!$IWEB_SHOP_IN) { trigger_error('Hacking attempt'); } /* 公共信息处理 header, left, footer */ require("foundation/module_shop.php"); require("foundation/module_users.php"); require("foundation/module_shop_category.php"); //引入语言包 $s_langpackage = new shoplp; $i_langpackage = new indexlp; /* 数据库操作 */ dbtarget('r', $dbServs); $dbo = new dbex(); /* 定义文件表 */ $t_shop_info = $tablePreStr . "shop_info"; $t_users = $tablePreStr . "users"; $t_shop_category = $tablePreStr . "shop_category"; $t_shop_categories = $tablePreStr . "shop_categories"; /* 商铺信息处理 */ $SHOP = get_shop_info($dbo, $t_shop_info, $shop_id); //商铺分类 $shop_rank = $SHOP['shop_categories']; $shop_rank_arr = get_categories_rank($shop_rank, $dbo, $t_shop_categories); if ($shop_rank_arr) { $num = count($shop_rank_arr) - 1; } if (!$SHOP) { trigger_error($s_langpackage->s_shop_error); }//无此商铺 if ($SHOP['lock_flg']) { trigger_error($s_langpackage->s_shop_locked); }//锁定 if ($SHOP['open_flg']) { trigger_error($s_langpackage->s_shop_close); }//关闭 $sql = "select rank_id,user_name,last_login_time from $t_users where user_id='" . $SHOP['user_id'] . "'"; $ranks = $dbo->getRow($sql); $SHOP['rank_id'] = $ranks[0]; /* 文章头部信息 */ $header = get_shop_header($s_langpackage->s_shop_index, $SHOP); //$nav_selected=3; ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title><?php echo $header['title']; ?></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/> <meta name="keywords" content="<?php echo $header['keywords']; ?>"/> <meta name="description" content="<?php echo $header['description']; ?>"/> <base href="<?php echo $baseUrl; ?>"/> <link href="skin/<?php echo $SYSINFO['templates']; ?>/css/shop.css" rel="stylesheet" type="text/css"/> <link href="skin/<?php echo $SYSINFO['templates']; ?>/css/import.css" type="text/css" rel="stylesheet"/> <link href="skin/<?php echo $SYSINFO['templates']; ?>/css/article.css" type="text/css" rel="stylesheet"/> <link href="skin/<?php echo $SYSINFO['templates']; ?>/css/shop_<?php echo $SHOP['shop_template']; ?>.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="skin/<?php echo $SYSINFO['templates']; ?>/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="skin/<?php echo $SYSINFO['templates']; ?>/js/changeStyle.js"></script> <style> <?php if($SHOP['shop_template_img']){?> #shopHeader { background: transparent url(<?php echo $SHOP['shop_template_img'];?>) no-repeat scroll 0 0 #4A9DA5; } <?php }?> </style> </head> <body onload="initialize()" onunload="GUnload()"> <!-- wrapper --> <div id="wrapper"> <?php require("shop/index_header.php"); ?> <!-- contents --> <div id="contents" class="clearfix"> <div id="pkz"> <?php echo $s_langpackage->s_this_location; ?><a href="index.php"><?php echo $SYSINFO['sys_name']; ?></a> &gt; <a href="shop_list.php"><?php echo $s_langpackage->s_shop_category; ?></a> &gt; <?php foreach ($shop_rank_arr as $k => $value) { ?> <?php if ($num == $k) { ?> <a href=""><?php echo $value['cat_name']; ?></a> <?php } else { ?> <a href=""><?php echo $value['cat_name']; ?></a> &gt; <?php } ?> <?php } ?> </div> <div id="shopHeader" class=" mg12b clearfix"> <p class="shopName"><?php echo $SHOP['shop_name']; ?></p> <div class="shop_nav"> <?php require("shop/menu.php"); ?> </div> </div> <?php require("shop/left.php"); ?> <div id="rightCloumn"> <div class="bigpart"> <div class="shop_notice top10"> <div class="c_t"> <div class="c_t_l left"></div> <div class="c_t_r right"></div> <h2><a href="javascript:;"><?php echo $s_langpackage->s_shop_seat; ?></a><span></span></h2> </div> <div class="c_m"> <div id="map_canvas" style="width: 688px; height: 500px"></div> </div> <div class="c_bt"> <div class="c_bt_l left"></div> <div class="c_bt_r right"></div> </div> </div> </div> </div> </div> <?php require("shop/index_footer.php"); ?> <script src="http://maps.google.com/maps?file=api&v=2.x&key=<?php echo $SYSINFO['map_key']; ?>" type="text/javascript"></script> <script type="text/javascript"> var now_x = <?php echo $SHOP['map_x'];?>; var now_y = <?php echo $SHOP['map_y'];?>; var now_zoom = <?php echo $SHOP['map_zoom'];?>; function initialize() { if (GBrowserIsCompatible()) { var map = new GMap2(document.getElementById("map_canvas")); var center = new GLatLng(now_y, now_x); map.setCenter(center, now_zoom); var point = new GLatLng(now_y, now_x); var marker = new GMarker(point); map.addOverlay(marker); map.addControl(new GSmallMapControl()); map.addControl(new GMapTypeControl()); } } </script> </body> </html><?php } ?>
hisuley/gds
trunk/shop/map.php
PHP
mit
7,143
package com.example; import java.util.Set; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; public class ServletContainerInitializerImpl implements ServletContainerInitializer { @Override public void onStartup(final Set<Class<?>> c, final ServletContext ctx) throws ServletException { final AnnotationConfigWebApplicationContext wac = new AnnotationConfigWebApplicationContext(); wac.register(MvcConfig.class); wac.refresh(); final DispatcherServlet servlet = new DispatcherServlet(wac); final ServletRegistration.Dynamic reg = ctx.addServlet("dispatcher", servlet); reg.addMapping("/*"); } }
backpaper0/sandbox
springmvc-study-no-xml/src/main/java/com/example/ServletContainerInitializerImpl.java
Java
mit
923
import React from 'react'; const EditHero = props => { if (props.selectedHero) { return ( <div> <div className="editfields"> <div> <label>id: </label> {props.addingHero ? <input type="number" name="id" placeholder="id" value={props.selectedHero.id} onChange={props.onChange} /> : <label className="value"> {props.selectedHero.id} </label>} </div> <div> <label>name: </label> <input name="name" value={props.selectedHero.name} placeholder="name" onChange={props.onChange} /> </div> <div> <label>saying: </label> <input name="saying" value={props.selectedHero.saying} placeholder="saying" onChange={props.onChange} /> </div> </div> <button onClick={props.onCancel}>Cancel</button> <button onClick={props.onSave}>Save</button> </div> ); } else { return <div />; } }; export default EditHero;
Ryan-ZL-Lin/react-cosmosdb
src/components/EditHero.js
JavaScript
mit
1,289
#guimporter.py import sys from PySide import QtGui, QtCore, QtWebKit Signal = QtCore.Signal
lazunin/stclient
guimporter.py
Python
mit
92
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("SearchForANumber")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SearchForANumber")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("fe6220fa-63b8-4168-9867-f466b571c2a5")] // 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")]
davidvaleff/ProgrammingFundamentals-Sept2017
06.Lists/Exercises/SearchForANumber/Properties/AssemblyInfo.cs
C#
mit
1,403
'use strict'; var redis = require('redis') , xtend = require('xtend') , hyperquest = require('hyperquest') ; module.exports = FetchAndCache; /** * Creates a fetchncache instance. * * #### redis opts * * - **opts.redis.host** *{number=}* host at which redis is listening, defaults to `127.0.0.1` * - **opts.redis.port** *{string=}* port at which redis is listening, defaults to `6379` * * #### service opts * * - **opts.service.url** *{string=}* url at which to reach the service * * @name fetchncache * @function * @param {Object=} opts * @param {Object=} opts.redis redis options passed straight to [redis](https://github.com/mranney/node_redis) (@see above) * @param {Object=} opts.service options specifying how to reach the service that provides the data (@see above) * @param {number=} opts.expire the default number of seconds after which to expire a resource from the redis cache (defaults to 15mins) * @return {Object} fetchncache instance */ function FetchAndCache(opts) { if (!(this instanceof FetchAndCache)) return new FetchAndCache(opts); opts = opts || {}; var redisOpts = xtend({ port: 6379, host: '127.0.0.1' }, opts.redis) , serviceOpts = xtend({ url: 'http://127.0.0.1' }, opts.service) this._defaultExpire = opts.expire || 15 * 60 // 15min this._serviceOpts = serviceOpts; this._markCached = opts.markCached !== false; this._client = redis.createClient(redisOpts.port, redisOpts.host, redisOpts) } var proto = FetchAndCache.prototype; /** * Fetches the resource, probing the redis cache first and falling back to the service. * If a transform function is provided (@see opts), that is applied to the result before returning or caching it. * When fetched from the service it is added to the redis cached according to the provided options. * * @name fetcncache::fetch * @function * @param {string} uri path to the resource, i.e. `/reource1?q=1234` * @param {Object=} opts configure caching and transformation behavior for this particular resource * @param {number=} opts.expire overrides default expire for this particular resource * @param {function=} opts.transform specify the transform function to be applied, default: `function (res} { return res }` * @param {function} cb called back with an error or the transformed resource */ proto.fetch = function (uri, opts, cb) { var self = this; if (!self._client) return cb(new Error('fetchncache was stopped and can no longer be used to fetch data')); if (typeof opts === 'function') { cb = opts; opts = null; } opts = xtend({ expire: self._defaultExpire, transform: function (x) { return x } }, opts); self._client.get(uri, function (err, res) { if (err) return cb(err); if (res) return cb(null, res, true); self._get(uri, function (err, res) { if (err) return cb(err); self._cache(uri, res, opts, cb); }) }); } /** * Stops the redis client in order to allow exiting the application. * At this point this fetchncache instance becomes unusable and throws errors on any attempts to use it. * * @name fetchncache::stop * @function * @param {boolean=} force will make it more aggressive about ending the underlying redis client (default: false) */ proto.stop = function (force) { if (!this._client) throw new Error('fetchncache was stopped previously and cannot be stopped again'); if (force) this._client.end(); else this._client.unref(); this._client = null; } /** * Clears the entire redis cache, so use with care. * Mainly useful for testing or to ensure that all resources get refreshed. * * @name fetchncache::clearCache * @function * @return {Object} fetchncache instance */ proto.clearCache = function () { if (!this._client) throw new Error('fetchncache was stopped previously and cannot be cleared'); this._client.flushdb(); return this; } proto._get = function (uri, cb) { var body = ''; var url = this._serviceOpts.url + uri; console.log('url', url); hyperquest .get(url) .on('error', cb) .on('data', function (d) { body += d.toString() }) .on('end', function () { cb(null, body) }) } proto._cache = function (uri, res, opts, cb) { var self = this; var val; try { val = opts.transform(res); } catch (e) { return cb(e); } // assuming that value is now a string we use set to add it self._client.set(uri, val, function (err) { if (err) return cb(err); self._client.expire(uri, opts.expire, function (err) { if (err) return cb(err); cb(null, val); }) }); }
thlorenz/fetchncache
index.js
JavaScript
mit
4,638
package org.blendee.jdbc; /** * プレースホルダを持つ SQL 文と、プレースホルダにセットする値を持つものを表すインターフェイスです。 * @author 千葉 哲嗣 */ public interface ComposedSQL extends ChainPreparedStatementComplementer { /** * このインスタンスが持つ SQL 文を返します。 * @return SQL 文 */ String sql(); /** * {@link PreparedStatementComplementer} を入れ替えた新しい {@link ComposedSQL} を生成します。 * @param complementer 入れ替える {@link PreparedStatementComplementer} * @return 同じ SQL を持つ、別のインスタンス */ default ComposedSQL reproduce(PreparedStatementComplementer complementer) { var sql = sql(); return new ComposedSQL() { @Override public String sql() { return sql; } @Override public int complement(int done, BPreparedStatement statement) { complementer.complement(statement); return Integer.MIN_VALUE; } }; } /** * {@link ChainPreparedStatementComplementer} を入れ替えた新しい {@link ComposedSQL} を生成します。 * @param complementer 入れ替える {@link ChainPreparedStatementComplementer} * @return 同じ SQL を持つ、別のインスタンス */ default ComposedSQL reproduce(ChainPreparedStatementComplementer complementer) { var sql = sql(); return new ComposedSQL() { @Override public String sql() { return sql; } @Override public int complement(int done, BPreparedStatement statement) { return complementer.complement(done, statement); } }; } }
blendee/blendee
src/main/java/org/blendee/jdbc/ComposedSQL.java
Java
mit
1,611
<TS language="es_419" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Haga clic para editar la dirección o etiqueta</translation> </message> <message> <source>Create a new address</source> <translation>Crear una nueva dirección</translation> </message> <message> <source>&amp;New</source> <translation>&amp;New</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Copia la dirección seleccionada al portapapeles del sistema</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Borrar la dirección que esta seleccionada en la lista</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportar los datos de la actual tabla hacia un archivo</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>Seleccione la dirección a la que enviará las monedas</translation> </message> <message> <source>Choose the address to receive coins with</source> <translation>Seleccione la dirección con la que recibirá las monedas</translation> </message> <message> <source>Sending addresses</source> <translation>Enviando direcciones</translation> </message> <message> <source>Receiving addresses</source> <translation>Recibiendo direcciones</translation> </message> <message> <source>These are your Pandacoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Estas son sus direcciones de Pandacoin para enviar sus pagos. Siempre revise el monto y la dirección recibida antes de enviar monedas.</translation> </message> </context> <context> <name>AddressTableModel</name> </context> <context> <name>AskPassphraseDialog</name> </context> <context> <name>BanTableModel</name> </context> <context> <name>BitcoinGUI</name> </context> <context> <name>CoinControlDialog</name> </context> <context> <name>EditAddressDialog</name> </context> <context> <name>FreespaceChecker</name> </context> <context> <name>HelpMessageDialog</name> </context> <context> <name>Intro</name> </context> <context> <name>ModalOverlay</name> </context> <context> <name>OpenURIDialog</name> </context> <context> <name>OptionsDialog</name> </context> <context> <name>OverviewPage</name> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> </context> <context> <name>QObject</name> </context> <context> <name>QObject::QObject</name> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> </context> <context> <name>ReceiveCoinsDialog</name> </context> <context> <name>ReceiveRequestDialog</name> </context> <context> <name>RecentRequestsTableModel</name> </context> <context> <name>SendCoinsDialog</name> </context> <context> <name>SendCoinsEntry</name> </context> <context> <name>SendConfirmationDialog</name> </context> <context> <name>ShutdownWindow</name> </context> <context> <name>SignVerifyMessageDialog</name> </context> <context> <name>SplashScreen</name> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> </context> <context> <name>TransactionDescDialog</name> </context> <context> <name>TransactionTableModel</name> </context> <context> <name>TransactionView</name> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> </context> <context> <name>WalletView</name> <message> <source>Export the data in the current tab to a file</source> <translation>Exportar los datos de la actual tabla hacia un archivo</translation> </message> </context> <context> <name>bitcoin-core</name> </context> </TS>
DigitalPandacoin/pandacoin
src/qt/locale/bitcoin_es_419.ts
TypeScript
mit
4,495
package com.github.sixro.minihabits.core.infrastructure.domain; import java.util.*; import com.badlogic.gdx.Preferences; import com.github.sixro.minihabits.core.domain.*; public class PreferencesBasedRepository implements Repository { private final Preferences prefs; public PreferencesBasedRepository(Preferences prefs) { super(); this.prefs = prefs; } @Override public Set<MiniHabit> findAll() { String text = prefs.getString("mini_habits"); if (text == null || text.trim().isEmpty()) return new LinkedHashSet<MiniHabit>(); return newMiniHabits(text); } @Override public void add(MiniHabit miniHabit) { Set<MiniHabit> list = findAll(); list.add(miniHabit); prefs.putString("mini_habits", asString(list)); prefs.flush(); } @Override public void update(Collection<MiniHabit> list) { Set<MiniHabit> currentList = findAll(); currentList.removeAll(list); currentList.addAll(list); prefs.putString("mini_habits", asString(currentList)); prefs.flush(); } @Override public void updateProgressDate(DateAtMidnight aDate) { prefs.putLong("last_feedback_timestamp", aDate.getTime()); prefs.flush(); } @Override public DateAtMidnight lastFeedbackDate() { long timestamp = prefs.getLong("last_feedback_timestamp"); if (timestamp == 0L) return null; return DateAtMidnight.from(timestamp); } private Set<MiniHabit> newMiniHabits(String text) { String[] parts = text.split(","); Set<MiniHabit> ret = new LinkedHashSet<MiniHabit>(); for (String part: parts) ret.add(newMiniHabit(part)); return ret; } private MiniHabit newMiniHabit(String part) { int indexOfColon = part.indexOf(':'); String label = part.substring(0, indexOfColon); Integer daysInProgress = Integer.parseInt(part.substring(indexOfColon +1)); MiniHabit habit = new MiniHabit(label, daysInProgress); return habit; } private String asString(Collection<MiniHabit> list) { StringBuilder b = new StringBuilder(); int i = 0; for (MiniHabit each: list) { b.append(each.label() + ":" + each.daysInProgress()); if (i < list.size()-1) b.append(','); i++; } return b.toString(); } }
sixro/minihabits
core/src/main/java/com/github/sixro/minihabits/core/infrastructure/domain/PreferencesBasedRepository.java
Java
mit
2,241
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); let _ = require('lodash'); let async = require('async'); const pip_services3_commons_node_1 = require("pip-services3-commons-node"); const pip_services3_facade_node_1 = require("pip-services3-facade-node"); class RolesOperationsV1 extends pip_services3_facade_node_1.FacadeOperations { constructor() { super(); this._dependencyResolver.put('roles', new pip_services3_commons_node_1.Descriptor('pip-services-roles', 'client', '*', '*', '1.0')); } setReferences(references) { super.setReferences(references); this._rolesClient = this._dependencyResolver.getOneRequired('roles'); } getUserRolesOperation() { return (req, res) => { this.getUserRoles(req, res); }; } grantUserRolesOperation() { return (req, res) => { this.grantUserRoles(req, res); }; } revokeUserRolesOperation() { return (req, res) => { this.revokeUserRoles(req, res); }; } getUserRoles(req, res) { let userId = req.route.params.user_id; this._rolesClient.getRolesById(null, userId, this.sendResult(req, res)); } grantUserRoles(req, res) { let userId = req.route.params.user_id; let roles = req.body; this._rolesClient.grantRoles(null, userId, roles, this.sendResult(req, res)); } revokeUserRoles(req, res) { let userId = req.route.params.user_id; let roles = req.body; this._rolesClient.revokeRoles(null, userId, roles, this.sendResult(req, res)); } } exports.RolesOperationsV1 = RolesOperationsV1; //# sourceMappingURL=RolesOperationsV1.js.map
pip-services-users/pip-facade-users-node
obj/src/operations/version1/RolesOperationsV1.js
JavaScript
mit
1,730
require_relative 'rules_factory_common' FactoryBot.define do factory :priority_bills, parent: :answers do factory :S6_H1_missed_payment_low, traits: [:country, :S6_H1_missed_payment_low_answers] factory :S6_H2_council_tax_severe, traits: [:country, :S6_H2_tax_severe_answers] factory :S6_H2_domestic_rates_severe, traits: [:country, :S6_H2_tax_severe_answers] factory :S6_H2_council_tax_temp_worried, traits: [:country, :S6_H2_tax_temp_worried_answers] factory :S6_H2_domestic_rates_temp_worried, traits: [:country, :S6_H2_tax_temp_worried_answers] factory :S6_H2_council_tax_temp_normal, traits: [:country, :S6_H2_tax_temp_normal_answers] factory :S6_H2_domestic_rates_temp_normal, traits: [:country, :S6_H2_tax_temp_normal_answers] factory :S6_H2_council_tax_no_change, traits: [:country, :S6_H2_tax_no_change_answers] factory :S6_H2_domestic_rates_no_change, traits: [:country, :S6_H2_tax_no_change_answers] factory :S6_H3_gas_electricity_severe, traits: [:country, :S6_H3_gas_electricity_severe_answers] factory :S6_H3_gas_electricity_temp_worried, traits: [:country, :S6_H3_gas_electricity_temp_worried_answers] factory :S6_H3_gas_electricity_temp_normal, traits: [:country, :S6_H3_gas_electricity_temp_normal_answers] factory :S6_H3_gas_electricity_no_change, traits: [:country, :S6_H3_gas_electricity_no_change_answers] factory :S6_H4_dmp_hmrc_severe, traits: [:country, :S6_H4_dmp_hmrc_severe_answers] factory :S6_H4_dmp_hmrc_temp_worried, traits: [:country, :S6_H4_dmp_hmrc_temp_worried_answers] factory :S6_H4_dmp_hmrc_temp_normal, traits: [:country, :S6_H4_dmp_hmrc_temp_normal_answers] factory :S6_H4_dmp_hmrc_no_change, traits: [:country, :S6_H4_dmp_hmrc_no_change_answers] factory :S6_H5_tv_licence_severe, traits: [:country, :S6_H5_tv_licence_severe_answers] factory :S6_H5_tv_licence_temp_worried, traits: [:country, :S6_H5_tv_licence_temp_worried_answers] factory :S6_H5_tv_licence_temp_normal, traits: [:country, :S6_H5_tv_licence_temp_normal_answers] factory :S6_H5_tv_licence_no_change, traits: [:country, :S6_H5_tv_licence_no_change_answers] factory :S6_H6_income_tax_severe, traits: [:country, :S6_H6_income_tax_severe_answers] factory :S6_H6_income_tax_temp_worried, traits: [:country, :S6_H6_income_tax_temp_worried_answers] factory :S6_H6_income_tax_temp_normal, traits: [:country, :S6_H6_income_tax_temp_normal_answers] factory :S6_H6_income_tax_no_change, traits: [:country, :S6_H6_income_tax_no_change_answers] factory :S6_H7_child_maintenance_severe, traits: [:country, :S6_H7_child_maintenance_severe_answers] factory :S6_H7_child_maintenance_temp_worried, traits: [:country, :S6_H7_child_maintenance_temp_worried_answers] factory :S6_H7_child_maintenance_temp_normal, traits: [:country, :S6_H7_child_maintenance_temp_normal_answers] factory :S6_H7_child_maintenance_no_change, traits: [:country, :S6_H7_child_maintenance_no_change_answers] factory :S6_H8_court_fines_severe, traits: [:country, :S6_H8_court_fines_severe_answers] factory :S6_H8_court_fines_temp_worried, traits: [:country, :S6_H8_court_fines_temp_worried_answers] factory :S6_H8_court_fines_temp_normal, traits: [:country, :S6_H8_court_fines_temp_normal_answers] factory :S6_H8_court_fines_temp_normal_ni, traits: [:country, :S6_H8_court_fines_temp_normal_ni_answers] factory :S6_H8_court_fines_temp_normal_scotland, traits: [:country, :S6_H8_court_fines_temp_normal_scotland_answers] factory :S6_H8_court_fines_no_change, traits: [:country, :S6_H8_court_fines_no_change_answers] factory :S6_H9_hire_purchase_severe, traits: [:country, :S6_H9_hire_purchase_severe_answers] factory :S6_H9_hire_purchase_temp_worried, traits: [:country, :S6_H9_hire_purchase_temp_worried_answers] factory :S6_H9_hire_purchase_temp_normal, traits: [:country, :S6_H9_hire_purchase_temp_normal_answers] factory :S6_H9_hire_purchase_no_change, traits: [:country, :S6_H9_hire_purchase_no_change_answers] factory :S6_H10_car_park_severe, traits: [:country, :S6_H10_car_park_severe_answers] factory :S6_H10_car_park_temp_worried, traits: [:country, :S6_H10_car_park_temp_worried_answers] factory :S6_H10_car_park_temp_normal, traits: [:country, :S6_H10_car_park_temp_normal_answers] factory :S6_H10_car_park_temp_normal_ni, traits: [:country, :S6_H10_car_park_temp_normal_ni_answers] factory :S6_H10_car_park_temp_normal_scotland, traits: [:country, :S6_H10_car_park_temp_normal_scotland_answers] factory :S6_H10_car_park_no_change, traits: [:country, :S6_H10_car_park_no_change_answers] trait :S6_H1_missed_payment_low_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', [], nil) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H2_tax_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a1'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H2_tax_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a1'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H2_tax_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a1'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H2_tax_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a1'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H3_gas_electricity_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a2'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H3_gas_electricity_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a2'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H3_gas_electricity_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a2'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H3_gas_electricity_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a2'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H4_dmp_hmrc_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a3'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H4_dmp_hmrc_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a3'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H4_dmp_hmrc_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a3'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H4_dmp_hmrc_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a3'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H5_tv_licence_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a4'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H5_tv_licence_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a4'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H5_tv_licence_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a4'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H5_tv_licence_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a4'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H6_income_tax_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a5'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H6_income_tax_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a5'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H6_income_tax_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a5'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H6_income_tax_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a5'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H7_child_maintenance_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a6'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H7_child_maintenance_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a6'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H7_child_maintenance_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a6'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H7_child_maintenance_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a6'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_temp_normal_ni_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_temp_normal_scotland_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H9_hire_purchase_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a8'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H9_hire_purchase_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a8'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H9_hire_purchase_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a8'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H9_hire_purchase_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a8'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_temp_normal_ni_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_temp_normal_scotland_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'],[] ) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end end end
moneyadviceservice/frontend
features/factories/money_navigator/priority_bills_rules.rb
Ruby
mit
33,882
var config = require('../lib/config')(); var Changeset = require('./Changeset'); var queries = require('./queries'); var helpers = require('../helpers'); require('../validators'); var validate = require('validate.js'); var errors = require('../errors'); var pgPromise = helpers.pgPromise; var promisifyQuery = helpers.promisifyQuery; var changesets = {}; module.exports = changesets; var pgURL = config.PostgresURL; changesets.search = function(params) { var parseError = validateParams(params); if (parseError) { return Promise.reject(new errors.ParseError(parseError)); } var searchQuery = queries.getSearchQuery(params); var countQuery = queries.getCountQuery(params); console.log('searchQ', searchQuery); console.log('countQ', countQuery); return pgPromise(pgURL) .then(function (pg) { var query = promisifyQuery(pg.client); var searchProm = query(searchQuery.text, searchQuery.values); var countProm = query(countQuery.text, countQuery.values); return Promise.all([searchProm, countProm]) .then(function (r) { pg.done(); return r; }) .catch(function (e) { pg.done(); return Promise.reject(e); }); }) .then(processSearchResults); }; changesets.get = function(id) { if (!validate.isNumber(parseInt(id, 10))) { return Promise.reject(new errors.ParseError('Changeset id must be a number')); } var changesetQuery = queries.getChangesetQuery(id); var changesetCommentsQuery = queries.getChangesetCommentsQuery(id); return pgPromise(pgURL) .then(function (pg) { var query = promisifyQuery(pg.client); var changesetProm = query(changesetQuery.text, changesetQuery.values); var changesetCommentsProm = query(changesetCommentsQuery.text, changesetCommentsQuery.values); return Promise.all([changesetProm, changesetCommentsProm]) .then(function (results) { pg.done(); return results; }) .catch(function (e) { pg.done(); return Promise.reject(e); }); }) .then(function (results) { var changesetResult = results[0]; if (changesetResult.rows.length === 0) { return Promise.reject(new errors.NotFoundError('Changeset not found')); } var changeset = new Changeset(results[0].rows[0], results[1].rows); return changeset.getGeoJSON(); }); }; function processSearchResults(results) { var searchResult = results[0]; var countResult = results[1]; var changesetsArray = searchResult.rows.map(function (row) { var changeset = new Changeset(row); return changeset.getGeoJSON(); }); var count; if (countResult.rows.length > 0) { count = countResult.rows[0].count; } else { count = 0; } var featureCollection = { 'type': 'FeatureCollection', 'features': changesetsArray, 'total': count }; return featureCollection; } function validateParams(params) { var constraints = { 'from': { 'presence': false, 'datetime': true }, 'to': { 'presence': false, 'datetime': true }, 'bbox': { 'presence': false, 'bbox': true } }; var errs = validate(params, constraints); if (errs) { var errMsg = Object.keys(errs).map(function(key) { return errs[key][0]; }).join(', '); return errMsg; } return null; }
mapbox/osm-comments-api
changesets/index.js
JavaScript
mit
3,841
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.Windows.Automation.Peers; using System.Windows.Media; using System.Windows.Threading; using MS.Internal.KnownBoxes; namespace System.Windows.Controls.Primitives { /// <summary> /// StatusBar is a visual indicator of the operational status of an application and/or /// its components running in a window. StatusBar control consists of a series of zones /// on a band that can display text, graphics, or other rich content. The control can /// group items within these zones to emphasize relational similarities or functional /// connections. The StatusBar can accommodate multiple sets of UI or functionality that /// can be chosen even within the same application. /// </summary> [StyleTypedProperty(Property = "ItemContainerStyle", StyleTargetType = typeof(StatusBarItem))] public class StatusBar : ItemsControl { //------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------- #region Constructors static StatusBar() { DefaultStyleKeyProperty.OverrideMetadata(typeof(StatusBar), new FrameworkPropertyMetadata(typeof(StatusBar))); _dType = DependencyObjectType.FromSystemTypeInternal(typeof(StatusBar)); IsTabStopProperty.OverrideMetadata(typeof(StatusBar), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox)); ItemsPanelTemplate template = new ItemsPanelTemplate(new FrameworkElementFactory(typeof(DockPanel))); template.Seal(); ItemsPanelProperty.OverrideMetadata(typeof(StatusBar), new FrameworkPropertyMetadata(template)); } #endregion #region Public Properties /// <summary> /// DependencyProperty for ItemContainerTemplateSelector property. /// </summary> public static readonly DependencyProperty ItemContainerTemplateSelectorProperty = MenuBase.ItemContainerTemplateSelectorProperty.AddOwner( typeof(StatusBar), new FrameworkPropertyMetadata(new DefaultItemContainerTemplateSelector())); /// <summary> /// DataTemplateSelector property which provides the DataTemplate to be used to create an instance of the ItemContainer. /// </summary> public ItemContainerTemplateSelector ItemContainerTemplateSelector { get { return (ItemContainerTemplateSelector)GetValue(ItemContainerTemplateSelectorProperty); } set { SetValue(ItemContainerTemplateSelectorProperty, value); } } /// <summary> /// DependencyProperty for UsesItemContainerTemplate property. /// </summary> public static readonly DependencyProperty UsesItemContainerTemplateProperty = MenuBase.UsesItemContainerTemplateProperty.AddOwner(typeof(StatusBar)); /// <summary> /// UsesItemContainerTemplate property which says whether the ItemContainerTemplateSelector property is to be used. /// </summary> public bool UsesItemContainerTemplate { get { return (bool)GetValue(UsesItemContainerTemplateProperty); } set { SetValue(UsesItemContainerTemplateProperty, value); } } #endregion //------------------------------------------------------------------- // // Protected Methods // //------------------------------------------------------------------- #region Protected Methods private object _currentItem; /// <summary> /// Return true if the item is (or is eligible to be) its own ItemUI /// </summary> protected override bool IsItemItsOwnContainerOverride(object item) { bool ret = (item is StatusBarItem) || (item is Separator); if (!ret) { _currentItem = item; } return ret; } protected override DependencyObject GetContainerForItemOverride() { object currentItem = _currentItem; _currentItem = null; if (UsesItemContainerTemplate) { DataTemplate itemContainerTemplate = ItemContainerTemplateSelector.SelectTemplate(currentItem, this); if (itemContainerTemplate != null) { object itemContainer = itemContainerTemplate.LoadContent(); if (itemContainer is StatusBarItem || itemContainer is Separator) { return itemContainer as DependencyObject; } else { throw new InvalidOperationException(SR.Get(SRID.InvalidItemContainer, this.GetType().Name, typeof(StatusBarItem).Name, typeof(Separator).Name, itemContainer)); } } } return new StatusBarItem(); } /// <summary> /// Prepare the element to display the item. This may involve /// applying styles, setting bindings, etc. /// </summary> protected override void PrepareContainerForItemOverride(DependencyObject element, object item) { base.PrepareContainerForItemOverride(element, item); Separator separator = element as Separator; if (separator != null) { bool hasModifiers; BaseValueSourceInternal vs = separator.GetValueSource(StyleProperty, null, out hasModifiers); if (vs <= BaseValueSourceInternal.ImplicitReference) separator.SetResourceReference(StyleProperty, SeparatorStyleKey); separator.DefaultStyleKey = SeparatorStyleKey; } } /// <summary> /// Determine whether the ItemContainerStyle/StyleSelector should apply to the container /// </summary> /// <returns>false if item is a Separator, otherwise return true</returns> protected override bool ShouldApplyItemContainerStyle(DependencyObject container, object item) { if (item is Separator) { return false; } else { return base.ShouldApplyItemContainerStyle(container, item); } } #endregion #region Accessibility /// <summary> /// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>) /// </summary> protected override AutomationPeer OnCreateAutomationPeer() { return new StatusBarAutomationPeer(this); } #endregion #region DTypeThemeStyleKey // Returns the DependencyObjectType for the registered ThemeStyleKey's default // value. Controls will override this method to return approriate types. internal override DependencyObjectType DTypeThemeStyleKey { get { return _dType; } } private static DependencyObjectType _dType; #endregion DTypeThemeStyleKey #region ItemsStyleKey /// <summary> /// Resource Key for the SeparatorStyle /// </summary> public static ResourceKey SeparatorStyleKey { get { return SystemResourceKey.StatusBarSeparatorStyleKey; } } #endregion } }
mind0n/hive
Cache/Libs/net46/wpf/src/Framework/System/Windows/Controls/Primitives/StatusBar.cs
C#
mit
7,812
// John Meyer // CSE 271 F // Dr. Angel Bravo import java.util.Scanner; import java.io.*; /** * Copies a file with line numbers prefixed to every line */ public class Lab2InputOutput { public static void main(String[] args) throws Exception { // Define variables Scanner keyboardReader = new Scanner(System.in); String inputFileName; String outputFileName; // Check arguments if (args.length == 0) { System.out.println("Usage: java Lab2InputOutput /path/to/file"); return; } inputFileName = args[0]; // Find input file File inputFile = new File(inputFileName); Scanner fileInput = new Scanner(inputFile); // Get output file name System.out.print("Output File Name: "); outputFileName = keyboardReader.next(); File outputFile = new File(outputFileName); // Start copying PrintWriter fileOutput = new PrintWriter(outputFile); String lineContent; for (int lineNumber = 1; fileInput.hasNext(); lineNumber++) { lineContent = fileInput.nextLine(); fileOutput.printf("/* %d */ %s%n", lineNumber, lineContent); } fileInput.close(); fileOutput.close(); } // end method main } // end class Lab2InputOutput
0x326/academic-code-portfolio
2016-2021 Miami University/CSE 271 Introduction to Object-Oriented Programming/Lab02/src/main/java/Lab2InputOutput.java
Java
mit
1,334
module ClassifyCluster VERSION = "0.4.17" end
socialcast/classify_cluster
lib/classify_cluster/version.rb
Ruby
mit
48
// Copyright 2013 The Changkong Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package dmt const VersionNo = "20131207" /* 图片分类 */ type PictureCategory struct { Created string `json:"created"` Modified string `json:"modified"` ParentId int `json:"parent_id"` PictureCategoryId int `json:"picture_category_id"` PictureCategoryName string `json:"picture_category_name"` Position int `json:"position"` Type string `json:"type"` } /* 图片 */ type Picture struct { ClientType string `json:"client_type"` Created string `json:"created"` Deleted string `json:"deleted"` Md5 string `json:"md5"` Modified string `json:"modified"` PictureCategoryId int `json:"picture_category_id"` PictureId int `json:"picture_id"` PicturePath string `json:"picture_path"` Pixel string `json:"pixel"` Referenced bool `json:"referenced"` Sizes int `json:"sizes"` Status string `json:"status"` Title string `json:"title"` Uid int `json:"uid"` } /* 图片空间的用户信息获取,包括订购容量等 */ type UserInfo struct { AvailableSpace string `json:"available_space"` FreeSpace string `json:"free_space"` OrderExpiryDate string `json:"order_expiry_date"` OrderSpace string `json:"order_space"` RemainingSpace string `json:"remaining_space"` UsedSpace string `json:"used_space"` WaterMark string `json:"water_mark"` } /* 搜索返回的结果类 */ type TOPSearchResult struct { Paginator *TOPPaginator `json:"paginator"` VideoItems struct { VideoItem []*VideoItem `json:"video_item"` } `json:"video_items"` } /* 分页信息 */ type TOPPaginator struct { CurrentPage int `json:"current_page"` IsLastPage bool `json:"is_last_page"` PageSize int `json:"page_size"` TotalResults int `json:"total_results"` } /* 视频 */ type VideoItem struct { CoverUrl string `json:"cover_url"` Description string `json:"description"` Duration int `json:"duration"` IsOpenToOther bool `json:"is_open_to_other"` State int `json:"state"` Tags []string `json:"tags"` Title string `json:"title"` UploadTime string `json:"upload_time"` UploaderId int `json:"uploader_id"` VideoId int `json:"video_id"` VideoPlayInfo *VideoPlayInfo `json:"video_play_info"` } /* 视频播放信息 */ type VideoPlayInfo struct { AndroidpadUrl string `json:"androidpad_url"` AndroidpadV23Url *AndroidVlowUrl `json:"androidpad_v23_url"` AndroidphoneUrl string `json:"androidphone_url"` AndroidphoneV23Url *AndroidVlowUrl `json:"androidphone_v23_url"` FlashUrl string `json:"flash_url"` IpadUrl string `json:"ipad_url"` IphoneUrl string `json:"iphone_url"` WebUrl string `json:"web_url"` } /* android phone和pad播放的mp4文件类。适用2.3版本的Android。 */ type AndroidVlowUrl struct { Hd string `json:"hd"` Ld string `json:"ld"` Sd string `json:"sd"` Ud string `json:"ud"` }
yaofangou/open_taobao
api/dmt/dmt_structs.go
GO
mit
3,394
"use strict"; let datafire = require('datafire'); let openapi = require('./openapi.json'); module.exports = datafire.Integration.fromOpenAPI(openapi, "azure_sql_failoverdatabases");
DataFire/Integrations
integrations/generated/azure_sql_failoverdatabases/index.js
JavaScript
mit
181
package generated.zcsclient.mail; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for messagePartHitInfo complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="messagePartHitInfo"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="e" type="{urn:zimbraMail}emailInfo" minOccurs="0"/> * &lt;element name="su" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="sf" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="s" type="{http://www.w3.org/2001/XMLSchema}long" /> * &lt;attribute name="d" type="{http://www.w3.org/2001/XMLSchema}long" /> * &lt;attribute name="cid" type="{http://www.w3.org/2001/XMLSchema}int" /> * &lt;attribute name="mid" type="{http://www.w3.org/2001/XMLSchema}int" /> * &lt;attribute name="ct" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="part" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "messagePartHitInfo", propOrder = { "e", "su" }) public class testMessagePartHitInfo { protected testEmailInfo e; protected String su; @XmlAttribute(name = "id") protected String id; @XmlAttribute(name = "sf") protected String sf; @XmlAttribute(name = "s") protected Long s; @XmlAttribute(name = "d") protected Long d; @XmlAttribute(name = "cid") protected Integer cid; @XmlAttribute(name = "mid") protected Integer mid; @XmlAttribute(name = "ct") protected String ct; @XmlAttribute(name = "name") protected String name; @XmlAttribute(name = "part") protected String part; /** * Gets the value of the e property. * * @return * possible object is * {@link testEmailInfo } * */ public testEmailInfo getE() { return e; } /** * Sets the value of the e property. * * @param value * allowed object is * {@link testEmailInfo } * */ public void setE(testEmailInfo value) { this.e = value; } /** * Gets the value of the su property. * * @return * possible object is * {@link String } * */ public String getSu() { return su; } /** * Sets the value of the su property. * * @param value * allowed object is * {@link String } * */ public void setSu(String value) { this.su = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the sf property. * * @return * possible object is * {@link String } * */ public String getSf() { return sf; } /** * Sets the value of the sf property. * * @param value * allowed object is * {@link String } * */ public void setSf(String value) { this.sf = value; } /** * Gets the value of the s property. * * @return * possible object is * {@link Long } * */ public Long getS() { return s; } /** * Sets the value of the s property. * * @param value * allowed object is * {@link Long } * */ public void setS(Long value) { this.s = value; } /** * Gets the value of the d property. * * @return * possible object is * {@link Long } * */ public Long getD() { return d; } /** * Sets the value of the d property. * * @param value * allowed object is * {@link Long } * */ public void setD(Long value) { this.d = value; } /** * Gets the value of the cid property. * * @return * possible object is * {@link Integer } * */ public Integer getCid() { return cid; } /** * Sets the value of the cid property. * * @param value * allowed object is * {@link Integer } * */ public void setCid(Integer value) { this.cid = value; } /** * Gets the value of the mid property. * * @return * possible object is * {@link Integer } * */ public Integer getMid() { return mid; } /** * Sets the value of the mid property. * * @param value * allowed object is * {@link Integer } * */ public void setMid(Integer value) { this.mid = value; } /** * Gets the value of the ct property. * * @return * possible object is * {@link String } * */ public String getCt() { return ct; } /** * Sets the value of the ct property. * * @param value * allowed object is * {@link String } * */ public void setCt(String value) { this.ct = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the part property. * * @return * possible object is * {@link String } * */ public String getPart() { return part; } /** * Sets the value of the part property. * * @param value * allowed object is * {@link String } * */ public void setPart(String value) { this.part = value; } }
nico01f/z-pec
ZimbraSoap/src/wsdl-test/generated/zcsclient/mail/testMessagePartHitInfo.java
Java
mit
7,074
/* * Copyright (c) 2013 Adobe Systems Incorporated. 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. * */ /*jslint vars: true, plusplus: true, devel: true, node: true, nomen: true, indent: 4, maxerr: 50 */ /*global expect, describe, it, beforeEach, afterEach */ "use strict"; var ExtensionsDomain = require("../ExtensionManagerDomain"), fs = require("fs-extra"), async = require("async"), path = require("path"); var testFilesDirectory = path.join(path.dirname(module.filename), "..", // node "..", // extensibility "..", // src "..", // brackets "test", "spec", "extension-test-files"), installParent = path.join(path.dirname(module.filename), "extensions"), installDirectory = path.join(installParent, "good"), disabledDirectory = path.join(installParent, "disabled"); var basicValidExtension = path.join(testFilesDirectory, "basic-valid-extension.zip"), basicValidExtension2 = path.join(testFilesDirectory, "basic-valid-extension-2.0.zip"), missingMain = path.join(testFilesDirectory, "missing-main.zip"), oneLevelDown = path.join(testFilesDirectory, "one-level-extension-master.zip"), incompatibleVersion = path.join(testFilesDirectory, "incompatible-version.zip"), invalidZip = path.join(testFilesDirectory, "invalid-zip-file.zip"), missingPackageJSON = path.join(testFilesDirectory, "missing-package-json.zip"); describe("Package Installation", function () { var standardOptions = { disabledDirectory: disabledDirectory, apiVersion: "0.22.0" }; beforeEach(function (done) { fs.mkdirs(installDirectory, function (err) { fs.mkdirs(disabledDirectory, function (err) { done(); }); }); }); afterEach(function (done) { fs.remove(installParent, function (err) { done(); }); }); function checkPaths(pathsToCheck, callback) { var existsCalls = []; pathsToCheck.forEach(function (path) { existsCalls.push(function (callback) { fs.exists(path, async.apply(callback, null)); }); }); async.parallel(existsCalls, function (err, results) { expect(err).toBeNull(); results.forEach(function (result, num) { expect(result ? "" : pathsToCheck[num] + " does not exist").toEqual(""); }); callback(); }); } it("should validate the package", function (done) { ExtensionsDomain._cmdInstall(missingMain, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); var errors = result.errors; expect(errors.length).toEqual(1); done(); }); }); it("should work fine if all is well", function (done) { ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) { var extensionDirectory = path.join(installDirectory, "basic-valid-extension"); expect(err).toBeNull(); var errors = result.errors; expect(errors.length).toEqual(0); expect(result.metadata.name).toEqual("basic-valid-extension"); expect(result.name).toEqual("basic-valid-extension"); expect(result.installedTo).toEqual(extensionDirectory); var pathsToCheck = [ path.join(extensionDirectory, "package.json"), path.join(extensionDirectory, "main.js") ]; checkPaths(pathsToCheck, done); }); }); // This is mildly redundant. the validation check should catch this. // But, I wanted to be sure that the install function doesn't try to // do anything with the file before validation. it("should fail for missing package", function (done) { ExtensionsDomain._cmdInstall(path.join(testFilesDirectory, "NOT A PACKAGE"), installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); var errors = result.errors; expect(errors.length).toEqual(1); expect(errors[0][0]).toEqual("NOT_FOUND_ERR"); done(); }); }); it("should install to the disabled directory if it's already installed", function (done) { ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); expect(result.disabledReason).toBeNull(); ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); expect(result.disabledReason).toEqual("ALREADY_INSTALLED"); var extensionDirectory = path.join(disabledDirectory, "basic-valid-extension"); var pathsToCheck = [ path.join(extensionDirectory, "package.json"), path.join(extensionDirectory, "main.js") ]; checkPaths(pathsToCheck, done); }); }); }); it("should yield an error if there's no disabled directory set", function (done) { ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, { apiVersion: "0.22.0" }, function (err, result) { expect(err.message).toEqual("MISSING_REQUIRED_OPTIONS"); done(); }); }); it("should yield an error if there's no apiVersion set", function (done) { ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, { disabledDirectory: disabledDirectory }, function (err, result) { expect(err.message).toEqual("MISSING_REQUIRED_OPTIONS"); done(); }); }); it("should overwrite the disabled directory copy if there's already one", function (done) { ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); expect(result.disabledReason).toBeNull(); ExtensionsDomain._cmdInstall(basicValidExtension, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); expect(result.disabledReason).toEqual("ALREADY_INSTALLED"); ExtensionsDomain._cmdInstall(basicValidExtension2, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); expect(result.disabledReason).toEqual("ALREADY_INSTALLED"); var extensionDirectory = path.join(disabledDirectory, "basic-valid-extension"); fs.readJson(path.join(extensionDirectory, "package.json"), function (err, packageObj) { expect(err).toBeNull(); expect(packageObj.version).toEqual("2.0.0"); done(); }); }); }); }); }); it("should derive the name from the zip if there's no package.json", function (done) { ExtensionsDomain._cmdInstall(missingPackageJSON, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); expect(result.disabledReason).toBeNull(); var extensionDirectory = path.join(installDirectory, "missing-package-json"); var pathsToCheck = [ path.join(extensionDirectory, "main.js") ]; checkPaths(pathsToCheck, done); }); }); it("should install with the common prefix removed", function (done) { ExtensionsDomain._cmdInstall(oneLevelDown, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); var extensionDirectory = path.join(installDirectory, "one-level-extension"); var pathsToCheck = [ path.join(extensionDirectory, "main.js"), path.join(extensionDirectory, "package.json"), path.join(extensionDirectory, "lib", "foo.js") ]; checkPaths(pathsToCheck, done); }); }); it("should disable extensions that are not compatible with the current Brackets API", function (done) { ExtensionsDomain._cmdInstall(incompatibleVersion, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); expect(result.disabledReason).toEqual("API_NOT_COMPATIBLE"); var extensionDirectory = path.join(disabledDirectory, "incompatible-version"); var pathsToCheck = [ path.join(extensionDirectory, "main.js"), path.join(extensionDirectory, "package.json") ]; checkPaths(pathsToCheck, done); }); }); it("should not have trouble with invalid zip files", function (done) { ExtensionsDomain._cmdInstall(invalidZip, installDirectory, standardOptions, function (err, result) { expect(err).toBeNull(); expect(result.errors.length).toEqual(1); done(); }); }); });
L0g1k/quickfire-old
src/extensibility/node/spec/Installation.spec.js
JavaScript
mit
10,734
#include "stdafx.h" #include "Renderer.h" #include "RenderMethod_PhongPoint_CG.h" RenderMethod_PhongPoint_CG::RenderMethod_PhongPoint_CG(class Renderer *r) { ASSERT(r, "Null pointer: r"); renderer = r; useCG = true; } bool RenderMethod_PhongPoint_CG::isSupported() const { return areShadersAvailable(); } void RenderMethod_PhongPoint_CG::setupShader(CGcontext &cg, CGprofile &_cgVertexProfile, CGprofile &_cgFragmentProfile) { RenderMethod::setupShader(cg, _cgVertexProfile, _cgFragmentProfile); createVertexProgram(cg, FileName("data/shaders/cg/phong_point.vp.cg")); createFragmentProgram(cg, FileName("data/shaders/cg/phong_point.fp.cg")); // Vertex program parameters cgMVP = getVertexProgramParameter (cg, "MVP"); cgView = getVertexProgramParameter (cg, "View"); cgLightPos = getVertexProgramParameter (cg, "LightPos"); cgCameraPos = getVertexProgramParameter (cg, "CameraPos"); cgTexture = getFragmentProgramParameter(cg, "tex0"); cgKa = getFragmentProgramParameter(cg, "Ka"); cgKd = getFragmentProgramParameter(cg, "Kd"); cgKs = getFragmentProgramParameter(cg, "Ks"); cgShininess = getFragmentProgramParameter(cg, "shininess"); cgkC = getFragmentProgramParameter(cg, "kC"); cgkL = getFragmentProgramParameter(cg, "kL"); cgkQ = getFragmentProgramParameter(cg, "kQ"); } void RenderMethod_PhongPoint_CG::renderPass(RENDER_PASS pass) { switch (pass) { case OPAQUE_PASS: pass_opaque(); break; default: return; } } void RenderMethod_PhongPoint_CG::pass_opaque() { CHECK_GL_ERROR(); // Setup state glPushAttrib(GL_ALL_ATTRIB_BITS); glColor4fv(white); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); glEnable(GL_TEXTURE_2D); // Setup client state glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); // Render the geometry chunks renderChunks(); // Restore client state glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); // Restore settings glPopAttrib(); CHECK_GL_ERROR(); } void RenderMethod_PhongPoint_CG::setShaderData(const GeometryChunk &gc) { const Renderer::Light &light0 = renderer->getLight(); ASSERT(light0.type == Renderer::Light::POINT, "point lights only pls"); mat4 MI = (gc.transformation).inverse(); // world -> object projection // Set the position of the light (in object-space) vec3 LightPosObj = MI.transformVector(light0.position); cgGLSetParameter3fv(cgLightPos, LightPosObj); // Set the position of the camera (in object-space) vec3 CameraPosWld = renderer->getCamera().getPosition(); vec3 CameraPosObj = MI.transformVector(CameraPosWld); cgGLSetParameter3fv(cgCameraPos, CameraPosObj); // Set the light properties cgGLSetParameter1fv(cgkC, &light0.kC); cgGLSetParameter1fv(cgkL, &light0.kL); cgGLSetParameter1fv(cgkQ, &light0.kQ); // Set the material properties cgGLSetParameter4fv(cgKa, gc.material.Ka); cgGLSetParameter4fv(cgKd, gc.material.Kd); cgGLSetParameter4fv(cgKs, gc.material.Ks); cgGLSetParameter1fv(cgShininess, &gc.material.shininess); // Everything else cgGLSetStateMatrixParameter(cgMVP, CG_GL_MODELVIEW_PROJECTION_MATRIX, CG_GL_MATRIX_IDENTITY); cgGLSetStateMatrixParameter(cgView, CG_GL_MODELVIEW_MATRIX, CG_GL_MATRIX_IDENTITY); }
foxostro/CheeseTesseract
src/RenderMethod_PhongPoint_CG.cpp
C++
mit
3,567
class AddOriginalMd5ChecksumToVideos < ActiveRecord::Migration def change add_column :videos, :original_md5_checksum, :string, :limit => 40 end end
pr0d1r2/myvod
db/migrate/20130824090308_add_original_md5_checksum_to_videos.rb
Ruby
mit
156
import ReactIdSwiper from './ReactIdSwiper'; // Types export { ReactIdSwiperProps, ReactIdSwiperRenderProps, SelectableElement, SwiperInstance, WrappedElementType, ReactIdSwiperChildren, SwiperModuleName, SwiperRefNode } from './types'; // React-id-swiper export default ReactIdSwiper;
kidjp85/react-id-swiper
src/index.ts
TypeScript
mit
304
# -*- coding: utf-8 -*- # @Author: karthik # @Date: 2016-12-10 21:40:07 # @Last Modified by: chandan # @Last Modified time: 2016-12-11 12:55:27 from models.portfolio import Portfolio from models.company import Company from models.position import Position import tenjin from tenjin.helpers import * import wikipedia import matplotlib.pyplot as plt from data_helpers import * from stock_data import * import BeautifulSoup as bs import urllib2 import re from datetime import date as dt engine = tenjin.Engine(path=['templates']) # info fetch handler def send_info_handler(bot, update, args): args = list(parse_args(args)) if len(args) == 0 or "portfolio" in [arg.lower() for arg in args] : send_portfolio_info(bot, update) else: info_companies = get_companies(args) send_companies_info(bot, update, info_companies) # get portfolio function def send_portfolio_info(bot, update): print "Userid: %d requested portfolio information" %(update.message.chat_id) context = { 'positions': Portfolio.instance.positions, 'wallet_value': Portfolio.instance.wallet_value, } html_str = engine.render('portfolio_info.pyhtml', context) bot.sendMessage(parse_mode="HTML", chat_id=update.message.chat_id, text=html_str) # get companies information def send_companies_info(bot, update, companies): print "Userid: requested information for following companies %s" %','.join([c.name for c in companies]) for company in companies: context = { 'company': company, 'current_price': get_current_price(company), 'description': wikipedia.summary(company.name.split()[0], sentences=2) } wiki_page = wikipedia.page(company.name.split()[0]) html_page = urllib2.urlopen(wiki_page.url) soup = bs.BeautifulSoup(html_page) img_url = 'http:' + soup.find('td', { "class" : "logo" }).find('img')['src'] bot.sendPhoto(chat_id=update.message.chat_id, photo=img_url) html_str = engine.render('company_template.pyhtml', context) bot.sendMessage(parse_mode="HTML", chat_id=update.message.chat_id, text=html_str) symbols = [c.symbol for c in companies] if len(symbols) >= 2: symbol_string = ", ".join(symbols[:-1]) + " and " + symbols[-1] else: symbol_string = symbols[0] last_n_days = 10 if len(companies) < 4: create_graph(companies, last_n_days) history_text = ''' Here's the price history for {} for the last {} days '''.format(symbol_string, last_n_days) bot.sendMessage(chat_id=update.message.chat_id, text=history_text) bot.sendPhoto(chat_id=update.message.chat_id, photo=open("plots/temp.png",'rb')) def create_graph(companies, timedel): fig, ax = plt.subplots() for company in companies: dates, lookback_prices = get_lookback_prices(company, timedel) # dates = [i.strftime('%d/%m') for i in dates] h = ax.plot(dates, lookback_prices, label=company.symbol) ax.legend() plt.xticks(rotation=45) plt.savefig('plots/temp.png')
coders-creed/botathon
src/info/fetch_info.py
Python
mit
2,889
using System; using System.Collections.Generic; using System.Html; namespace wwtlib { public class PlotTile : Tile { bool topDown = true; protected PositionTexture[] bounds; protected bool backslash = false; List<PositionTexture> vertexList = null; List<Triangle>[] childTriangleList = null; protected float[] demArray; protected void ComputeBoundingSphere() { InitializeGrids(); TopLeft = bounds[0 + 3 * 0].Position.Copy(); BottomRight = bounds[2 + 3 * 2].Position.Copy(); TopRight = bounds[2 + 3 * 0].Position.Copy(); BottomLeft = bounds[0 + 3 * 2].Position.Copy(); CalcSphere(); } public override void RenderPart(RenderContext renderContext, int part, double opacity, bool combine) { if (renderContext.gl != null) { //todo draw in WebGL } else { if (part == 0) { foreach(Star star in stars) { double radDec = 25 / Math.Pow(1.6, star.Magnitude); Planets.DrawPointPlanet(renderContext, star.Position, radDec, star.Col, false); } } } } WebFile webFile; public override void RequestImage() { if (!Downloading && !ReadyToRender) { Downloading = true; webFile = new WebFile(Util.GetProxiedUrl(this.URL)); webFile.OnStateChange = FileStateChange; webFile.Send(); } } public void FileStateChange() { if(webFile.State == StateType.Error) { Downloading = false; ReadyToRender = false; errored = true; RequestPending = false; TileCache.RemoveFromQueue(this.Key, true); } else if(webFile.State == StateType.Received) { texReady = true; Downloading = false; errored = false; ReadyToRender = texReady && (DemReady || !demTile); RequestPending = false; TileCache.RemoveFromQueue(this.Key, true); LoadData(webFile.GetText()); } } List<Star> stars = new List<Star>(); private void LoadData(string data) { string[] rows = data.Replace("\r\n","\n").Split("\n"); bool firstRow = true; PointType type = PointType.Move; Star star = null; foreach (string row in rows) { if (firstRow) { firstRow = false; continue; } if (row.Trim().Length > 5) { star = new Star(row); star.Position = Coordinates.RADecTo3dAu(star.RA, star.Dec, 1); stars.Add(star); } } } public override bool IsPointInTile(double lat, double lng) { if (Level == 0) { return true; } if (Level == 1) { if ((lng >= 0 && lng <= 90) && (tileX == 0 && tileY == 1)) { return true; } if ((lng > 90 && lng <= 180) && (tileX == 1 && tileY == 1)) { return true; } if ((lng < 0 && lng >= -90) && (tileX == 0 && tileY == 0)) { return true; } if ((lng < -90 && lng >= -180) && (tileX == 1 && tileY == 0)) { return true; } return false; } if (!this.DemReady || this.DemData == null) { return false; } Vector3d testPoint = Coordinates.GeoTo3dDouble(-lat, lng); bool top = IsLeftOfHalfSpace(TopLeft.Copy(), TopRight.Copy(), testPoint); bool right = IsLeftOfHalfSpace(TopRight.Copy(), BottomRight.Copy(), testPoint); bool bottom = IsLeftOfHalfSpace(BottomRight.Copy(), BottomLeft.Copy(), testPoint); bool left = IsLeftOfHalfSpace(BottomLeft.Copy(), TopLeft.Copy(), testPoint); if (top && right && bottom && left) { // showSelected = true; return true; } return false; ; } private bool IsLeftOfHalfSpace(Vector3d pntA, Vector3d pntB, Vector3d pntTest) { pntA.Normalize(); pntB.Normalize(); Vector3d cross = Vector3d.Cross(pntA, pntB); double dot = Vector3d.Dot(cross, pntTest); return dot < 0; } private void InitializeGrids() { vertexList = new List<PositionTexture>(); childTriangleList = new List<Triangle>[4]; childTriangleList[0] = new List<Triangle>(); childTriangleList[1] = new List<Triangle>(); childTriangleList[2] = new List<Triangle>(); childTriangleList[3] = new List<Triangle>(); bounds = new PositionTexture[9]; if (Level > 0) { // Set in constuctor now //ToastTile parent = (ToastTile)TileCache.GetTile(level - 1, x / 2, y / 2, dataset, null); if (Parent == null) { Parent = TileCache.GetTile(Level - 1, tileX / 2, tileY / 2, dataset, null); } PlotTile parent = (PlotTile)Parent; int xIndex = tileX % 2; int yIndex = tileY % 2; if (Level > 1) { backslash = parent.backslash; } else { backslash = xIndex == 1 ^ yIndex == 1; } bounds[0 + 3 * 0] = parent.bounds[xIndex + 3 * yIndex].Copy(); bounds[1 + 3 * 0] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * yIndex]); bounds[2 + 3 * 0] = parent.bounds[xIndex + 1 + 3 * yIndex].Copy(); bounds[0 + 3 * 1] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]); if (backslash) { bounds[1 + 3 * 1] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); } else { bounds[1 + 3 * 1] = Midpoint(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]); } bounds[2 + 3 * 1] = Midpoint(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); bounds[0 + 3 * 2] = parent.bounds[xIndex + 3 * (yIndex + 1)].Copy(); bounds[1 + 3 * 2] = Midpoint(parent.bounds[xIndex + 3 * (yIndex + 1)], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]); bounds[2 + 3 * 2] = parent.bounds[xIndex + 1 + 3 * (yIndex + 1)].Copy(); bounds[0 + 3 * 0].Tu = 0*uvMultiple; bounds[0 + 3 * 0].Tv = 0 * uvMultiple; bounds[1 + 3 * 0].Tu = .5f * uvMultiple; bounds[1 + 3 * 0].Tv = 0 * uvMultiple; bounds[2 + 3 * 0].Tu = 1 * uvMultiple; bounds[2 + 3 * 0].Tv = 0 * uvMultiple; bounds[0 + 3 * 1].Tu = 0 * uvMultiple; bounds[0 + 3 * 1].Tv = .5f * uvMultiple; bounds[1 + 3 * 1].Tu = .5f * uvMultiple; bounds[1 + 3 * 1].Tv = .5f * uvMultiple; bounds[2 + 3 * 1].Tu = 1 * uvMultiple; bounds[2 + 3 * 1].Tv = .5f * uvMultiple; bounds[0 + 3 * 2].Tu = 0 * uvMultiple; bounds[0 + 3 * 2].Tv = 1 * uvMultiple; bounds[1 + 3 * 2].Tu = .5f * uvMultiple; bounds[1 + 3 * 2].Tv = 1 * uvMultiple; bounds[2 + 3 * 2].Tu = 1 * uvMultiple; bounds[2 + 3 * 2].Tv = 1 * uvMultiple; } else { bounds[0 + 3 * 0] = PositionTexture.Create(0, -1, 0, 0, 0); bounds[1 + 3 * 0] = PositionTexture.Create(0, 0, 1, .5f, 0); bounds[2 + 3 * 0] = PositionTexture.Create(0, -1, 0, 1, 0); bounds[0 + 3 * 1] = PositionTexture.Create(-1, 0, 0, 0, .5f); bounds[1 + 3 * 1] = PositionTexture.Create(0, 1, 0, .5f, .5f); bounds[2 + 3 * 1] = PositionTexture.Create(1, 0, 0, 1, .5f); bounds[0 + 3 * 2] = PositionTexture.Create(0, -1, 0, 0, 1); bounds[1 + 3 * 2] = PositionTexture.Create(0, 0, -1, .5f, 1); bounds[2 + 3 * 2] = PositionTexture.Create(0, -1, 0, 1, 1); // Setup default matrix of points. } } private PositionTexture Midpoint(PositionTexture positionNormalTextured, PositionTexture positionNormalTextured_2) { Vector3d a1 = Vector3d.Lerp(positionNormalTextured.Position, positionNormalTextured_2.Position, .5f); Vector2d a1uv = Vector2d.Lerp(Vector2d.Create(positionNormalTextured.Tu, positionNormalTextured.Tv), Vector2d.Create(positionNormalTextured_2.Tu, positionNormalTextured_2.Tv), .5f); a1.Normalize(); return PositionTexture.CreatePos(a1, a1uv.X, a1uv.Y); } int subDivisionLevel = 4; bool subDivided = false; public override bool CreateGeometry(RenderContext renderContext) { if (GeometryCreated) { return true; } GeometryCreated = true; base.CreateGeometry(renderContext); return true; } public PlotTile() { } public static PlotTile Create(int level, int xc, int yc, Imageset dataset, Tile parent) { PlotTile temp = new PlotTile(); temp.Parent = parent; temp.Level = level; temp.tileX = xc; temp.tileY = yc; temp.dataset = dataset; temp.topDown = !dataset.BottomsUp; if (temp.tileX != (int)xc) { Script.Literal("alert('bad')"); } //temp.ComputeQuadrant(); if (dataset.MeanRadius != 0) { temp.DemScaleFactor = dataset.MeanRadius; } else { if (dataset.DataSetType == ImageSetType.Earth) { temp.DemScaleFactor = 6371000; } else { temp.DemScaleFactor = 3396010; } } temp.ComputeBoundingSphere(); return temp; } public override void CleanUp(bool removeFromParent) { base.CleanUp(removeFromParent); if (vertexList != null) { vertexList = null; } if (childTriangleList != null) { childTriangleList = null; } subDivided = false; demArray = null; } } }
juoni/wwt-web-client
HTML5SDK/wwtlib/PlotTile.cs
C#
mit
11,749
<?php /** * This file is part of the browscap-json-cache package. * * (c) Thomas Mueller <mimmi20@live.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types = 1); namespace Browscap\Cache; use BrowscapPHP\Cache\BrowscapCacheInterface; use WurflCache\Adapter\AdapterInterface; /** * a cache proxy to be able to use the cache adapters provided by the WurflCache package * * @category Browscap-PHP * * @copyright Copyright (c) 1998-2014 Browser Capabilities Project * * @version 3.0 * * @license http://www.opensource.org/licenses/MIT MIT License * * @see https://github.com/browscap/browscap-php/ */ final class JsonCache implements BrowscapCacheInterface { /** * The cache livetime in seconds. * * @var int */ public const CACHE_LIVETIME = 315360000; // ~10 years (60 * 60 * 24 * 365 * 10) /** * Path to the cache directory * * @var \WurflCache\Adapter\AdapterInterface */ private $cache; /** * Detected browscap version (read from INI file) * * @var int */ private $version; /** * Release date of the Browscap data (read from INI file) * * @var string */ private $releaseDate; /** * Type of the Browscap data (read from INI file) * * @var string */ private $type; /** * Constructor class, checks for the existence of (and loads) the cache and * if needed updated the definitions * * @param \WurflCache\Adapter\AdapterInterface $adapter * @param int $updateInterval */ public function __construct(AdapterInterface $adapter, $updateInterval = self::CACHE_LIVETIME) { $this->cache = $adapter; $this->cache->setExpiration($updateInterval); } /** * Gets the version of the Browscap data * * @return int|null */ public function getVersion(): ?int { if (null === $this->version) { $success = true; $version = $this->getItem('browscap.version', false, $success); if (null !== $version && $success) { $this->version = (int) $version; } } return $this->version; } /** * Gets the release date of the Browscap data * * @return string */ public function getReleaseDate(): string { if (null === $this->releaseDate) { $success = true; $releaseDate = $this->getItem('browscap.releaseDate', false, $success); if (null !== $releaseDate && $success) { $this->releaseDate = $releaseDate; } } return $this->releaseDate; } /** * Gets the type of the Browscap data * * @return string|null */ public function getType(): ?string { if (null === $this->type) { $success = true; $type = $this->getItem('browscap.type', false, $success); if (null !== $type && $success) { $this->type = $type; } } return $this->type; } /** * Get an item. * * @param string $cacheId * @param bool $withVersion * @param bool|null $success * * @return mixed Data on success, null on failure */ public function getItem(string $cacheId, bool $withVersion = true, ?bool &$success = null) { if ($withVersion) { $cacheId .= '.' . $this->getVersion(); } if (!$this->cache->hasItem($cacheId)) { $success = false; return null; } $success = null; $data = $this->cache->getItem($cacheId, $success); if (!$success) { $success = false; return null; } if (!property_exists($data, 'content')) { $success = false; return null; } $success = true; return $data->content; } /** * save the content into an php file * * @param string $cacheId The cache id * @param mixed $content The content to store * @param bool $withVersion * * @return bool whether the file was correctly written to the disk */ public function setItem(string $cacheId, $content, bool $withVersion = true): bool { $data = new \stdClass(); // Get the whole PHP code $data->content = $content; if ($withVersion) { $cacheId .= '.' . $this->getVersion(); } // Save and return return $this->cache->setItem($cacheId, $data); } /** * Test if an item exists. * * @param string $cacheId * @param bool $withVersion * * @return bool */ public function hasItem(string $cacheId, bool $withVersion = true): bool { if ($withVersion) { $cacheId .= '.' . $this->getVersion(); } return $this->cache->hasItem($cacheId); } /** * Remove an item. * * @param string $cacheId * @param bool $withVersion * * @return bool */ public function removeItem(string $cacheId, bool $withVersion = true): bool { if ($withVersion) { $cacheId .= '.' . $this->getVersion(); } return $this->cache->removeItem($cacheId); } /** * Flush the whole storage * * @return bool */ public function flush(): bool { return $this->cache->flush(); } }
mimmi20/browscap-json-cache
src/JsonCache.php
PHP
mit
5,684
(function () { "use strict"; require('futures/forEachAsync'); var fs = require('fs'), crypto = require('crypto'), path = require('path'), exec = require('child_process').exec, mime = require('mime'), FileStat = require('filestat'), dbaccess = require('../dbaccess'), utils = require('../utils'), hashAlgo = "md5"; function readFile(filePath, callback) { var readStream, hash = crypto.createHash(hashAlgo); readStream = fs.createReadStream(filePath); readStream.on('data', function (data) { hash.update(data); }); readStream.on('error', function (err) { console.log("Read Error: " + err.toString()); readStream.destroy(); fs.unlink(filePath); callback(err); }); readStream.on('end', function () { callback(null, hash.digest("hex")); }); } function saveToFs(md5, filePath, callback) { var newPath = utils.hashToPath(md5); path.exists(newPath, function (exists) { if (exists) { fs.move(filePath, newPath, function (err) { callback(err, newPath); }); return; } exec('mkdir -p ' + newPath, function (err, stdout, stderr) { var tError; if (err || stderr) { console.log("Err: " + (err ? err : "none")); console.log("stderr: " + (stderr ? stderr : "none")); tError = {error: err, stderr: stderr, stdout: stdout}; return callback(tError, newPath); } console.log("stdout: " + (stdout ? stdout : "none")); fs.move(filePath, newPath, function (moveErr) { callback(moveErr, newPath); }); }); }); } function addKeysToFileStats(fieldNames, stats) { var fileStats = []; stats.forEach(function (item) { var fileStat = new FileStat(); item.forEach(function (fieldValue, i) { fileStat[fieldNames[i]] = fieldValue; }); if (fileStat.path) { fileStat.type = mime.lookup(fileStat.path); } fileStats.push(fileStat); }); return fileStats; } function importFile(fileStat, tmpFile, username, callback) { var oldPath; oldPath = tmpFile.path; readFile(oldPath, function (err, md5) { if (err) { fileStat.err = err; callback(err, fileStat); return; } // if we have an md5sum and they don't match, abandon ship if (fileStat.md5 && fileStat.md5 !== md5) { callback("MD5 sums don't match"); return; } fileStat.md5 = md5; fileStat.genTmd5(function (error, tmd5) { if (!error) { fileStat.tmd5 = tmd5; saveToFs(fileStat.md5, oldPath, function (fserr) { if (fserr) { // ignoring possible unlink error fs.unlink(oldPath); fileStat.err = "File did not save"; } else { dbaccess.put(fileStat, username); } callback(fserr, fileStat); }); } }); }); } function handleUpload(req, res, next) { if (!req.form) { return next(); } req.form.complete(function (err, fields, files) { var fileStats, bFirst; fields.statsHeader = JSON.parse(fields.statsHeader); fields.stats = JSON.parse(fields.stats); fileStats = addKeysToFileStats(fields.statsHeader, fields.stats); dbaccess.createViews(req.remoteUser, fileStats); res.writeHead(200, {'Content-Type': 'application/json'}); // response as array res.write("["); bFirst = true; function handleFileStat(next, fileStat) { // this callback is synchronous fileStat.checkMd5(function (qmd5Error, qmd5) { function finishReq(err) { console.log(fileStat); fileStat.err = err; // we only want to add a comma after the first one if (!bFirst) { res.write(","); } bFirst = false; res.write(JSON.stringify(fileStat)); return next(); } if (qmd5Error) { return finishReq(qmd5Error); } importFile(fileStat, files[qmd5], req.remoteUser, finishReq); }); } fileStats.forEachAsync(handleFileStat).then(function () { // end response array res.end("]"); }); }); } module.exports = handleUpload; }());
beatgammit/node-filesync
server/lib/routes/upload.js
JavaScript
mit
3,981
#!/usr/bin/python from typing import List, Optional """ 16. 3Sum Closest https://leetcode.com/problems/3sum-closest/ """ def bsearch(nums, left, right, res, i, j, target): while left <= right: middle = (left + right) // 2 candidate = nums[i] + nums[j] + nums[middle] if res is None or abs(candidate - target) < abs(res - target): res = candidate if candidate == target: return res elif candidate > target: right = middle - 1 else: left = middle + 1 return res class Solution: def threeSumClosest(self, nums: List[int], target: int) -> Optional[int]: res = None nums = sorted(nums) for i in range(len(nums)): for j in range(i + 1, len(nums)): res = bsearch(nums, j + 1, len(nums) - 1, res, i, j, target) return res def main(): sol = Solution() print(sol.threeSumClosest([-111, -111, 3, 6, 7, 16, 17, 18, 19], 13)) return 0 if __name__ == '__main__': raise SystemExit(main())
pisskidney/leetcode
medium/16.py
Python
mit
1,070
package bits; /** * Created by krzysztofkaczor on 3/10/15. */ public class ExclusiveOrOperator implements BinaryOperator { @Override public BitArray combine(BitArray operand1, BitArray operand2) { if(operand1.size() != operand2.size()) { throw new IllegalArgumentException("ExclusiveOrOperator operands must have same size"); } int size = operand1.size(); BitArray result = new BitArray(size); for (int i = 0;i < size;i++) { boolean a = operand1.get(i); boolean b = operand2.get(i); result.set(i, a != b ); } return result; } }
krzkaczor/IDEA
src/main/java/bits/ExclusiveOrOperator.java
Java
mit
651
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); // Database var mongo = require('mongodb'); var monk = require('monk'); var db = monk('localhost:27017/mydb'); var index = require('./routes/index'); var buyer = require('./routes/buyer'); var seller = require('./routes/seller'); var products = require('./routes/products'); var app = express(); const ObjectID = mongo.ObjectID; // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.engine('html', require('ejs').renderFile); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); // Make our db accessible to our router app.use(function(req,res,next){ req.db = db; req.ObjectID = ObjectID; next(); }); app.use('/', index); app.use('/buyer', buyer); app.use('/seller', seller); app.use('/products', products); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error.html', err); }); module.exports = app;
imRishabhGupta/smart-kart
app.js
JavaScript
mit
1,740
# Smallest Integer # I worked on this challenge [by myself, with: ]. # smallest_integer is a method that takes an array of integers as its input # and returns the smallest integer in the array # # +list_of_nums+ is an array of integers # smallest_integer(list_of_nums) should return the smallest integer in +list_of_nums+ # # If +list_of_nums+ is empty the method should return nil # Your Solution Below def smallest_integer(list_of_nums) if list_of_nums.empty? return nil else list_of_nums.sort! return list_of_nums[0] end end
NoahHeinrich/phase-0
week-4/smallest-integer/my_solution.rb
Ruby
mit
548
FactoryGirl.define do factory :user do provider 'trello' uid 'trello-special-uid' full_name 'Dennis Martinez' nickname 'dennmart' oauth_token 'trello-token' trait :admin do admin true end end end
dennmart/echo_for_trello
spec/factories/users.rb
Ruby
mit
235
from multiprocessing import Pool import os, time, random def long_time_task(name): print 'Run task %s (%s)...' % (name, os.getpid()) start = time.time() time.sleep(random.random() * 3) end = time.time() print 'Task %s runs %0.2f seconds.' % (name, (end - start)) if __name__ == '__main__': print 'Parent process %s.' % os.getpid() p = Pool() for i in range(5): p.apply_async(long_time_task, args=(i,)) print 'Waiting for all subprocesses done...' p.close() p.join() print 'All subprocesses done.' """ 代码解读: 对Pool对象调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了。 请注意输出的结果,task 0,1,2,3是立刻执行的,而task 4要等待前面某个task完成后才执行,这是因为Pool的默认大小在我的电脑上是4,因此,最多同时执行4个进程。这是Pool有意设计的限制,并不是操作系统的限制。如果改成: p = Pool(5) """
Jayin/practice_on_py
Process&Thread/PoolTest.py
Python
mit
1,094
package net.comfreeze.lib; import android.app.AlarmManager; import android.app.Application; import android.app.NotificationManager; import android.content.ComponentName; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.content.res.Resources; import android.location.LocationManager; import android.media.AudioManager; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import net.comfreeze.lib.audio.SoundManager; import java.io.File; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Calendar; import java.util.TimeZone; abstract public class CFZApplication extends Application { public static final String TAG = "CFZApplication"; public static final String PACKAGE = "com.rastermedia"; public static final String KEY_DEBUG = "debug"; public static final String KEY_SYNC_PREFEX = "sync_"; public static SharedPreferences preferences = null; protected static Context context = null; protected static CFZApplication instance; public static LocalBroadcastManager broadcast; public static boolean silent = true; @Override public void onCreate() { if (!silent) Log.d(TAG, "Initializing"); instance = this; setContext(); setPreferences(); broadcast = LocalBroadcastManager.getInstance(context); super.onCreate(); } @Override public void onLowMemory() { if (!silent) Log.d(TAG, "Low memory!"); super.onLowMemory(); } @Override public void onTerminate() { unsetContext(); if (!silent) Log.d(TAG, "Terminating"); super.onTerminate(); } abstract public void setPreferences(); abstract public void setContext(); abstract public void unsetContext(); abstract public String getProductionKey(); public static CFZApplication getInstance(Class<?> className) { // log("Returning current application instance"); if (instance == null) { synchronized (className) { if (instance == null) try { instance = (CFZApplication) className.newInstance(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } } } return instance; } public void clearApplicationData() { File cache = getCacheDir(); File appDir = new File(cache.getParent()); if (appDir.exists()) { String[] children = appDir.list(); for (String dir : children) { if (!dir.equals("lib")) { deleteDir(new File(appDir, dir)); } } } preferences.edit().clear().commit(); } private static boolean deleteDir(File dir) { if (dir != null) { if (!silent) Log.d(PACKAGE, "Deleting: " + dir.getAbsolutePath()); if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) return false; } } return dir.delete(); } return false; } public static int dipsToPixel(float value, float scale) { return (int) (value * scale + 0.5f); } public static long timezoneOffset() { Calendar calendar = Calendar.getInstance(); return (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)); } public static long timezoneOffset(String timezone) { Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(timezone)); return (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)); } public static Resources res() { return context.getResources(); } public static LocationManager getLocationManager(Context context) { return (LocationManager) context.getSystemService(LOCATION_SERVICE); } public static AlarmManager getAlarmManager(Context context) { return (AlarmManager) context.getSystemService(ALARM_SERVICE); } public static NotificationManager getNotificationManager(Context context) { return (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE); } public static AudioManager getAudioManager(Context context) { return (AudioManager) context.getSystemService(AUDIO_SERVICE); } public static SoundManager getSoundManager(CFZApplication application) { return (SoundManager) SoundManager.instance(application); } public static void setSyncDate(String key, long date) { preferences.edit().putLong(KEY_SYNC_PREFEX + key, date).commit(); } public static long getSyncDate(String key) { return preferences.getLong(KEY_SYNC_PREFEX + key, -1L); } public static boolean needSync(String key, long limit) { return (System.currentTimeMillis() - getSyncDate(key) > limit); } public static String hash(final String algorithm, final String s) { try { // Create specified hash MessageDigest digest = java.security.MessageDigest.getInstance(algorithm); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); // Create hex string StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) h = "0" + h; hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } public boolean isProduction(Context context) { boolean result = false; try { ComponentName component = new ComponentName(context, instance.getClass()); PackageInfo info = context.getPackageManager().getPackageInfo(component.getPackageName(), PackageManager.GET_SIGNATURES); Signature[] sigs = info.signatures; for (int i = 0; i < sigs.length; i++) if (!silent) Log.d(TAG, "Signing key: " + sigs[i].toCharsString()); String targetKey = getProductionKey(); if (null == targetKey) targetKey = ""; if (targetKey.equals(sigs[0].toCharsString())) { result = true; if (!silent) Log.d(TAG, "Signed with production key"); } else { if (!silent) Log.d(TAG, "Not signed with production key"); } } catch (PackageManager.NameNotFoundException e) { if (!silent) Log.e(TAG, "Package exception", e); } return result; } public static class LOG { // Without Throwables public static void v(String tag, String message) { if (!silent) Log.v(tag, message); } public static void d(String tag, String message) { if (!silent) Log.d(tag, message); } public static void i(String tag, String message) { if (!silent) Log.i(tag, message); } public static void w(String tag, String message) { if (!silent) Log.w(tag, message); } public static void e(String tag, String message) { if (!silent) Log.e(tag, message); } public static void wtf(String tag, String message) { if (!silent) Log.wtf(tag, message); } // With Throwables public static void v(String tag, String message, Throwable t) { if (!silent) Log.v(tag, message, t); } public static void d(String tag, String message, Throwable t) { if (!silent) Log.d(tag, message, t); } public static void i(String tag, String message, Throwable t) { if (!silent) Log.i(tag, message, t); } public static void w(String tag, String message, Throwable t) { if (!silent) Log.w(tag, message, t); } public static void e(String tag, String message, Throwable t) { if (!silent) Log.e(tag, message, t); } public static void wtf(String tag, String message, Throwable t) { if (!silent) Log.wtf(tag, message, t); } } }
comfreeze/android-tools
CFZLib/src/main/java/net/comfreeze/lib/CFZApplication.java
Java
mit
8,991
/** * @author yomboprime https://github.com/yomboprime * * GPUComputationRenderer, based on SimulationRenderer by zz85 * * The GPUComputationRenderer uses the concept of variables. These variables are RGBA float textures that hold 4 floats * for each compute element (texel) * * Each variable has a fragment shader that defines the computation made to obtain the variable in question. * You can use as many variables you need, and make dependencies so you can use textures of other variables in the shader * (the sampler uniforms are added automatically) Most of the variables will need themselves as dependency. * * The renderer has actually two render targets per variable, to make ping-pong. Textures from the current frame are used * as inputs to render the textures of the next frame. * * The render targets of the variables can be used as input textures for your visualization shaders. * * Variable names should be valid identifiers and should not collide with THREE GLSL used identifiers. * a common approach could be to use 'texture' prefixing the variable name; i.e texturePosition, textureVelocity... * * The size of the computation (sizeX * sizeY) is defined as 'resolution' automatically in the shader. For example: * #DEFINE resolution vec2( 1024.0, 1024.0 ) * * ------------- * * Basic use: * * // Initialization... * * // Create computation renderer * var gpuCompute = new GPUComputationRenderer( 1024, 1024, renderer ); * * // Create initial state float textures * var pos0 = gpuCompute.createTexture(); * var vel0 = gpuCompute.createTexture(); * // and fill in here the texture data... * * // Add texture variables * var velVar = gpuCompute.addVariable( "textureVelocity", fragmentShaderVel, pos0 ); * var posVar = gpuCompute.addVariable( "texturePosition", fragmentShaderPos, vel0 ); * * // Add variable dependencies * gpuCompute.setVariableDependencies( velVar, [ velVar, posVar ] ); * gpuCompute.setVariableDependencies( posVar, [ velVar, posVar ] ); * * // Add custom uniforms * velVar.material.uniforms.time = { value: 0.0 }; * * // Check for completeness * var error = gpuCompute.init(); * if ( error !== null ) { * console.error( error ); * } * * * // In each frame... * * // Compute! * gpuCompute.compute(); * * // Update texture uniforms in your visualization materials with the gpu renderer output * myMaterial.uniforms.myTexture.value = gpuCompute.getCurrentRenderTarget( posVar ).texture; * * // Do your rendering * renderer.render( myScene, myCamera ); * * ------------- * * Also, you can use utility functions to create ShaderMaterial and perform computations (rendering between textures) * Note that the shaders can have multiple input textures. * * var myFilter1 = gpuCompute.createShaderMaterial( myFilterFragmentShader1, { theTexture: { value: null } } ); * var myFilter2 = gpuCompute.createShaderMaterial( myFilterFragmentShader2, { theTexture: { value: null } } ); * * var inputTexture = gpuCompute.createTexture(); * * // Fill in here inputTexture... * * myFilter1.uniforms.theTexture.value = inputTexture; * * var myRenderTarget = gpuCompute.createRenderTarget(); * myFilter2.uniforms.theTexture.value = myRenderTarget.texture; * * var outputRenderTarget = gpuCompute.createRenderTarget(); * * // Now use the output texture where you want: * myMaterial.uniforms.map.value = outputRenderTarget.texture; * * // And compute each frame, before rendering to screen: * gpuCompute.doRenderTarget( myFilter1, myRenderTarget ); * gpuCompute.doRenderTarget( myFilter2, outputRenderTarget ); * * * * @param {int} sizeX Computation problem size is always 2d: sizeX * sizeY elements. * @param {int} sizeY Computation problem size is always 2d: sizeX * sizeY elements. * @param {WebGLRenderer} renderer The renderer */ import { Camera, ClampToEdgeWrapping, DataTexture, FloatType, HalfFloatType, Mesh, NearestFilter, PlaneBufferGeometry, RGBAFormat, Scene, ShaderMaterial, WebGLRenderTarget } from "./three.module.js"; var GPUComputationRenderer = function ( sizeX, sizeY, renderer ) { this.variables = []; this.currentTextureIndex = 0; var scene = new Scene(); var camera = new Camera(); camera.position.z = 1; var passThruUniforms = { passThruTexture: { value: null } }; var passThruShader = createShaderMaterial( getPassThroughFragmentShader(), passThruUniforms ); var mesh = new Mesh( new PlaneBufferGeometry( 2, 2 ), passThruShader ); scene.add( mesh ); this.addVariable = function ( variableName, computeFragmentShader, initialValueTexture ) { var material = this.createShaderMaterial( computeFragmentShader ); var variable = { name: variableName, initialValueTexture: initialValueTexture, material: material, dependencies: null, renderTargets: [], wrapS: null, wrapT: null, minFilter: NearestFilter, magFilter: NearestFilter }; this.variables.push( variable ); return variable; }; this.setVariableDependencies = function ( variable, dependencies ) { variable.dependencies = dependencies; }; this.init = function () { if ( ! renderer.extensions.get( "OES_texture_float" ) && ! renderer.capabilities.isWebGL2 ) { return "No OES_texture_float support for float textures."; } if ( renderer.capabilities.maxVertexTextures === 0 ) { return "No support for vertex shader textures."; } for ( var i = 0; i < this.variables.length; i ++ ) { var variable = this.variables[ i ]; // Creates rendertargets and initialize them with input texture variable.renderTargets[ 0 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter ); variable.renderTargets[ 1 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter ); this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 0 ] ); this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 1 ] ); // Adds dependencies uniforms to the ShaderMaterial var material = variable.material; var uniforms = material.uniforms; if ( variable.dependencies !== null ) { for ( var d = 0; d < variable.dependencies.length; d ++ ) { var depVar = variable.dependencies[ d ]; if ( depVar.name !== variable.name ) { // Checks if variable exists var found = false; for ( var j = 0; j < this.variables.length; j ++ ) { if ( depVar.name === this.variables[ j ].name ) { found = true; break; } } if ( ! found ) { return "Variable dependency not found. Variable=" + variable.name + ", dependency=" + depVar.name; } } uniforms[ depVar.name ] = { value: null }; material.fragmentShader = "\nuniform sampler2D " + depVar.name + ";\n" + material.fragmentShader; } } } this.currentTextureIndex = 0; return null; }; this.compute = function () { var currentTextureIndex = this.currentTextureIndex; var nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0; for ( var i = 0, il = this.variables.length; i < il; i ++ ) { var variable = this.variables[ i ]; // Sets texture dependencies uniforms if ( variable.dependencies !== null ) { var uniforms = variable.material.uniforms; for ( var d = 0, dl = variable.dependencies.length; d < dl; d ++ ) { var depVar = variable.dependencies[ d ]; uniforms[ depVar.name ].value = depVar.renderTargets[ currentTextureIndex ].texture; } } // Performs the computation for this variable this.doRenderTarget( variable.material, variable.renderTargets[ nextTextureIndex ] ); } this.currentTextureIndex = nextTextureIndex; }; this.getCurrentRenderTarget = function ( variable ) { return variable.renderTargets[ this.currentTextureIndex ]; }; this.getAlternateRenderTarget = function ( variable ) { return variable.renderTargets[ this.currentTextureIndex === 0 ? 1 : 0 ]; }; function addResolutionDefine( materialShader ) { materialShader.defines.resolution = 'vec2( ' + sizeX.toFixed( 1 ) + ', ' + sizeY.toFixed( 1 ) + " )"; } this.addResolutionDefine = addResolutionDefine; // The following functions can be used to compute things manually function createShaderMaterial( computeFragmentShader, uniforms ) { uniforms = uniforms || {}; var material = new ShaderMaterial( { uniforms: uniforms, vertexShader: getPassThroughVertexShader(), fragmentShader: computeFragmentShader } ); addResolutionDefine( material ); return material; } this.createShaderMaterial = createShaderMaterial; this.createRenderTarget = function ( sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter ) { sizeXTexture = sizeXTexture || sizeX; sizeYTexture = sizeYTexture || sizeY; wrapS = wrapS || ClampToEdgeWrapping; wrapT = wrapT || ClampToEdgeWrapping; minFilter = minFilter || NearestFilter; magFilter = magFilter || NearestFilter; var renderTarget = new WebGLRenderTarget( sizeXTexture, sizeYTexture, { wrapS: wrapS, wrapT: wrapT, minFilter: minFilter, magFilter: magFilter, format: RGBAFormat, type: ( /(iPad|iPhone|iPod)/g.test( navigator.userAgent ) ) ? HalfFloatType : FloatType, stencilBuffer: false, depthBuffer: false } ); return renderTarget; }; this.createTexture = function () { var a = new Float32Array( sizeX * sizeY * 4 ); var texture = new DataTexture( a, sizeX, sizeY, RGBAFormat, FloatType ); texture.needsUpdate = true; return texture; }; this.renderTexture = function ( input, output ) { // Takes a texture, and render out in rendertarget // input = Texture // output = RenderTarget passThruUniforms.passThruTexture.value = input; this.doRenderTarget( passThruShader, output ); passThruUniforms.passThruTexture.value = null; }; this.doRenderTarget = function ( material, output ) { var currentRenderTarget = renderer.getRenderTarget(); mesh.material = material; renderer.setRenderTarget( output ); renderer.render( scene, camera ); mesh.material = passThruShader; renderer.setRenderTarget( currentRenderTarget ); }; // Shaders function getPassThroughVertexShader() { return "void main() {\n" + "\n" + " gl_Position = vec4( position, 1.0 );\n" + "\n" + "}\n"; } function getPassThroughFragmentShader() { return "uniform sampler2D passThruTexture;\n" + "\n" + "void main() {\n" + "\n" + " vec2 uv = gl_FragCoord.xy / resolution.xy;\n" + "\n" + " gl_FragColor = texture2D( passThruTexture, uv );\n" + "\n" + "}\n"; } }; export { GPUComputationRenderer };
ChenJiaH/chenjiah.github.io
js/GPUComputationRenderer.js
JavaScript
mit
10,733
package com.example.mesh; import java.util.HashMap; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; @Path("/") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class EndpointControlResource { /** * @see <a href="https://relay.bluejeans.com/docs/mesh.html#capabilities">https://relay.bluejeans.com/docs/mesh.html#capabilities</a> */ @GET @Path("{ipAddress}/capabilities") public Map<String, Boolean> capabilities(@PathParam("ipAddress") final String ipAddress, @QueryParam("port") final Integer port, @QueryParam("name") final String name) { System.out.println("Received capabilities request"); System.out.println(" ipAddress = " + ipAddress); System.out.println(" port = " + port); System.out.println(" name = " + name); final Map<String, Boolean> capabilities = new HashMap<>(); capabilities.put("JOIN", true); capabilities.put("HANGUP", true); capabilities.put("STATUS", true); capabilities.put("MUTEMICROPHONE", true); return capabilities; } /** * @see <a href="https://relay.bluejeans.com/docs/mesh.html#status">https://relay.bluejeans.com/docs/mesh.html#status</a> */ @GET @Path("{ipAddress}/status") public Map<String, Boolean> status(@PathParam("ipAddress") final String ipAddress, @QueryParam("port") final Integer port, @QueryParam("name") final String name) { System.out.println("Received status request"); System.out.println(" ipAddress = " + ipAddress); System.out.println(" port = " + port); System.out.println(" name = " + name); final Map<String, Boolean> status = new HashMap<>(); status.put("callActive", false); status.put("microphoneMuted", false); return status; } /** * @see <a href="https://relay.bluejeans.com/docs/mesh.html#join">https://relay.bluejeans.com/docs/mesh.html#join</a> */ @POST @Path("{ipAddress}/join") public void join(@PathParam("ipAddress") final String ipAddress, @QueryParam("dialString") final String dialString, @QueryParam("meetingId") final String meetingId, @QueryParam("passcode") final String passcode, @QueryParam("bridgeAddress") final String bridgeAddress, final Endpoint endpoint) { System.out.println("Received join request"); System.out.println(" ipAddress = " + ipAddress); System.out.println(" dialString = " + dialString); System.out.println(" meetingId = " + meetingId); System.out.println(" passcode = " + passcode); System.out.println(" bridgeAddress = " + bridgeAddress); System.out.println(" endpoint = " + endpoint); } /** * @see <a href="https://relay.bluejeans.com/docs/mesh.html#hangup">https://relay.bluejeans.com/docs/mesh.html#hangup</a> */ @POST @Path("{ipAddress}/hangup") public void hangup(@PathParam("ipAddress") final String ipAddress, final Endpoint endpoint) { System.out.println("Received hangup request"); System.out.println(" ipAddress = " + ipAddress); System.out.println(" endpoint = " + endpoint); } /** * @see <a href="https://relay.bluejeans.com/docs/mesh.html#mutemicrophone">https://relay.bluejeans.com/docs/mesh.html#mutemicrophone</a> */ @POST @Path("{ipAddress}/mutemicrophone") public void muteMicrophone(@PathParam("ipAddress") final String ipAddress, final Endpoint endpoint) { System.out.println("Received mutemicrophone request"); System.out.println(" ipAddress = " + ipAddress); System.out.println(" endpoint = " + endpoint); } /** * @see <a href="https://relay.bluejeans.com/docs/mesh.html#mutemicrophone">https://relay.bluejeans.com/docs/mesh.html#mutemicrophone</a> */ @POST @Path("{ipAddress}/unmutemicrophone") public void unmuteMicrophone(@PathParam("ipAddress") final String ipAddress, final Endpoint endpoint) { System.out.println("Received unmutemicrophone request"); System.out.println(" ipAddress = " + ipAddress); System.out.println(" endpoint = " + endpoint); } }
Aldaviva/relay-mesh-example-java
src/main/java/com/example/mesh/EndpointControlResource.java
Java
mit
4,452
<?php namespace Screeenly\Screenshot; /** * Interface description. * * @author Stefan Zweifel */ interface ClientInterface { /** * Method description. * * @author Stefan Zweifel * * @param type $parameter * * @return type */ public function build(); public function capture(Screenshot $screenshot); }
imdanshraaj/screeenly
app/Screenshot/ClientInterface.php
PHP
mit
362
// cpu/test/unique-strings.cpp -*-C++-*- // ---------------------------------------------------------------------------- // Copyright (C) 2015 Dietmar Kuehl http://www.dietmar-kuehl.de // // 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. // ---------------------------------------------------------------------------- #include "cpu/tube/context.hpp" #include <algorithm> #include <iostream> #include <iomanip> #include <sstream> #include <iterator> #include <string> #include <random> #include <set> #include <unordered_set> #include <vector> #if defined(HAS_BSL) #include <bsl_set.h> #include <bsl_unordered_set.h> #endif #include <stdlib.h> // ---------------------------------------------------------------------------- namespace std { template <typename Algo> void hashAppend(Algo& algo, std::string const& value) { algo(value.c_str(), value.size()); } } // ---------------------------------------------------------------------------- namespace { struct std_algos { std::string name() const { return "std::sort()/std::unique()"; } std::size_t run(std::vector<std::string> const& keys) const { std::vector<std::string> values(keys.begin(), keys.end()); std::sort(values.begin(), values.end()); auto end = std::unique(values.begin(), values.end()); values.erase(end, values.end()); return values.size(); } }; struct std_set { std::string name() const { return "std::set<std::string>"; } std::size_t run(std::vector<std::string> const& keys) const { std::set<std::string> values(keys.begin(), keys.end()); return values.size(); } }; struct std_insert_set { std::string name() const { return "std::set<std::string> (insert)"; } std::size_t run(std::vector<std::string> const& keys) const { std::set<std::string> values; for (std::string value: keys) { values.insert(value); } return values.size(); } }; struct std_reverse_set { std::string name() const { return "std::set<std::string> (reverse)"; } std::size_t run(std::vector<std::string> const& keys) const { std::set<std::string> values; for (std::string value: keys) { std::reverse(value.begin(), value.end()); values.insert(value); } return values.size(); } }; struct std_unordered_set { std::string name() const { return "std::unordered_set<std::string>"; } std::size_t run(std::vector<std::string> const& keys) const { std::unordered_set<std::string> values(keys.begin(), keys.end()); return values.size(); } }; struct std_insert_unordered_set { std::string name() const { return "std::unordered_set<std::string> (insert)"; } std::size_t run(std::vector<std::string> const& keys) const { std::unordered_set<std::string> values; for (std::string value: keys) { values.insert(value); } return values.size(); } }; struct std_reserve_unordered_set { std::string name() const { return "std::unordered_set<std::string> (reserve)"; } std::size_t run(std::vector<std::string> const& keys) const { std::unordered_set<std::string> values; values.reserve(keys.size()); for (std::string value: keys) { values.insert(value); } return values.size(); } }; #if defined(HAS_BSL) struct bsl_set { std::string name() const { return "bsl::set<std::string>"; } std::size_t run(std::vector<std::string> const& keys) const { bsl::set<std::string> values(keys.begin(), keys.end()); return values.size(); } }; struct bsl_insert_set { std::string name() const { return "bsl::set<std::string> (insert)"; } std::size_t run(std::vector<std::string> const& keys) const { bsl::set<std::string> values; for (std::string value: keys) { values.insert(value); } return values.size(); } }; struct bsl_reverse_set { std::string name() const { return "bsl::set<std::string> (reverse)"; } std::size_t run(std::vector<std::string> const& keys) const { bsl::set<std::string> values; for (std::string value: keys) { std::reverse(value.begin(), value.end()); values.insert(value); } return values.size(); } }; struct bsl_unordered_set { std::string name() const { return "bsl::unordered_set<std::string>"; } std::size_t run(std::vector<std::string> const& keys) const { bsl::unordered_set<std::string> values(keys.begin(), keys.end()); return values.size(); } }; struct bsl_insert_unordered_set { std::string name() const { return "bsl::unordered_set<std::string> (insert)"; } std::size_t run(std::vector<std::string> const& keys) const { bsl::unordered_set<std::string> values; for (std::string value: keys) { values.insert(value); } return values.size(); } }; struct bsl_reserve_unordered_set { std::string name() const { return "bsl::unordered_set<std::string> (reserve)"; } std::size_t run(std::vector<std::string> const& keys) const { bsl::unordered_set<std::string> values; values.reserve(keys.size()); for (std::string value: keys) { values.insert(value); } return values.size(); } }; #endif } // ---------------------------------------------------------------------------- namespace { template <typename Algo> void measure(cpu::tube::context& context, std::vector<std::string> const& keys, std::size_t basesize, Algo algo) { auto timer = context.start(); std::size_t size = algo.run(keys); auto time = timer.measure(); std::ostringstream out; out << std::left << std::setw(50) << algo.name() << " [" << keys.size() << "/" << basesize << "]"; context.report(out.str(), time, size); } } static void measure(cpu::tube::context& context, std::vector<std::string> const& keys, std::size_t basesize) { measure(context, keys, basesize, std_algos()); measure(context, keys, basesize, std_set()); measure(context, keys, basesize, std_insert_set()); measure(context, keys, basesize, std_reverse_set()); measure(context, keys, basesize, std_unordered_set()); measure(context, keys, basesize, std_insert_unordered_set()); measure(context, keys, basesize, std_reserve_unordered_set()); #if defined(HAS_BSL) measure(context, keys, basesize, bsl_set()); measure(context, keys, basesize, bsl_insert_set()); measure(context, keys, basesize, bsl_reverse_set()); measure(context, keys, basesize, bsl_unordered_set()); measure(context, keys, basesize, bsl_insert_unordered_set()); measure(context, keys, basesize, bsl_reserve_unordered_set()); #endif } // ---------------------------------------------------------------------------- static void run_tests(cpu::tube::context& context, int size) { std::string const bases[] = { "/usr/local/include/", "/some/medium/sized/path/as/a/prefix/to/the/actual/interesting/names/", "/finally/a/rather/long/string/including/pointless/sequences/like/" "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/" "just/to/make/the/string/longer/to/qualify/as/an/actual/long/string/" }; std::mt19937 gen(4711); std::uniform_int_distribution<> rand(0, size * 0.8); for (std::string const& base: bases) { std::vector<std::string> keys; keys.reserve(size); int i = 0; std::generate_n(std::back_inserter(keys), size, [i, &base, &rand, &gen]()mutable{ return base + std::to_string(rand(gen)); }); measure(context, keys, base.size()); } } // ---------------------------------------------------------------------------- int main(int ac, char* av[]) { cpu::tube::context context(CPUTUBE_CONTEXT_ARGS(ac, av)); int size(ac == 1? 0: atoi(av[1])); if (size) { run_tests(context, size); } else { for (int i(10); i <= 100000; i *= 10) { for (int j(1); j < 10; j *= 2) { run_tests(context, i * j); } } } }
dietmarkuehl/cputube
cpu/test/unique-strings.cpp
C++
mit
10,438
/* * Encog(tm) Core v3.1 - Java Version * http://www.heatonresearch.com/encog/ * http://code.google.com/p/encog-java/ * Copyright 2008-2012 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.plugin.system; import org.encog.EncogError; import org.encog.engine.network.activation.ActivationFunction; import org.encog.ml.MLMethod; import org.encog.ml.data.MLDataSet; import org.encog.ml.factory.MLTrainFactory; import org.encog.ml.factory.train.AnnealFactory; import org.encog.ml.factory.train.BackPropFactory; import org.encog.ml.factory.train.ClusterSOMFactory; import org.encog.ml.factory.train.GeneticFactory; import org.encog.ml.factory.train.LMAFactory; import org.encog.ml.factory.train.ManhattanFactory; import org.encog.ml.factory.train.NeighborhoodSOMFactory; import org.encog.ml.factory.train.NelderMeadFactory; import org.encog.ml.factory.train.PNNTrainFactory; import org.encog.ml.factory.train.PSOFactory; import org.encog.ml.factory.train.QuickPropFactory; import org.encog.ml.factory.train.RBFSVDFactory; import org.encog.ml.factory.train.RPROPFactory; import org.encog.ml.factory.train.SCGFactory; import org.encog.ml.factory.train.SVMFactory; import org.encog.ml.factory.train.SVMSearchFactory; import org.encog.ml.factory.train.TrainBayesianFactory; import org.encog.ml.train.MLTrain; import org.encog.plugin.EncogPluginBase; import org.encog.plugin.EncogPluginService1; public class SystemTrainingPlugin implements EncogPluginService1 { /** * The factory for K2 */ private final TrainBayesianFactory bayesianFactory = new TrainBayesianFactory(); /** * The factory for backprop. */ private final BackPropFactory backpropFactory = new BackPropFactory(); /** * The factory for LMA. */ private final LMAFactory lmaFactory = new LMAFactory(); /** * The factory for RPROP. */ private final RPROPFactory rpropFactory = new RPROPFactory(); /** * THe factory for basic SVM. */ private final SVMFactory svmFactory = new SVMFactory(); /** * The factory for SVM-Search. */ private final SVMSearchFactory svmSearchFactory = new SVMSearchFactory(); /** * The factory for SCG. */ private final SCGFactory scgFactory = new SCGFactory(); /** * The factory for simulated annealing. */ private final AnnealFactory annealFactory = new AnnealFactory(); /** * Nelder Mead Factory. */ private final NelderMeadFactory nmFactory = new NelderMeadFactory(); /** * The factory for neighborhood SOM. */ private final NeighborhoodSOMFactory neighborhoodFactory = new NeighborhoodSOMFactory(); /** * The factory for SOM cluster. */ private final ClusterSOMFactory somClusterFactory = new ClusterSOMFactory(); /** * The factory for genetic. */ private final GeneticFactory geneticFactory = new GeneticFactory(); /** * The factory for Manhattan networks. */ private final ManhattanFactory manhattanFactory = new ManhattanFactory(); /** * Factory for SVD. */ private final RBFSVDFactory svdFactory = new RBFSVDFactory(); /** * Factory for PNN. */ private final PNNTrainFactory pnnFactory = new PNNTrainFactory(); /** * Factory for quickprop. */ private final QuickPropFactory qpropFactory = new QuickPropFactory(); private final PSOFactory psoFactory = new PSOFactory(); /** * {@inheritDoc} */ @Override public final String getPluginDescription() { return "This plugin provides the built in training " + "methods for Encog."; } /** * {@inheritDoc} */ @Override public final String getPluginName() { return "HRI-System-Training"; } /** * @return This is a type-1 plugin. */ @Override public final int getPluginType() { return 1; } /** * This plugin does not support activation functions, so it will * always return null. * @return Null, because this plugin does not support activation functions. */ @Override public ActivationFunction createActivationFunction(String name) { return null; } @Override public MLMethod createMethod(String methodType, String architecture, int input, int output) { // TODO Auto-generated method stub return null; } @Override public MLTrain createTraining(MLMethod method, MLDataSet training, String type, String args) { String args2 = args; if (args2 == null) { args2 = ""; } if (MLTrainFactory.TYPE_RPROP.equalsIgnoreCase(type)) { return this.rpropFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_BACKPROP.equalsIgnoreCase(type)) { return this.backpropFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_SCG.equalsIgnoreCase(type)) { return this.scgFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_LMA.equalsIgnoreCase(type)) { return this.lmaFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_SVM.equalsIgnoreCase(type)) { return this.svmFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_SVM_SEARCH.equalsIgnoreCase(type)) { return this.svmSearchFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_SOM_NEIGHBORHOOD.equalsIgnoreCase( type)) { return this.neighborhoodFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_ANNEAL.equalsIgnoreCase(type)) { return this.annealFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_GENETIC.equalsIgnoreCase(type)) { return this.geneticFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_SOM_CLUSTER.equalsIgnoreCase(type)) { return this.somClusterFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_MANHATTAN.equalsIgnoreCase(type)) { return this.manhattanFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_SVD.equalsIgnoreCase(type)) { return this.svdFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_PNN.equalsIgnoreCase(type)) { return this.pnnFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_QPROP.equalsIgnoreCase(type)) { return this.qpropFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_BAYESIAN.equals(type) ) { return this.bayesianFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_NELDER_MEAD.equals(type) ) { return this.nmFactory.create(method, training, args2); } else if (MLTrainFactory.TYPE_PSO.equals(type) ) { return this.psoFactory.create(method, training, args2); } else { throw new EncogError("Unknown training type: " + type); } } /** * {@inheritDoc} */ @Override public int getPluginServiceType() { return EncogPluginBase.TYPE_SERVICE; } }
larhoy/SentimentProjectV2
SentimentAnalysisV2/encog-core-3.1.0/src/main/java/org/encog/plugin/system/SystemTrainingPlugin.java
Java
mit
7,358
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import './index.scss' import React, { Component } from 'react' // import { Grid, Col, Row } from 'react-bootstrap'; export default class IndexPage extends Component { render() { return ( <div className="top-page"> <div> <img className="top-image" src="/cover2.jpg" width="100%" alt="cover image" /> </div> <div className="top-page--footer"> The source code of this website is available&nbsp; <a href="https://github.com/odoruinu/odoruinu.net-pug" target="_blank" rel="noopener noreferrer" > here on GitHub </a> . </div> </div> ) } }
odoruinu/odoruinu.net-pug
pages/index.js
JavaScript
mit
908
# coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import pytest from os import path, remove, sys, urandom import platform import uuid from azure.storage.blob import ( BlobServiceClient, ContainerClient, BlobClient, ContentSettings ) if sys.version_info >= (3,): from io import BytesIO else: from cStringIO import StringIO as BytesIO from settings.testcase import BlobPreparer from devtools_testutils.storage import StorageTestCase # ------------------------------------------------------------------------------ TEST_BLOB_PREFIX = 'largeblob' LARGE_BLOB_SIZE = 12 * 1024 * 1024 LARGE_BLOCK_SIZE = 6 * 1024 * 1024 # ------------------------------------------------------------------------------ if platform.python_implementation() == 'PyPy': pytest.skip("Skip tests for Pypy", allow_module_level=True) class StorageLargeBlockBlobTest(StorageTestCase): def _setup(self, storage_account_name, key): # test chunking functionality by reducing the threshold # for chunking and the size of each chunk, otherwise # the tests would take too long to execute self.bsc = BlobServiceClient( self.account_url(storage_account_name, "blob"), credential=key, max_single_put_size=32 * 1024, max_block_size=2 * 1024 * 1024, min_large_block_upload_threshold=1 * 1024 * 1024) self.config = self.bsc._config self.container_name = self.get_resource_name('utcontainer') if self.is_live: try: self.bsc.create_container(self.container_name) except: pass def _teardown(self, file_name): if path.isfile(file_name): try: remove(file_name) except: pass # --Helpers----------------------------------------------------------------- def _get_blob_reference(self): return self.get_resource_name(TEST_BLOB_PREFIX) def _create_blob(self): blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) blob.upload_blob(b'') return blob def assertBlobEqual(self, container_name, blob_name, expected_data): blob = self.bsc.get_blob_client(container_name, blob_name) actual_data = blob.download_blob() self.assertEqual(b"".join(list(actual_data.chunks())), expected_data) # --Test cases for block blobs -------------------------------------------- @pytest.mark.live_test_only @BlobPreparer() def test_put_block_bytes_large(self, storage_account_name, storage_account_key): self._setup(storage_account_name, storage_account_key) blob = self._create_blob() # Act for i in range(5): resp = blob.stage_block( 'block {0}'.format(i).encode('utf-8'), urandom(LARGE_BLOCK_SIZE)) self.assertIsNotNone(resp) assert 'content_md5' in resp assert 'content_crc64' in resp assert 'request_id' in resp # Assert @pytest.mark.live_test_only @BlobPreparer() def test_put_block_bytes_large_with_md5(self, storage_account_name, storage_account_key): self._setup(storage_account_name, storage_account_key) blob = self._create_blob() # Act for i in range(5): resp = blob.stage_block( 'block {0}'.format(i).encode('utf-8'), urandom(LARGE_BLOCK_SIZE), validate_content=True) self.assertIsNotNone(resp) assert 'content_md5' in resp assert 'content_crc64' in resp assert 'request_id' in resp @pytest.mark.live_test_only @BlobPreparer() def test_put_block_stream_large(self, storage_account_name, storage_account_key): self._setup(storage_account_name, storage_account_key) blob = self._create_blob() # Act for i in range(5): stream = BytesIO(bytearray(LARGE_BLOCK_SIZE)) resp = resp = blob.stage_block( 'block {0}'.format(i).encode('utf-8'), stream, length=LARGE_BLOCK_SIZE) self.assertIsNotNone(resp) assert 'content_md5' in resp assert 'content_crc64' in resp assert 'request_id' in resp # Assert @pytest.mark.live_test_only @BlobPreparer() def test_put_block_stream_large_with_md5(self, storage_account_name, storage_account_key): self._setup(storage_account_name, storage_account_key) blob = self._create_blob() # Act for i in range(5): stream = BytesIO(bytearray(LARGE_BLOCK_SIZE)) resp = resp = blob.stage_block( 'block {0}'.format(i).encode('utf-8'), stream, length=LARGE_BLOCK_SIZE, validate_content=True) self.assertIsNotNone(resp) assert 'content_md5' in resp assert 'content_crc64' in resp assert 'request_id' in resp # Assert @pytest.mark.live_test_only @BlobPreparer() def test_create_large_blob_from_path(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = 'large_blob_from_path.temp.{}.dat'.format(str(uuid.uuid4())) with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, max_concurrency=2, overwrite=True) block_list = blob.get_block_list() # Assert self.assertIsNot(len(block_list), 0) self.assertBlobEqual(self.container_name, blob_name, data) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_create_large_blob_from_path_with_md5(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = "blob_from_path_with_md5.temp.dat" with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, validate_content=True, max_concurrency=2) # Assert self.assertBlobEqual(self.container_name, blob_name, data) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_create_large_blob_from_path_non_parallel(self, storage_account_name, storage_account_key): self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(self.get_random_bytes(100)) FILE_PATH = "blob_from_path_non_parallel.temp.dat" with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, max_concurrency=1) # Assert self.assertBlobEqual(self.container_name, blob_name, data) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_create_large_blob_from_path_with_progress(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = "blob_from_path_with_progress.temp.dat" with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act progress = [] def callback(response): current = response.context['upload_stream_current'] total = response.context['data_stream_total'] if current is not None: progress.append((current, total)) with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, max_concurrency=2, raw_response_hook=callback) # Assert self.assertBlobEqual(self.container_name, blob_name, data) self.assert_upload_progress(len(data), self.config.max_block_size, progress) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_create_large_blob_from_path_with_properties(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = 'blob_from_path_with_properties.temp.{}.dat'.format(str(uuid.uuid4())) with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act content_settings = ContentSettings( content_type='image/png', content_language='spanish') with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, content_settings=content_settings, max_concurrency=2) # Assert self.assertBlobEqual(self.container_name, blob_name, data) properties = blob.get_blob_properties() self.assertEqual(properties.content_settings.content_type, content_settings.content_type) self.assertEqual(properties.content_settings.content_language, content_settings.content_language) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_create_large_blob_from_stream_chunked_upload(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = 'blob_from_stream_chunked_upload.temp.{}.dat'.format(str(uuid.uuid4())) with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, max_concurrency=2) # Assert self.assertBlobEqual(self.container_name, blob_name, data) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_creat_lrgblob_frm_stream_w_progress_chnkd_upload(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = 'stream_w_progress_chnkd_upload.temp.{}.dat'.format(str(uuid.uuid4())) with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act progress = [] def callback(response): current = response.context['upload_stream_current'] total = response.context['data_stream_total'] if current is not None: progress.append((current, total)) with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, max_concurrency=2, raw_response_hook=callback) # Assert self.assertBlobEqual(self.container_name, blob_name, data) self.assert_upload_progress(len(data), self.config.max_block_size, progress) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_create_large_blob_from_stream_chunked_upload_with_count(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = 'chunked_upload_with_count.temp.{}.dat'.format(str(uuid.uuid4())) with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act blob_size = len(data) - 301 with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, length=blob_size, max_concurrency=2) # Assert self.assertBlobEqual(self.container_name, blob_name, data[:blob_size]) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_creat_lrgblob_frm_strm_chnkd_uplod_w_count_n_props(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = 'plod_w_count_n_props.temp.{}.dat'.format(str(uuid.uuid4())) with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act content_settings = ContentSettings( content_type='image/png', content_language='spanish') blob_size = len(data) - 301 with open(FILE_PATH, 'rb') as stream: blob.upload_blob( stream, length=blob_size, content_settings=content_settings, max_concurrency=2) # Assert self.assertBlobEqual(self.container_name, blob_name, data[:blob_size]) properties = blob.get_blob_properties() self.assertEqual(properties.content_settings.content_type, content_settings.content_type) self.assertEqual(properties.content_settings.content_language, content_settings.content_language) self._teardown(FILE_PATH) @pytest.mark.live_test_only @BlobPreparer() def test_creat_lrg_blob_frm_stream_chnked_upload_w_props(self, storage_account_name, storage_account_key): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) blob_name = self._get_blob_reference() blob = self.bsc.get_blob_client(self.container_name, blob_name) data = bytearray(urandom(LARGE_BLOB_SIZE)) FILE_PATH = 'creat_lrg_blob.temp.{}.dat'.format(str(uuid.uuid4())) with open(FILE_PATH, 'wb') as stream: stream.write(data) # Act content_settings = ContentSettings( content_type='image/png', content_language='spanish') with open(FILE_PATH, 'rb') as stream: blob.upload_blob(stream, content_settings=content_settings, max_concurrency=2) # Assert self.assertBlobEqual(self.container_name, blob_name, data) properties = blob.get_blob_properties() self.assertEqual(properties.content_settings.content_type, content_settings.content_type) self.assertEqual(properties.content_settings.content_language, content_settings.content_language) self._teardown(FILE_PATH) # ------------------------------------------------------------------------------
Azure/azure-sdk-for-python
sdk/storage/azure-storage-blob/tests/test_large_block_blob.py
Python
mit
16,306
package controllers; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Date; import models.Usuario; import play.Play; import play.mvc.*; import play.data.validation.*; import play.libs.*; import play.utils.*; public class Secure extends Controller { @Before(unless={"login", "authenticate", "logout"}) static void checkAccess() throws Throwable { // Authent if(!session.contains("username")) { flash.put("url", "GET".equals(request.method) ? request.url : Play.ctxPath + "/"); // seems a good default login(); } // Checks Check check = getActionAnnotation(Check.class); if(check != null) { check(check); } check = getControllerInheritedAnnotation(Check.class); if(check != null) { check(check); } } private static void check(Check check) throws Throwable { for(String profile : check.value()) { boolean hasProfile = (Boolean)Security.invoke("check", profile); if(!hasProfile) { Security.invoke("onCheckFailed", profile); } } } // ~~~ Login public static void login() throws Throwable { Http.Cookie remember = request.cookies.get("rememberme"); if(remember != null) { int firstIndex = remember.value.indexOf("-"); int lastIndex = remember.value.lastIndexOf("-"); if (lastIndex > firstIndex) { String sign = remember.value.substring(0, firstIndex); String restOfCookie = remember.value.substring(firstIndex + 1); String username = remember.value.substring(firstIndex + 1, lastIndex); String time = remember.value.substring(lastIndex + 1); Date expirationDate = new Date(Long.parseLong(time)); // surround with try/catch? Date now = new Date(); if (expirationDate == null || expirationDate.before(now)) { logout(); } if(Crypto.sign(restOfCookie).equals(sign)) { session.put("username", username); redirectToOriginalURL(); } } } flash.keep("url"); render(); } public static void authenticate(@Required String username, String password, boolean remember) throws Throwable { // Check tokens //Boolean allowed = false; Usuario usuario = Usuario.find("usuario = ? and clave = ?", username, password).first(); if(usuario != null){ //session.put("nombreCompleto", usuario.nombreCompleto); //session.put("idUsuario", usuario.id); //if(usuario.tienda != null){ //session.put("idTienda", usuario.id); //} //allowed = true; } else { flash.keep("url"); flash.error("secure.error"); params.flash(); login(); } /*try { // This is the deprecated method name allowed = (Boolean)Security.invoke("authenticate", username, password); } catch (UnsupportedOperationException e ) { // This is the official method name allowed = (Boolean)Security.invoke("authenticate", username, password); }*/ /*if(validation.hasErrors() || !allowed) { flash.keep("url"); flash.error("secure.error"); params.flash(); login(); }*/ // Mark user as connected session.put("username", username); // Remember if needed if(remember) { Date expiration = new Date(); String duration = "30d"; // maybe make this override-able expiration.setTime(expiration.getTime() + Time.parseDuration(duration)); response.setCookie("rememberme", Crypto.sign(username + "-" + expiration.getTime()) + "-" + username + "-" + expiration.getTime(), duration); } // Redirect to the original URL (or /) redirectToOriginalURL(); } public static void logout() throws Throwable { Security.invoke("onDisconnect"); session.clear(); response.removeCookie("rememberme"); Security.invoke("onDisconnected"); flash.success("secure.logout"); login(); } // ~~~ Utils static void redirectToOriginalURL() throws Throwable { Security.invoke("onAuthenticated"); String url = flash.get("url"); if(url == null) { url = Play.ctxPath + "/"; } redirect(url); } public static class Security extends Controller { /** * @Deprecated * * @param username * @param password * @return */ static boolean authentify(String username, String password) { throw new UnsupportedOperationException(); } /** * This method is called during the authentication process. This is where you check if * the user is allowed to log in into the system. This is the actual authentication process * against a third party system (most of the time a DB). * * @param username * @param password * @return true if the authentication process succeeded */ static boolean authenticate(String username, String password) { return true; } /** * This method checks that a profile is allowed to view this page/method. This method is called prior * to the method's controller annotated with the @Check method. * * @param profile * @return true if you are allowed to execute this controller method. */ static boolean check(String profile) { return true; } /** * This method returns the current connected username * @return */ static String connected() { return session.get("username"); } /** * Indicate if a user is currently connected * @return true if the user is connected */ static boolean isConnected() { return session.contains("username"); } /** * This method is called after a successful authentication. * You need to override this method if you with to perform specific actions (eg. Record the time the user signed in) */ static void onAuthenticated() { } /** * This method is called before a user tries to sign off. * You need to override this method if you wish to perform specific actions (eg. Record the name of the user who signed off) */ static void onDisconnect() { } /** * This method is called after a successful sign off. * You need to override this method if you wish to perform specific actions (eg. Record the time the user signed off) */ static void onDisconnected() { } /** * This method is called if a check does not succeed. By default it shows the not allowed page (the controller forbidden method). * @param profile */ static void onCheckFailed(String profile) { forbidden(); } private static Object invoke(String m, Object... args) throws Throwable { try { return Java.invokeChildOrStatic(Security.class, m, args); } catch(InvocationTargetException e) { throw e.getTargetException(); } } } }
marti1125/Project_Store
app/controllers/Secure.java
Java
mit
7,739
from django.shortcuts import redirect from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from paste.models import Paste, Language @csrf_exempt def add(request): print "jojo" if request.method == 'POST': language = request.POST['language'] content = request.POST['content'] try: lang = Language.objects.get(pk=language) except: print "lang not avalible", language lang = Language.objects.get(pk='txt') paste = Paste(content=content, language=lang) paste.save() paste = Paste.objects.latest() return HttpResponse(paste.pk, content_type='text/plain') else: return redirect('/api')
spezifanta/Paste-It
api/v01/views.py
Python
mit
749
module Ahoy module Stores class ActiveRecordStore < BaseStore def track_visit(options, &block) visit = visit_model.new do |v| v.id = ahoy.visit_id v.visitor_id = ahoy.visitor_id v.user = user if v.respond_to?(:user=) end set_visit_properties(visit) yield(visit) if block_given? begin visit.save! geocode(visit) rescue *unique_exception_classes # do nothing end end def track_event(name, properties, options, &block) event = event_model.new do |e| e.id = options[:id] e.visit_id = ahoy.visit_id e.visitor_id = ahoy.visitor_id e.user = user e.name = name properties.each do |name, value| e.properties.build(name: name, value: value) end end yield(event) if block_given? begin event.save! rescue *unique_exception_classes # do nothing end end def visit @visit ||= visit_model.where(id: ahoy.visit_id).first if ahoy.visit_id end protected def visit_model ::Visit end def event_model ::Ahoy::Event end end end end
littlebitselectronics/ahoy
lib/ahoy/stores/active_record_store.rb
Ruby
mit
1,335
import {extend} from 'lodash'; export default class User { /** * The User class * @class * @param {Object} user * @return {Object} A User */ constructor(user) { extend(this, user); console.log(this); } }
mpaarating/sports-thing-web
client/app/users/models/user.js
JavaScript
mit
236
using UnityEngine; using System.Collections; public class Intro : MonoBehaviour { public GameObject martin; public GameObject mrsStrump; public GameObject strumpFire; public Sprite sadMartin, slinkton, police, candles, houses, strumps; public Camera cam; // Use this for initialization void Start () { strumpFire.GetComponent<SpriteRenderer>().enabled = false; } // Update is called once per frame void Update () { if (Input.GetKeyDown ("space") || Input.GetMouseButtonDown (0)) Application.LoadLevel ("game"); float time = Time.timeSinceLevelLoad; if (time > 4.0F && time < 4.5F) { mrsStrump.transform.position = new Vector3(-13, 0, -5); } if (time > 4.5F && time < 4.6F) { mrsStrump.transform.position = new Vector3(-13, -1, -5); } if (time > 17.2F && time < 17.7F) { martin.transform.position = new Vector3(-11, 0, -5); } if (time > 17.7F && time < 17.8F) { martin.transform.position = new Vector3(-11, -1, -5); } if (time > 18.5F && time < 18.6F) { cam.transform.position = new Vector3(-4, 0, -10); } if (time > 18.6F && time < 18.7F) { martin.GetComponent<Rigidbody2D>().velocity = new Vector2(11, 0); martin.GetComponent<SpriteRenderer>().sprite = sadMartin; } if (time > 20.0F && time < 20.1F) { martin.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 0); martin.transform.position = new Vector3(5.8F, -2, -5); } if (time > 33.0F && time < 33.1F) { strumpFire.GetComponent<SpriteRenderer>().enabled = true; } if (time > 35.0F && time < 35.1F) { strumpFire.GetComponent<SpriteRenderer>().sprite = slinkton; } if (time > 37.7F && time < 37.8F) { strumpFire.GetComponent<SpriteRenderer>().sprite = police; } if (time > 39.2F && time < 39.3F) { strumpFire.GetComponent<SpriteRenderer>().sprite = candles; } if (time > 41.0F && time < 41.1F) { strumpFire.GetComponent<SpriteRenderer>().sprite = houses; } if (time > 42.5F && time < 42.6F) { strumpFire.GetComponent<SpriteRenderer>().sprite = strumps; } if (time > 43.5F && time < 43.6F) { strumpFire.GetComponent<SpriteRenderer>().enabled = false; } if (time > 51.5F) Application.LoadLevel ("game"); } }
Bonfanti/Platformer
S Run Ronald Strump/Assets/scripts/Intro.cs
C#
mit
2,199
module Parsers module Edi class IncomingTransaction attr_reader :errors def self.from_etf(etf, i_cache) incoming_transaction = new(etf) subscriber_policy_loop = etf.subscriber_loop.policy_loops.first find_policy = FindPolicy.new(incoming_transaction) policy = find_policy.by_subkeys({ :eg_id => subscriber_policy_loop.eg_id, :hios_plan_id => subscriber_policy_loop.hios_id }) person_loop_validator = PersonLoopValidator.new etf.people.each do |person_loop| person_loop_validator.validate(person_loop, incoming_transaction, policy) end policy_loop_validator = PolicyLoopValidator.new policy_loop_validator.validate(subscriber_policy_loop, incoming_transaction) incoming_transaction end def initialize(etf) @etf = etf @errors = [] end def valid? @errors.empty? end def import return unless valid? is_policy_term = false is_policy_cancel = false is_non_payment = false old_npt_flag = @policy.term_for_np @etf.people.each do |person_loop| begin enrollee = @policy.enrollee_for_member_id(person_loop.member_id) policy_loop = person_loop.policy_loops.first enrollee.c_id = person_loop.carrier_member_id enrollee.cp_id = policy_loop.id if(!@etf.is_shop? && policy_loop.action == :stop ) enrollee.coverage_status = 'inactive' enrollee.coverage_end = policy_loop.coverage_end if enrollee.subscriber? is_non_payment = person_loop.non_payment_change? if enrollee.coverage_start == enrollee.coverage_end is_policy_cancel = true policy_end_date = enrollee.coverage_end enrollee.policy.aasm_state = "canceled" enrollee.policy.term_for_np = is_non_payment enrollee.policy.save else is_policy_term = true policy_end_date = enrollee.coverage_end enrollee.policy.aasm_state = "terminated" enrollee.policy.term_for_np = is_non_payment enrollee.policy.save end end end rescue Exception puts @policy.eg_id puts person_loop.member_id raise $! end end save_val = @policy.save unless exempt_from_notification?(@policy, is_policy_cancel, is_policy_term, old_npt_flag == is_non_payment) Observers::PolicyUpdated.notify(@policy) end if is_policy_term # Broadcast the term reason_headers = if is_non_payment {:qualifying_reason => "urn:openhbx:terms:v1:benefit_maintenance#non_payment"} else {} end Amqp::EventBroadcaster.with_broadcaster do |eb| eb.broadcast( { :routing_key => "info.events.policy.terminated", :headers => { :resource_instance_uri => @policy.eg_id, :event_effective_date => @policy.policy_end.strftime("%Y%m%d"), :hbx_enrollment_ids => JSON.dump(@policy.hbx_enrollment_ids) }.merge(reason_headers) }, "") end elsif is_policy_cancel # Broadcast the cancel reason_headers = if is_non_payment {:qualifying_reason => "urn:openhbx:terms:v1:benefit_maintenance#non_payment"} else {} end Amqp::EventBroadcaster.with_broadcaster do |eb| eb.broadcast( { :routing_key => "info.events.policy.canceled", :headers => { :resource_instance_uri => @policy.eg_id, :event_effective_date => @policy.policy_end.strftime("%Y%m%d"), :hbx_enrollment_ids => JSON.dump(@policy.hbx_enrollment_ids) }.merge(reason_headers) }, "") end end save_val end def exempt_from_notification?(policy, is_cancel, is_term, npt_changed) return false if is_cancel return false if npt_changed return false unless is_term (policy.policy_end.day == 31) && (policy.policy_end.month == 12) end def policy_found(policy) @policy = policy end def termination_with_no_end_date(details) @errors << "File is a termination, but no or invalid end date is provided for a member: Member #{details[:member_id]}, Coverage End: #{details[:coverage_end_string]}" end def coverage_end_before_coverage_start(details) @errors << "Coverage end before coverage start: Member #{details[:member_id]}, coverage_start: #{details[:coverage_start]}, coverage_end: #{details[:coverage_end]}" end def term_or_cancel_for_2014_individual(details) @errors << "Cancel/Term issued on 2014 policy. Member #{details[:member_id]}, end date #{details[:date]}" end def effectuation_date_mismatch(details) @errors << "Effectuation date mismatch: member #{details[:member_id]}, enrollee start: #{details[:policy]}, effectuation start: #{details[:effectuation]}" end def indeterminate_policy_expiration(details) @errors << "Could not determine natural policy expiration date: member #{details[:member_id]}" end def termination_date_after_expiration(details) @errors << "Termination date after natural policy expiration: member #{details[:member_id]}, coverage end: #{details[:coverage_end]}, expiration_date: #{details[:expiration_date]}" end def policy_not_found(subkeys) @errors << "Policy not found. Details: #{subkeys}" end def plan_found(plan) @plan = plan end def plan_not_found(hios_id) @errors << "Plan not found. (hios id: #{hios_id})" end def carrier_found(carrier) @carrier = carrier end def carrier_not_found(fein) @errors << "Carrier not found. (fein: #{fein})" end def found_carrier_member_id(id) end def missing_carrier_member_id(person_loop) policy_loop = person_loop.policy_loops.first if(!policy_loop.canceled?) @errors << "Missing Carrier Member ID." end end def no_such_member(id) @errors << "Member not found in policy: #{id}" end def found_carrier_policy_id(id) end def missing_carrier_policy_id @errors << "Missing Carrier Policy ID." end def policy_id @policy ? @policy._id : nil end def carrier_id @carrier ? @carrier._id : nil end def employer_id @employer ? @employer._id : nil end end end end
dchbx/gluedb
app/models/parsers/edi/incoming_transaction.rb
Ruby
mit
7,194
exports._buildExclamationKeyObject = function (tuples) { var valueMap = {}; tuples.forEach(function (tuple) { valueMap['!' + tuple.value0] = tuple.value1; }); return valueMap; }; var templatePattern = /\$\{([^}]+)\}/g; exports._getTemplateVars = function (str) { return (str.match(templatePattern) || []).map(function (str) { return str.substring(2, str.length - 1); }); };
LiamGoodacre/purescript-template-strings
src/Data/TemplateString/TemplateString.js
JavaScript
mit
397
/** * @overview * API handler action creator * Takes a key-value -pair representing the event to handle as key and its respective * handler function as the value. * * Event-to-URL mapping is done in {@link ApiEventPaths}. * * @since 0.2.0 * @version 0.3.0 */ import { Seq, Map } from 'immutable'; import { createAction } from 'redux-actions'; import { Internal } from '../records'; import { ApiEventPaths } from '../constants'; import * as apiHandlerFns from '../actions/kcsapi'; /** * Ensure that the action handlers are mapped into {@link ApiHandler} records. * @type {Immutable.Iterable<any, any>} * @since 0.2.0 */ export const handlers = Seq.Keyed(ApiEventPaths) .flatMap((path, event) => Map.of(event, new Internal.ApiHandler({ path, event, handler: apiHandlerFns[event] }))); /** * A non-`Seq` version of the @see findEventSeq function. * @param {string} findPath * @returns {string} * @since 0.2.0 * @version 0.3.0 */ export const findEvent = (findPath) => { const pathRegex = new RegExp(`^${findPath}$`); return ApiEventPaths.findKey((path) => pathRegex.test(path)); }; /** * Create a `Seq` of action handlers that is in a usable form for the Redux application. * @type {Immutable.Iterable<any, any>} * @since 0.2.0 */ export const actionHandlers = Seq.Keyed(handlers) .flatMap((handlerRecord, event) => Map.of(event, createAction(event, handlerRecord.handler)));
rensouhou/dockyard-app
app/actions/api-actions.js
JavaScript
mit
1,532
// xParentN 2, Copyright 2005-2007 Olivier Spinelli // Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL function xParentN(e, n) { while (e && n--) e = e.parentNode; return e; }
sambaker/awe-core
test/x/lib/xparentn.js
JavaScript
mit
230
<?php /** * @file include/zot.php * @brief Hubzilla implementation of zot protocol. * * https://github.com/friendica/red/wiki/zot * https://github.com/friendica/red/wiki/Zot---A-High-Level-Overview * */ require_once('include/crypto.php'); require_once('include/items.php'); require_once('include/hubloc.php'); require_once('include/queue_fn.php'); require_once('include/perm_upgrade.php'); /** * @brief Generates a unique string for use as a zot guid. * * Generates a unique string for use as a zot guid using our DNS-based url, the * channel nickname and some entropy. * The entropy ensures uniqueness against re-installs where the same URL and * nickname are chosen. * * @note zot doesn't require this to be unique. Internally we use a whirlpool * hash of this guid and the signature of this guid signed with the channel * private key. This can be verified and should make the probability of * collision of the verified result negligible within the constraints of our * immediate universe. * * @param string $channel_nick a unique nickname of controlling entity * @returns string */ function zot_new_uid($channel_nick) { $rawstr = z_root() . '/' . $channel_nick . '.' . mt_rand(); return(base64url_encode(hash('whirlpool', $rawstr, true), true)); } /** * @brief Generates a portable hash identifier for a channel. * * Generates a portable hash identifier for the channel identified by $guid and * signed with $guid_sig. * * @note This ID is portable across the network but MUST be calculated locally * by verifying the signature and can not be trusted as an identity. * * @param string $guid * @param string $guid_sig */ function make_xchan_hash($guid, $guid_sig) { return base64url_encode(hash('whirlpool', $guid . $guid_sig, true)); } /** * @brief Given a zot hash, return all distinct hubs. * * This function is used in building the zot discovery packet and therefore * should only be used by channels which are defined on this hub. * * @param string $hash - xchan_hash * @returns array of hubloc (hub location structures) * * \b hubloc_id int * * \b hubloc_guid char(255) * * \b hubloc_guid_sig text * * \b hubloc_hash char(255) * * \b hubloc_addr char(255) * * \b hubloc_flags int * * \b hubloc_status int * * \b hubloc_url char(255) * * \b hubloc_url_sig text * * \b hubloc_host char(255) * * \b hubloc_callback char(255) * * \b hubloc_connect char(255) * * \b hubloc_sitekey text * * \b hubloc_updated datetime * * \b hubloc_connected datetime */ function zot_get_hublocs($hash) { /* Only search for active hublocs - e.g. those that haven't been marked deleted */ $ret = q("select * from hubloc where hubloc_hash = '%s' and hubloc_deleted = 0 order by hubloc_url ", dbesc($hash) ); return $ret; } /** * @brief Builds a zot notification packet. * * Builds a zot notification packet that you can either store in the queue with * a message array or call zot_zot to immediately zot it to the other side. * * @param array $channel * sender channel structure * @param string $type * packet type: one of 'ping', 'pickup', 'purge', 'refresh', 'force_refresh', 'notify', 'auth_check' * @param array $recipients * envelope information, array ( 'guid' => string, 'guid_sig' => string ); empty for public posts * @param string $remote_key * optional public site key of target hub used to encrypt entire packet * NOTE: remote_key and encrypted packets are required for 'auth_check' packets, optional for all others * @param string $secret * random string, required for packets which require verification/callback * e.g. 'pickup', 'purge', 'notify', 'auth_check'. Packet types 'ping', 'force_refresh', and 'refresh' do not require verification * @param string $extra * @returns string json encoded zot packet */ function zot_build_packet($channel, $type = 'notify', $recipients = null, $remote_key = null, $secret = null, $extra = null) { $data = array( 'type' => $type, 'sender' => array( 'guid' => $channel['channel_guid'], 'guid_sig' => base64url_encode(rsa_sign($channel['channel_guid'],$channel['channel_prvkey'])), 'url' => z_root(), 'url_sig' => base64url_encode(rsa_sign(z_root(),$channel['channel_prvkey'])), 'sitekey' => get_config('system','pubkey') ), 'callback' => '/post', 'version' => ZOT_REVISION ); if ($recipients) { for ($x = 0; $x < count($recipients); $x ++) unset($recipients[$x]['hash']); $data['recipients'] = $recipients; } if ($secret) { $data['secret'] = $secret; $data['secret_sig'] = base64url_encode(rsa_sign($secret,$channel['channel_prvkey'])); } if ($extra) { foreach ($extra as $k => $v) $data[$k] = $v; } logger('zot_build_packet: ' . print_r($data,true), LOGGER_DATA, LOG_DEBUG); // Hush-hush ultra top-secret mode if ($remote_key) { $data = crypto_encapsulate(json_encode($data),$remote_key); } return json_encode($data); } /** * @brief * * @see z_post_url() * * @param string $url * @param array $data * @return array see z_post_url() for returned data format */ function zot_zot($url, $data) { return z_post_url($url, array('data' => $data)); } /** * @brief Look up information about channel. * * @param string $webbie * does not have to be host qualified e.g. 'foo' is treated as 'foo\@thishub' * @param array $channel * (optional), if supplied permissions will be enumerated specifically for $channel * @param boolean $autofallback * fallback/failover to http if https connection cannot be established. Default is true. * * @return array see z_post_url() and \ref mod/zfinger.php */ function zot_finger($webbie, $channel = null, $autofallback = true) { if (strpos($webbie,'@') === false) { $address = $webbie; $host = App::get_hostname(); } else { $address = substr($webbie,0,strpos($webbie,'@')); $host = substr($webbie,strpos($webbie,'@')+1); } $xchan_addr = $address . '@' . $host; if ((! $address) || (! $xchan_addr)) { logger('zot_finger: no address :' . $webbie); return array('success' => false); } logger('using xchan_addr: ' . $xchan_addr, LOGGER_DATA, LOG_DEBUG); // potential issue here; the xchan_addr points to the primary hub. // The webbie we were called with may not, so it might not be found // unless we query for hubloc_addr instead of xchan_addr $r = q("select xchan.*, hubloc.* from xchan left join hubloc on xchan_hash = hubloc_hash where xchan_addr = '%s' and hubloc_primary = 1 limit 1", dbesc($xchan_addr) ); if ($r) { $url = $r[0]['hubloc_url']; if ($r[0]['hubloc_network'] && $r[0]['hubloc_network'] !== 'zot') { logger('zot_finger: alternate network: ' . $webbie); logger('url: '.$url.', net: '.var_export($r[0]['hubloc_network'],true), LOGGER_DATA, LOG_DEBUG); return array('success' => false); } } else { $url = 'https://' . $host; } $rhs = '/.well-known/zot-info'; $https = ((strpos($url,'https://') === 0) ? true : false); logger('zot_finger: ' . $address . ' at ' . $url, LOGGER_DEBUG); if ($channel) { $postvars = array( 'address' => $address, 'target' => $channel['channel_guid'], 'target_sig' => $channel['channel_guid_sig'], 'key' => $channel['channel_pubkey'] ); $result = z_post_url($url . $rhs,$postvars); if ((! $result['success']) && ($autofallback)) { if ($https) { logger('zot_finger: https failed. falling back to http'); $result = z_post_url('http://' . $host . $rhs,$postvars); } } } else { $rhs .= '?f=&address=' . urlencode($address); $result = z_fetch_url($url . $rhs); if ((! $result['success']) && ($autofallback)) { if ($https) { logger('zot_finger: https failed. falling back to http'); $result = z_fetch_url('http://' . $host . $rhs); } } } if (! $result['success']) logger('zot_finger: no results'); return $result; } /** * @brief Refreshes after permission changed or friending, etc. * * zot_refresh is typically invoked when somebody has changed permissions of a channel and they are notified * to fetch new permissions via a finger/discovery operation. This may result in a new connection * (abook entry) being added to a local channel and it may result in auto-permissions being granted. * * Friending in zot is accomplished by sending a refresh packet to a specific channel which indicates a * permission change has been made by the sender which affects the target channel. The hub controlling * the target channel does targetted discovery (a zot-finger request requesting permissions for the local * channel). These are decoded here, and if necessary and abook structure (addressbook) is created to store * the permissions assigned to this channel. * * Initially these abook structures are created with a 'pending' flag, so that no reverse permissions are * implied until this is approved by the owner channel. A channel can also auto-populate permissions in * return and send back a refresh packet of its own. This is used by forum and group communication channels * so that friending and membership in the channel's "club" is automatic. * * @param array $them => xchan structure of sender * @param array $channel => local channel structure of target recipient, required for "friending" operations * @param array $force default false * * @returns boolean true if successful, else false */ function zot_refresh($them, $channel = null, $force = false) { if (array_key_exists('xchan_network', $them) && ($them['xchan_network'] !== 'zot')) { logger('zot_refresh: not got zot. ' . $them['xchan_name']); return true; } logger('zot_refresh: them: ' . print_r($them,true), LOGGER_DATA, LOG_DEBUG); if ($channel) logger('zot_refresh: channel: ' . print_r($channel,true), LOGGER_DATA, LOG_DEBUG); $url = null; if ($them['hubloc_url']) { $url = $them['hubloc_url']; } else { $r = null; // if they re-installed the server we could end up with the wrong record - pointing to the old install. // We'll order by reverse id to try and pick off the newest one first and hopefully end up with the // correct hubloc. If this doesn't work we may have to re-write this section to try them all. if(array_key_exists('xchan_addr',$them) && $them['xchan_addr']) { $r = q("select hubloc_url, hubloc_primary from hubloc where hubloc_addr = '%s' order by hubloc_id desc", dbesc($them['xchan_addr']) ); } if(! $r) { $r = q("select hubloc_url, hubloc_primary from hubloc where hubloc_hash = '%s' order by hubloc_id desc", dbesc($them['xchan_hash']) ); } if ($r) { foreach ($r as $rr) { if (intval($rr['hubloc_primary'])) { $url = $rr['hubloc_url']; break; } } if (! $url) $url = $r[0]['hubloc_url']; } } if (! $url) { logger('zot_refresh: no url'); return false; } $token = random_string(); $postvars = array(); $postvars['token'] = $token; if($channel) { $postvars['target'] = $channel['channel_guid']; $postvars['target_sig'] = $channel['channel_guid_sig']; $postvars['key'] = $channel['channel_pubkey']; } if (array_key_exists('xchan_addr',$them) && $them['xchan_addr']) $postvars['address'] = $them['xchan_addr']; if (array_key_exists('xchan_hash',$them) && $them['xchan_hash']) $postvars['guid_hash'] = $them['xchan_hash']; if (array_key_exists('xchan_guid',$them) && $them['xchan_guid'] && array_key_exists('xchan_guid_sig',$them) && $them['xchan_guid_sig']) { $postvars['guid'] = $them['xchan_guid']; $postvars['guid_sig'] = $them['xchan_guid_sig']; } $rhs = '/.well-known/zot-info'; $result = z_post_url($url . $rhs,$postvars); logger('zot_refresh: zot-info: ' . print_r($result,true), LOGGER_DATA, LOG_DEBUG); if ($result['success']) { $j = json_decode($result['body'],true); if (! (($j) && ($j['success']))) { logger('zot_refresh: result not decodable'); return false; } $signed_token = ((is_array($j) && array_key_exists('signed_token',$j)) ? $j['signed_token'] : null); if($signed_token) { $valid = rsa_verify('token.' . $token,base64url_decode($signed_token),$j['key']); if(! $valid) { logger('invalid signed token: ' . $url . $rhs, LOGGER_NORMAL, LOG_ERR); return false; } } else { logger('No signed token from ' . $url . $rhs, LOGGER_NORMAL, LOG_WARNING); // after 2017-01-01 this will be a hard error unless you over-ride it. if((time() > 1483228800) && (! get_config('system','allow_unsigned_zotfinger'))) { return false; } } $x = import_xchan($j, (($force) ? UPDATE_FLAGS_FORCED : UPDATE_FLAGS_UPDATED)); if(! $x['success']) return false; if($channel) { if($j['permissions']['data']) { $permissions = crypto_unencapsulate(array( 'data' => $j['permissions']['data'], 'key' => $j['permissions']['key'], 'iv' => $j['permissions']['iv']), $channel['channel_prvkey']); if($permissions) $permissions = json_decode($permissions,true); logger('decrypted permissions: ' . print_r($permissions,true), LOGGER_DATA, LOG_DEBUG); } else $permissions = $j['permissions']; $connected_set = false; if($permissions && is_array($permissions)) { $old_read_stream_perm = get_abconfig($channel['channel_id'],$x['hash'],'their_perms','view_stream'); foreach($permissions as $k => $v) { set_abconfig($channel['channel_id'],$x['hash'],'their_perms',$k,$v); } } if(array_key_exists('profile',$j) && array_key_exists('next_birthday',$j['profile'])) { $next_birthday = datetime_convert('UTC','UTC',$j['profile']['next_birthday']); } else { $next_birthday = NULL_DATE; } $r = q("select * from abook where abook_xchan = '%s' and abook_channel = %d and abook_self = 0 limit 1", dbesc($x['hash']), intval($channel['channel_id']) ); if($r) { // connection exists // if the dob is the same as what we have stored (disregarding the year), keep the one // we have as we may have updated the year after sending a notification; and resetting // to the one we just received would cause us to create duplicated events. if(substr($r[0]['abook_dob'],5) == substr($next_birthday,5)) $next_birthday = $r[0]['abook_dob']; $y = q("update abook set abook_dob = '%s' where abook_xchan = '%s' and abook_channel = %d and abook_self = 0 ", dbescdate($next_birthday), dbesc($x['hash']), intval($channel['channel_id']) ); if(! $y) logger('abook update failed'); else { // if we were just granted read stream permission and didn't have it before, try to pull in some posts if((! $old_read_stream_perm) && (intval($permissions['view_stream']))) Zotlabs\Daemon\Master::Summon(array('Onepoll',$r[0]['abook_id'])); } } else { // new connection $my_perms = null; $automatic = false; $role = get_pconfig($channel['channel_id'],'system','permissions_role'); if($role) { $xx = \Zotlabs\Access\PermissionRoles::role_perms($role); if($xx['perms_auto']) { $automatic = true; $default_perms = $xx['perms_connect']; $my_perms = \Zotlabs\Access\Permissions::FilledPerms($default_perms); } } if(! $my_perms) { $m = \Zotlabs\Access\Permissions::FilledAutoperms($channel['channel_id']); if($m) { $automatic = true; $my_perms = $m; } } if($my_perms) { foreach($my_perms as $k => $v) { set_abconfig($channel['channel_id'],$x['hash'],'my_perms',$k,$v); } } // Keep original perms to check if we need to notify them $previous_perms = get_all_perms($channel['channel_id'],$x['hash']); $closeness = get_pconfig($channel['channel_id'],'system','new_abook_closeness'); if($closeness === false) $closeness = 80; $y = q("insert into abook ( abook_account, abook_channel, abook_closeness, abook_xchan, abook_created, abook_updated, abook_dob, abook_pending ) values ( %d, %d, %d, '%s', '%s', '%s', '%s', %d )", intval($channel['channel_account_id']), intval($channel['channel_id']), intval($closeness), dbesc($x['hash']), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc($next_birthday), intval(($automatic) ? 0 : 1) ); if($y) { logger("New introduction received for {$channel['channel_name']}"); $new_perms = get_all_perms($channel['channel_id'],$x['hash']); // Send a clone sync packet and a permissions update if permissions have changed $new_connection = q("select * from abook left join xchan on abook_xchan = xchan_hash where abook_xchan = '%s' and abook_channel = %d and abook_self = 0 order by abook_created desc limit 1", dbesc($x['hash']), intval($channel['channel_id']) ); if($new_connection) { if(! \Zotlabs\Access\Permissions::PermsCompare($new_perms,$previous_perms)) Zotlabs\Daemon\Master::Summon(array('Notifier','permission_create',$new_connection[0]['abook_id'])); Zotlabs\Lib\Enotify::submit(array( 'type' => NOTIFY_INTRO, 'from_xchan' => $x['hash'], 'to_xchan' => $channel['channel_hash'], 'link' => z_root() . '/connedit/' . $new_connection[0]['abook_id'], )); if(intval($permissions['view_stream'])) { if(intval(get_pconfig($channel['channel_id'],'perm_limits','send_stream') & PERMS_PENDING) || (! intval($new_connection[0]['abook_pending']))) Zotlabs\Daemon\Master::Summon(array('Onepoll',$new_connection[0]['abook_id'])); } /** If there is a default group for this channel, add this connection to it */ $default_group = $channel['channel_default_group']; if($default_group) { require_once('include/group.php'); $g = group_rec_byhash($channel['channel_id'],$default_group); if($g) group_add_member($channel['channel_id'],'',$x['hash'],$g['id']); } unset($new_connection[0]['abook_id']); unset($new_connection[0]['abook_account']); unset($new_connection[0]['abook_channel']); $abconfig = load_abconfig($channel['channel_id'],$new_connection['abook_xchan']); if($abconfig) $new_connection['abconfig'] = $abconfig; build_sync_packet($channel['channel_id'], array('abook' => $new_connection)); } } } } return true; } return false; } /** * @brief Look up if channel is known and previously verified. * * A guid and a url, both signed by the sender, distinguish a known sender at a * known location. * This function looks these up to see if the channel is known and therefore * previously verified. If not, we will need to verify it. * * @param array $arr an associative array which must contain: * * \e string \b guid => guid of conversant * * \e string \b guid_sig => guid signed with conversant's private key * * \e string \b url => URL of the origination hub of this communication * * \e string \b url_sig => URL signed with conversant's private key * * @returns array|null null if site is blacklisted or not found, otherwise an * array with an hubloc record */ function zot_gethub($arr,$multiple = false) { if($arr['guid'] && $arr['guid_sig'] && $arr['url'] && $arr['url_sig']) { if(! check_siteallowed($arr['url'])) { logger('blacklisted site: ' . $arr['url']); return null; } $limit = (($multiple) ? '' : ' limit 1 '); $sitekey = ((array_key_exists('sitekey',$arr) && $arr['sitekey']) ? " and hubloc_sitekey = '" . protect_sprintf($arr['sitekey']) . "' " : ''); $r = q("select * from hubloc where hubloc_guid = '%s' and hubloc_guid_sig = '%s' and hubloc_url = '%s' and hubloc_url_sig = '%s' $sitekey $limit", dbesc($arr['guid']), dbesc($arr['guid_sig']), dbesc($arr['url']), dbesc($arr['url_sig']) ); if($r) { logger('zot_gethub: found', LOGGER_DEBUG); return (($multiple) ? $r : $r[0]); } } logger('zot_gethub: not found: ' . print_r($arr,true), LOGGER_DEBUG); return null; } /** * @brief Registers an unknown hub. * * A communication has been received which has an unknown (to us) sender. * Perform discovery based on our calculated hash of the sender at the * origination address. This will fetch the discovery packet of the sender, * which contains the public key we need to verify our guid and url signatures. * * @param array $arr an associative array which must contain: * * \e string \b guid => guid of conversant * * \e string \b guid_sig => guid signed with conversant's private key * * \e string \b url => URL of the origination hub of this communication * * \e string \b url_sig => URL signed with conversant's private key * * @returns array an associative array with * * \b success boolean true or false * * \b message (optional) error string only if success is false */ function zot_register_hub($arr) { $result = array('success' => false); if($arr['url'] && $arr['url_sig'] && $arr['guid'] && $arr['guid_sig']) { $guid_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']); $url = $arr['url'] . '/.well-known/zot-info/?f=&guid_hash=' . $guid_hash; logger('zot_register_hub: ' . $url, LOGGER_DEBUG); $x = z_fetch_url($url); logger('zot_register_hub: ' . print_r($x,true), LOGGER_DATA, LOG_DEBUG); if($x['success']) { $record = json_decode($x['body'],true); /* * We now have a key - only continue registration if our signatures are valid * AND the guid and guid sig in the returned packet match those provided in * our current communication. */ if((rsa_verify($arr['guid'],base64url_decode($arr['guid_sig']),$record['key'])) && (rsa_verify($arr['url'],base64url_decode($arr['url_sig']),$record['key'])) && ($arr['guid'] === $record['guid']) && ($arr['guid_sig'] === $record['guid_sig'])) { $c = import_xchan($record); if($c['success']) $result['success'] = true; } else { logger('zot_register_hub: failure to verify returned packet.'); } } } return $result; } /** * @brief Takes an associative array of a fetched discovery packet and updates * all internal data structures which need to be updated as a result. * * @param array $arr => json_decoded discovery packet * @param int $ud_flags * Determines whether to create a directory update record if any changes occur, default is UPDATE_FLAGS_UPDATED * $ud_flags = UPDATE_FLAGS_FORCED indicates a forced refresh where we unconditionally create a directory update record * this typically occurs once a month for each channel as part of a scheduled ping to notify the directory * that the channel still exists * @param array $ud_arr * If set [typically by update_directory_entry()] indicates a specific update table row and more particularly * contains a particular address (ud_addr) which needs to be updated in that table. * * @return associative array * * \e boolean \b success boolean true or false * * \e string \b message (optional) error string only if success is false */ function import_xchan($arr,$ud_flags = UPDATE_FLAGS_UPDATED, $ud_arr = null) { call_hooks('import_xchan', $arr); $ret = array('success' => false); $dirmode = intval(get_config('system','directory_mode')); $changed = false; $what = ''; if(! (is_array($arr) && array_key_exists('success',$arr) && $arr['success'])) { logger('import_xchan: invalid data packet: ' . print_r($arr,true)); $ret['message'] = t('Invalid data packet'); return $ret; } if(! ($arr['guid'] && $arr['guid_sig'])) { logger('import_xchan: no identity information provided. ' . print_r($arr,true)); return $ret; } $xchan_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']); $arr['hash'] = $xchan_hash; $import_photos = false; if(! rsa_verify($arr['guid'],base64url_decode($arr['guid_sig']),$arr['key'])) { logger('import_xchan: Unable to verify channel signature for ' . $arr['address']); $ret['message'] = t('Unable to verify channel signature'); return $ret; } logger('import_xchan: ' . $xchan_hash, LOGGER_DEBUG); $r = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($xchan_hash) ); if(! array_key_exists('connect_url', $arr)) $arr['connect_url'] = ''; if(strpos($arr['address'],'/') !== false) $arr['address'] = substr($arr['address'],0,strpos($arr['address'],'/')); if($r) { if($r[0]['xchan_photo_date'] != $arr['photo_updated']) $import_photos = true; // if we import an entry from a site that's not ours and either or both of us is off the grid - hide the entry. /** @TODO: check if we're the same directory realm, which would mean we are allowed to see it */ $dirmode = get_config('system','directory_mode'); if((($arr['site']['directory_mode'] === 'standalone') || ($dirmode & DIRECTORY_MODE_STANDALONE)) && ($arr['site']['url'] != z_root())) $arr['searchable'] = false; $hidden = (1 - intval($arr['searchable'])); $hidden_changed = $adult_changed = $deleted_changed = $pubforum_changed = 0; if(intval($r[0]['xchan_hidden']) != (1 - intval($arr['searchable']))) $hidden_changed = 1; if(intval($r[0]['xchan_selfcensored']) != intval($arr['adult_content'])) $adult_changed = 1; if(intval($r[0]['xchan_deleted']) != intval($arr['deleted'])) $deleted_changed = 1; if(intval($r[0]['xchan_pubforum']) != intval($arr['public_forum'])) $pubforum_changed = 1; if(($r[0]['xchan_name_date'] != $arr['name_updated']) || ($r[0]['xchan_connurl'] != $arr['connections_url']) || ($r[0]['xchan_addr'] != $arr['address']) || ($r[0]['xchan_follow'] != $arr['follow_url']) || ($r[0]['xchan_connpage'] != $arr['connect_url']) || ($r[0]['xchan_url'] != $arr['url']) || $hidden_changed || $adult_changed || $deleted_changed || $pubforum_changed ) { $rup = q("update xchan set xchan_name = '%s', xchan_name_date = '%s', xchan_connurl = '%s', xchan_follow = '%s', xchan_connpage = '%s', xchan_hidden = %d, xchan_selfcensored = %d, xchan_deleted = %d, xchan_pubforum = %d, xchan_addr = '%s', xchan_url = '%s' where xchan_hash = '%s'", dbesc(($arr['name']) ? $arr['name'] : '-'), dbesc($arr['name_updated']), dbesc($arr['connections_url']), dbesc($arr['follow_url']), dbesc($arr['connect_url']), intval(1 - intval($arr['searchable'])), intval($arr['adult_content']), intval($arr['deleted']), intval($arr['public_forum']), dbesc($arr['address']), dbesc($arr['url']), dbesc($xchan_hash) ); logger('import_xchan: update: existing: ' . print_r($r[0],true), LOGGER_DATA, LOG_DEBUG); logger('import_xchan: update: new: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); $what .= 'xchan '; $changed = true; } } else { $import_photos = true; if((($arr['site']['directory_mode'] === 'standalone') || ($dirmode & DIRECTORY_MODE_STANDALONE)) && ($arr['site']['url'] != z_root())) $arr['searchable'] = false; $x = q("insert into xchan ( xchan_hash, xchan_guid, xchan_guid_sig, xchan_pubkey, xchan_photo_mimetype, xchan_photo_l, xchan_addr, xchan_url, xchan_connurl, xchan_follow, xchan_connpage, xchan_name, xchan_network, xchan_photo_date, xchan_name_date, xchan_hidden, xchan_selfcensored, xchan_deleted, xchan_pubforum ) values ( '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d) ", dbesc($xchan_hash), dbesc($arr['guid']), dbesc($arr['guid_sig']), dbesc($arr['key']), dbesc($arr['photo_mimetype']), dbesc($arr['photo']), dbesc($arr['address']), dbesc($arr['url']), dbesc($arr['connections_url']), dbesc($arr['follow_url']), dbesc($arr['connect_url']), dbesc(($arr['name']) ? $arr['name'] : '-'), dbesc('zot'), dbescdate($arr['photo_updated']), dbescdate($arr['name_updated']), intval(1 - intval($arr['searchable'])), intval($arr['adult_content']), intval($arr['deleted']), intval($arr['public_forum']) ); $what .= 'new_xchan'; $changed = true; } if ($import_photos) { require_once('include/photo/photo_driver.php'); // see if this is a channel clone that's hosted locally - which we treat different from other xchans/connections $local = q("select channel_account_id, channel_id from channel where channel_hash = '%s' limit 1", dbesc($xchan_hash) ); if ($local) { $ph = z_fetch_url($arr['photo'], true); if ($ph['success']) { $hash = import_channel_photo($ph['body'], $arr['photo_mimetype'], $local[0]['channel_account_id'], $local[0]['channel_id']); if($hash) { // unless proven otherwise $is_default_profile = 1; $profile = q("select is_default from profile where aid = %d and uid = %d limit 1", intval($local[0]['channel_account_id']), intval($local[0]['channel_id']) ); if($profile) { if(! intval($profile[0]['is_default'])) $is_default_profile = 0; } // If setting for the default profile, unset the profile photo flag from any other photos I own if($is_default_profile) { q("UPDATE photo SET photo_usage = %d WHERE photo_usage = %d AND resource_id != '%s' AND aid = %d AND uid = %d", intval(PHOTO_NORMAL), intval(PHOTO_PROFILE), dbesc($hash), intval($local[0]['channel_account_id']), intval($local[0]['channel_id']) ); } } // reset the names in case they got messed up when we had a bug in this function $photos = array( z_root() . '/photo/profile/l/' . $local[0]['channel_id'], z_root() . '/photo/profile/m/' . $local[0]['channel_id'], z_root() . '/photo/profile/s/' . $local[0]['channel_id'], $arr['photo_mimetype'], false ); } } else { $photos = import_xchan_photo($arr['photo'], $xchan_hash); } if ($photos) { if ($photos[4]) { // importing the photo failed somehow. Leave the photo_date alone so we can try again at a later date. // This often happens when somebody joins the matrix with a bad cert. $r = q("update xchan set xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_hash = '%s'", dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), dbesc($photos[3]), dbesc($xchan_hash) ); } else { $r = q("update xchan set xchan_photo_date = '%s', xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_hash = '%s'", dbescdate(datetime_convert('UTC','UTC',$arr['photo_updated'])), dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), dbesc($photos[3]), dbesc($xchan_hash) ); } $what .= 'photo '; $changed = true; } } // what we are missing for true hub independence is for any changes in the primary hub to // get reflected not only in the hublocs, but also to update the URLs and addr in the appropriate xchan $s = sync_locations($arr, $arr); if($s) { if($s['change_message']) $what .= $s['change_message']; if($s['changed']) $changed = $s['changed']; if($s['message']) $ret['message'] .= $s['message']; } // Which entries in the update table are we interested in updating? $address = (($ud_arr && $ud_arr['ud_addr']) ? $ud_arr['ud_addr'] : $arr['address']); // Are we a directory server of some kind? $other_realm = false; $realm = get_directory_realm(); if(array_key_exists('site',$arr) && array_key_exists('realm',$arr['site']) && (strpos($arr['site']['realm'],$realm) === false)) $other_realm = true; if($dirmode != DIRECTORY_MODE_NORMAL) { // We're some kind of directory server. However we can only add directory information // if the entry is in the same realm (or is a sub-realm). Sub-realms are denoted by // including the parent realm in the name. e.g. 'RED_GLOBAL:foo' would allow an entry to // be in directories for the local realm (foo) and also the RED_GLOBAL realm. if(array_key_exists('profile',$arr) && is_array($arr['profile']) && (! $other_realm)) { $profile_changed = import_directory_profile($xchan_hash,$arr['profile'],$address,$ud_flags, 1); if($profile_changed) { $what .= 'profile '; $changed = true; } } else { logger('import_xchan: profile not available - hiding'); // they may have made it private $r = q("delete from xprof where xprof_hash = '%s'", dbesc($xchan_hash) ); $r = q("delete from xtag where xtag_hash = '%s' and xtag_flags = 0", dbesc($xchan_hash) ); } } if(array_key_exists('site',$arr) && is_array($arr['site'])) { $profile_changed = import_site($arr['site'],$arr['key']); if($profile_changed) { $what .= 'site '; $changed = true; } } if(($changed) || ($ud_flags == UPDATE_FLAGS_FORCED)) { $guid = random_string() . '@' . App::get_hostname(); update_modtime($xchan_hash,$guid,$address,$ud_flags); logger('import_xchan: changed: ' . $what,LOGGER_DEBUG); } elseif(! $ud_flags) { // nothing changed but we still need to update the updates record q("update updates set ud_flags = ( ud_flags | %d ) where ud_addr = '%s' and not (ud_flags & %d)>0 ", intval(UPDATE_FLAGS_UPDATED), dbesc($address), intval(UPDATE_FLAGS_UPDATED) ); } if(! x($ret,'message')) { $ret['success'] = true; $ret['hash'] = $xchan_hash; } logger('import_xchan: result: ' . print_r($ret,true), LOGGER_DATA, LOG_DEBUG); return $ret; } /** * @brief Called immediately after sending a zot message which is using queue processing. * * Updates the queue item according to the response result and logs any information * returned to aid communications troubleshooting. * * @param string $hub - url of site we just contacted * @param array $arr - output of z_post_url() * @param array $outq - The queue structure attached to this request */ function zot_process_response($hub, $arr, $outq) { if (! $arr['success']) { logger('zot_process_response: failed: ' . $hub); return; } $x = json_decode($arr['body'], true); if (! $x) { logger('zot_process_response: No json from ' . $hub); logger('zot_process_response: headers: ' . print_r($arr['header'],true), LOGGER_DATA, LOG_DEBUG); } if(is_array($x) && array_key_exists('delivery_report',$x) && is_array($x['delivery_report'])) { foreach($x['delivery_report'] as $xx) { if(is_array($xx) && array_key_exists('message_id',$xx) && delivery_report_is_storable($xx)) { q("insert into dreport ( dreport_mid, dreport_site, dreport_recip, dreport_result, dreport_time, dreport_xchan ) values ( '%s', '%s','%s','%s','%s','%s' ) ", dbesc($xx['message_id']), dbesc($xx['location']), dbesc($xx['recipient']), dbesc($xx['status']), dbesc(datetime_convert($xx['date'])), dbesc($xx['sender']) ); } } } // we have a more descriptive delivery report, so discard the per hub 'queued' report. q("delete from dreport where dreport_queue = '%s' ", dbesc($outq['outq_hash']) ); // update the timestamp for this site q("update site set site_dead = 0, site_update = '%s' where site_url = '%s'", dbesc(datetime_convert()), dbesc(dirname($hub)) ); // synchronous message types are handled immediately // async messages remain in the queue until processed. if(intval($outq['outq_async'])) remove_queue_item($outq['outq_hash'],$outq['outq_channel']); logger('zot_process_response: ' . print_r($x,true), LOGGER_DEBUG); } /** * @brief * * We received a notification packet (in mod_post) that a message is waiting for us, and we've verified the sender. * Now send back a pickup message, using our message tracking ID ($arr['secret']), which we will sign with our site * private key. * The entire pickup message is encrypted with the remote site's public key. * If everything checks out on the remote end, we will receive back a packet containing one or more messages, * which will be processed and delivered before this function ultimately returns. * * @see zot_import() * * @param array $arr * decrypted and json decoded notify packet from remote site * @return array from zot_import() */ function zot_fetch($arr) { logger('zot_fetch: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); $url = $arr['sender']['url'] . $arr['callback']; // set $multiple param on zot_gethub() to return all matching hubs // This allows us to recover from re-installs when a redundant (but invalid) hubloc for // this identity is widely dispersed throughout the network. $ret_hubs = zot_gethub($arr['sender'],true); if(! $ret_hubs) { logger('zot_fetch: no hub: ' . print_r($arr['sender'],true)); return; } foreach($ret_hubs as $ret_hub) { $data = array( 'type' => 'pickup', 'url' => z_root(), 'callback_sig' => base64url_encode(rsa_sign(z_root() . '/post',get_config('system','prvkey'))), 'callback' => z_root() . '/post', 'secret' => $arr['secret'], 'secret_sig' => base64url_encode(rsa_sign($arr['secret'],get_config('system','prvkey'))) ); $datatosend = json_encode(crypto_encapsulate(json_encode($data),$ret_hub['hubloc_sitekey'])); $fetch = zot_zot($url,$datatosend); $result = zot_import($fetch, $arr['sender']['url']); if($result) return $result; } return; } /** * @brief Process incoming array of messages. * * Process an incoming array of messages which were obtained via pickup, and * import, update, delete as directed. * * The message types handled here are 'activity' (e.g. posts), 'mail' , * 'profile', 'location' and 'channel_sync'. * * @param array $arr * 'pickup' structure returned from remote site * @param string $sender_url * the url specified by the sender in the initial communication. * We will verify the sender and url in each returned message structure and * also verify that all the messages returned match the site url that we are * currently processing. * * @returns array * suitable for logging remotely, enumerating the processing results of each message/recipient combination * * [0] => \e string $channel_hash * * [1] => \e string $delivery_status * * [2] => \e string $address */ function zot_import($arr, $sender_url) { $data = json_decode($arr['body'], true); if(! $data) { logger('zot_import: empty body'); return array(); } if(array_key_exists('iv', $data)) { $data = json_decode(crypto_unencapsulate($data,get_config('system','prvkey')),true); } if(! $data['success']) { if($data['message']) logger('remote pickup failed: ' . $data['message']); return false; } $incoming = $data['pickup']; $return = array(); if(is_array($incoming)) { foreach($incoming as $i) { if(! is_array($i)) { logger('incoming is not an array'); continue; } $result = null; if(array_key_exists('iv',$i['notify'])) { $i['notify'] = json_decode(crypto_unencapsulate($i['notify'],get_config('system','prvkey')),true); } logger('zot_import: notify: ' . print_r($i['notify'],true), LOGGER_DATA, LOG_DEBUG); $hub = zot_gethub($i['notify']['sender']); if((! $hub) || ($hub['hubloc_url'] != $sender_url)) { logger('zot_import: potential forgery: wrong site for sender: ' . $sender_url . ' != ' . print_r($i['notify'],true)); continue; } $message_request = ((array_key_exists('message_id',$i['notify'])) ? true : false); if($message_request) logger('processing message request'); $i['notify']['sender']['hash'] = make_xchan_hash($i['notify']['sender']['guid'],$i['notify']['sender']['guid_sig']); $deliveries = null; if(array_key_exists('message',$i) && array_key_exists('type',$i['message']) && $i['message']['type'] === 'rating') { // rating messages are processed only by directory servers logger('Rating received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); $result = process_rating_delivery($i['notify']['sender'],$i['message']); continue; } if(array_key_exists('recipients',$i['notify']) && count($i['notify']['recipients'])) { logger('specific recipients'); $recip_arr = array(); foreach($i['notify']['recipients'] as $recip) { if(is_array($recip)) { $recip_arr[] = make_xchan_hash($recip['guid'],$recip['guid_sig']); } } $r = false; if($recip_arr) { stringify_array_elms($recip_arr); $recips = implode(',',$recip_arr); $r = q("select channel_hash as hash from channel where channel_hash in ( " . $recips . " ) and channel_removed = 0 "); } if(! $r) { logger('recips: no recipients on this site'); continue; } // It's a specifically targetted post. If we were sent a public_scope hint (likely), // get rid of it so that it doesn't get stored and cause trouble. if(($i) && is_array($i) && array_key_exists('message',$i) && is_array($i['message']) && $i['message']['type'] === 'activity' && array_key_exists('public_scope',$i['message'])) unset($i['message']['public_scope']); $deliveries = $r; // We found somebody on this site that's in the recipient list. } else { if(($i['message']) && (array_key_exists('flags',$i['message'])) && (in_array('private',$i['message']['flags'])) && $i['message']['type'] === 'activity') { if(array_key_exists('public_scope',$i['message']) && $i['message']['public_scope'] === 'public') { // This should not happen but until we can stop it... logger('private message was delivered with no recipients.'); continue; } } logger('public post'); // Public post. look for any site members who are or may be accepting posts from this sender // and who are allowed to see them based on the sender's permissions $deliveries = allowed_public_recips($i); if($i['message'] && array_key_exists('type',$i['message']) && $i['message']['type'] === 'location') { $sys = get_sys_channel(); $deliveries = array(array('hash' => $sys['xchan_hash'])); } // if the scope is anything but 'public' we're going to store it as private regardless // of the private flag on the post. if($i['message'] && array_key_exists('public_scope',$i['message']) && $i['message']['public_scope'] !== 'public') { if(! array_key_exists('flags',$i['message'])) $i['message']['flags'] = array(); if(! in_array('private',$i['message']['flags'])) $i['message']['flags'][] = 'private'; } } // Go through the hash array and remove duplicates. array_unique() won't do this because the array is more than one level. $no_dups = array(); if($deliveries) { foreach($deliveries as $d) { if(! is_array($d)) { logger('Delivery hash array is not an array: ' . print_r($d,true)); continue; } if(! in_array($d['hash'],$no_dups)) $no_dups[] = $d['hash']; } if($no_dups) { $deliveries = array(); foreach($no_dups as $n) { $deliveries[] = array('hash' => $n); } } } if(! $deliveries) { logger('zot_import: no deliveries on this site'); continue; } if($i['message']) { if($i['message']['type'] === 'activity') { $arr = get_item_elements($i['message']); $v = validate_item_elements($i['message'],$arr); if(! $v['success']) { logger('Activity rejected: ' . $v['message'] . ' ' . print_r($i['message'],true)); continue; } logger('Activity received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); logger('Activity recipients: ' . print_r($deliveries,true), LOGGER_DATA, LOG_DEBUG); $relay = ((array_key_exists('flags',$i['message']) && in_array('relay',$i['message']['flags'])) ? true : false); $result = process_delivery($i['notify']['sender'],$arr,$deliveries,$relay,false,$message_request); } elseif($i['message']['type'] === 'mail') { $arr = get_mail_elements($i['message']); logger('Mail received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); logger('Mail recipients: ' . print_r($deliveries,true), LOGGER_DATA, LOG_DEBUG); $result = process_mail_delivery($i['notify']['sender'],$arr,$deliveries); } elseif($i['message']['type'] === 'profile') { $arr = get_profile_elements($i['message']); logger('Profile received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); logger('Profile recipients: ' . print_r($deliveries,true), LOGGER_DATA, LOG_DEBUG); $result = process_profile_delivery($i['notify']['sender'],$arr,$deliveries); } elseif($i['message']['type'] === 'channel_sync') { // $arr = get_channelsync_elements($i['message']); $arr = $i['message']; logger('Channel sync received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); logger('Channel sync recipients: ' . print_r($deliveries,true), LOGGER_DATA, LOG_DEBUG); $result = process_channel_sync_delivery($i['notify']['sender'],$arr,$deliveries); } elseif($i['message']['type'] === 'location') { $arr = $i['message']; logger('Location message received: ' . print_r($arr,true), LOGGER_DATA, LOG_DEBUG); logger('Location message recipients: ' . print_r($deliveries,true), LOGGER_DATA, LOG_DEBUG); $result = process_location_delivery($i['notify']['sender'],$arr,$deliveries); } } if($result){ $return = array_merge($return, $result); } } } return $return; } /** * @brief * * A public message with no listed recipients can be delivered to anybody who * has PERMS_NETWORK for that type of post, PERMS_AUTHED (in-network senders are * by definition authenticated) or PERMS_SITE and is one the same site, * or PERMS_SPECIFIC and the sender is a contact who is granted permissions via * their connection permissions in the address book. * Here we take a given message and construct a list of hashes of everybody * on the site that we should try and deliver to. * Some of these will be rejected, but this gives us a place to start. * * @param array $msg * @return NULL|array */ function public_recips($msg) { require_once('include/channel.php'); $check_mentions = false; $include_sys = false; if($msg['message']['type'] === 'activity') { if(! get_config('system','disable_discover_tab')) $include_sys = true; $perm = 'send_stream'; if(array_key_exists('flags',$msg['message']) && in_array('thread_parent', $msg['message']['flags'])) { // check mention recipient permissions on top level posts only $check_mentions = true; } else { // This doesn't look like it works so I have to explain what happened. These are my // notes (below) from when I got this section of code working. You would think that // we only have to find those with the requisite stream or comment permissions, // depending on whether this is a top-level post or a comment - but you would be wrong. // ... so public_recips and allowed_public_recips is working so much better // than before, but was still not quite right. We seem to be getting all the right // results for top-level posts now, but comments aren't getting through on channels // for which we've allowed them to send us their stream, but not comment on our posts. // The reason is we were seeing if they could comment - and we only need to do that if // we own the post. If they own the post, we only need to check if they can send us their stream. // if this is a comment and it wasn't sent by the post owner, check to see who is allowing them to comment. // We should have one specific recipient and this step shouldn't be needed unless somebody stuffed up // their software. We may need this step to protect us from bad guys intentionally stuffing up their software. // If it is sent by the post owner, we don't need to do this. We only need to see who is receiving the // owner's stream (which was already set above) - as they control the comment permissions, not us. // Note that by doing this we introduce another bug because some public forums have channel_w_stream // permissions set to themselves only. We also need in this function to add these public forums to the // public recipient list based on if they are tagged or not and have tag permissions. This is complicated // by the fact that this activity doesn't have the public forum tag. It's the parent activity that // contains the tag. we'll solve that further below. if($msg['notify']['sender']['guid_sig'] != $msg['message']['owner']['guid_sig']) { $perm = 'post_comments'; } } } elseif($msg['message']['type'] === 'mail') $perm = 'post_mail'; $r = array(); $c = q("select channel_id, channel_hash from channel where channel_removed = 0"); if($c) { foreach($c as $cc) { if(perm_is_allowed($cc['channel_id'],$msg['notify']['sender']['hash'],$perm)) { $r[] = [ 'hash' => $cc['channel_hash'] ]; } } } // logger('message: ' . print_r($msg['message'],true)); if($include_sys && array_key_exists('public_scope',$msg['message']) && $msg['message']['public_scope'] === 'public') { $sys = get_sys_channel(); if($sys) $r[] = [ 'hash' => $sys['channel_hash'] ]; } // look for any public mentions on this site // They will get filtered by tgroup_check() so we don't need to check permissions now if($check_mentions) { // It's a top level post. Look at the tags. See if any of them are mentions and are on this hub. if($msg['message']['tags']) { if(is_array($msg['message']['tags']) && $msg['message']['tags']) { foreach($msg['message']['tags'] as $tag) { if(($tag['type'] === 'mention') && (strpos($tag['url'],z_root()) !== false)) { $address = basename($tag['url']); if($address) { $z = q("select channel_hash as hash from channel where channel_address = '%s' and channel_removed = 0 limit 1", dbesc($address) ); if($z) $r = array_merge($r,$z); } } } } } } else { // This is a comment. We need to find any parent with ITEM_UPLINK set. But in fact, let's just return // everybody that stored a copy of the parent. This way we know we're covered. We'll check the // comment permissions when we deliver them. if($msg['message']['message_top']) { $z = q("select owner_xchan as hash from item where parent_mid = '%s' ", dbesc($msg['message']['message_top']) ); if($z) $r = array_merge($r,$z); } } // There are probably a lot of duplicates in $r at this point. We need to filter those out. // It's a bit of work since it's a multi-dimensional array if($r) { $uniq = array(); foreach($r as $rr) { if(! in_array($rr['hash'],$uniq)) $uniq[] = $rr['hash']; } $r = array(); foreach($uniq as $rr) { $r[] = array('hash' => $rr); } } logger('public_recips: ' . print_r($r,true), LOGGER_DATA, LOG_DEBUG); return $r; } /** * @brief * * This is the second part of public_recips(). * We'll find all the channels willing to accept public posts from us, then * match them against the sender privacy scope and see who in that list that * the sender is allowing. * * @see public_recipes() * @param array $msg * @return array */ function allowed_public_recips($msg) { logger('allowed_public_recips: ' . print_r($msg,true),LOGGER_DATA, LOG_DEBUG); if(array_key_exists('public_scope',$msg['message'])) $scope = $msg['message']['public_scope']; // Mail won't have a public scope. // in fact, it's doubtful mail will ever get here since it almost universally // has a recipient, but in fact we don't require this, so it's technically // possible to send mail to anybody that's listening. $recips = public_recips($msg); if(! $recips) return $recips; if($msg['message']['type'] === 'mail') return $recips; if($scope === 'public' || $scope === 'network: red' || $scope === 'authenticated') return $recips; if(strpos($scope,'site:') === 0) { if(($scope === 'site: ' . App::get_hostname()) && ($msg['notify']['sender']['url'] === z_root())) return $recips; else return array(); } $hash = make_xchan_hash($msg['notify']['sender']['guid'],$msg['notify']['sender']['guid_sig']); if($scope === 'self') { foreach($recips as $r) if($r['hash'] === $hash) return array('hash' => $hash); } // note: we shouldn't ever see $scope === 'specific' in this function, but handle it anyway if($scope === 'contacts' || $scope === 'any connections' || $scope === 'specific') { $condensed_recips = array(); foreach($recips as $rr) $condensed_recips[] = $rr['hash']; $results = array(); $r = q("select channel_hash as hash from channel left join abook on abook_channel = channel_id where abook_xchan = '%s' and channel_removed = 0 ", dbesc($hash) ); if($r) { foreach($r as $rr) if(in_array($rr['hash'],$condensed_recips)) $results[] = array('hash' => $rr['hash']); } return $results; } return array(); } /** * @brief * * @param array $sender * @param array $arr * @param array $deliveries * @param boolean $relay * @param boolean $public (optional) default false * @param boolean $request (optional) default false * @return array */ function process_delivery($sender, $arr, $deliveries, $relay, $public = false, $request = false) { $result = array(); $result['site'] = z_root(); // We've validated the sender. Now make sure that the sender is the owner or author if(! $public) { if($sender['hash'] != $arr['owner_xchan'] && $sender['hash'] != $arr['author_xchan']) { logger("process_delivery: sender {$sender['hash']} is not owner {$arr['owner_xchan']} or author {$arr['author_xchan']} - mid {$arr['mid']}"); return; } } foreach($deliveries as $d) { $local_public = $public; $DR = new Zotlabs\Zot\DReport(z_root(),$sender['hash'],$d['hash'],$arr['mid']); $r = q("select * from channel where channel_hash = '%s' limit 1", dbesc($d['hash']) ); if(! $r) { $DR->update('recipient not found'); $result[] = $DR->get(); continue; } $channel = $r[0]; $DR->addto_recipient($channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . App::get_hostname() . '>'); /* blacklisted channels get a permission denied, no special message to tip them off */ if(! check_channelallowed($sender['hash'])) { $DR->update('permission denied'); $result[] = $DR->get(); continue; } /** * @FIXME: Somehow we need to block normal message delivery from our clones, as the delivered * message doesn't have ACL information in it as the cloned copy does. That copy * will normally arrive first via sync delivery, but this isn't guaranteed. * There's a chance the current delivery could take place before the cloned copy arrives * hence the item could have the wrong ACL and *could* be used in subsequent deliveries or * access checks. So far all attempts at identifying this situation precisely * have caused issues with delivery of relayed comments. */ // if(($d['hash'] === $sender['hash']) && ($sender['url'] !== z_root()) && (! $relay)) { // $DR->update('self delivery ignored'); // $result[] = $DR->get(); // continue; // } // allow public postings to the sys channel regardless of permissions, but not // for comments travelling upstream. Wait and catch them on the way down. // They may have been blocked by the owner. if(intval($channel['channel_system']) && (! $arr['item_private']) && (! $relay)) { $local_public = true; $r = q("select xchan_selfcensored from xchan where xchan_hash = '%s' limit 1", dbesc($sender['hash']) ); // don't import sys channel posts from selfcensored authors if($r && (intval($r[0]['xchan_selfcensored']))) { $local_public = false; continue; } } $tag_delivery = tgroup_check($channel['channel_id'],$arr); $perm = 'send_stream'; if(($arr['mid'] !== $arr['parent_mid']) && ($relay)) $perm = 'post_comments'; // This is our own post, possibly coming from a channel clone if($arr['owner_xchan'] == $d['hash']) { $arr['item_wall'] = 1; } else { $arr['item_wall'] = 0; } if((! perm_is_allowed($channel['channel_id'],$sender['hash'],$perm)) && (! $tag_delivery) && (! $local_public)) { logger("permission denied for delivery to channel {$channel['channel_id']} {$channel['channel_address']}"); $DR->update('permission denied'); $result[] = $DR->get(); continue; } if($arr['mid'] != $arr['parent_mid']) { // check source route. // We are only going to accept comments from this sender if the comment has the same route as the top-level-post, // this is so that permissions mismatches between senders apply to the entire conversation // As a side effect we will also do a preliminary check that we have the top-level-post, otherwise // processing it is pointless. $r = q("select route, id from item where mid = '%s' and uid = %d limit 1", dbesc($arr['parent_mid']), intval($channel['channel_id']) ); if(! $r) { $DR->update('comment parent not found'); $result[] = $DR->get(); // We don't seem to have a copy of this conversation or at least the parent // - so request a copy of the entire conversation to date. // Don't do this if it's a relay post as we're the ones who are supposed to // have the copy and we don't want the request to loop. // Also don't do this if this comment came from a conversation request packet. // It's possible that comments are allowed but posting isn't and that could // cause a conversation fetch loop. We can detect these packets since they are // delivered via a 'notify' packet type that has a message_id element in the // initial zot packet (just like the corresponding 'request' packet type which // makes the request). // We'll also check the send_stream permission - because if it isn't allowed, // the top level post is unlikely to be imported and // this is just an exercise in futility. if((! $relay) && (! $request) && (! $local_public) && perm_is_allowed($channel['channel_id'],$sender['hash'],'send_stream')) { Zotlabs\Daemon\Master::Summon(array('Notifier', 'request', $channel['channel_id'], $sender['hash'], $arr['parent_mid'])); } continue; } if($relay) { // reset the route in case it travelled a great distance upstream // use our parent's route so when we go back downstream we'll match // with whatever route our parent has. $arr['route'] = $r[0]['route']; } else { // going downstream check that we have the same upstream provider that // sent it to us originally. Ignore it if it came from another source // (with potentially different permissions). // only compare the last hop since it could have arrived at the last location any number of ways. // Always accept empty routes and firehose items (route contains 'undefined') . $existing_route = explode(',', $r[0]['route']); $routes = count($existing_route); if($routes) { $last_hop = array_pop($existing_route); $last_prior_route = implode(',',$existing_route); } else { $last_hop = ''; $last_prior_route = ''; } if(in_array('undefined',$existing_route) || $last_hop == 'undefined' || $sender['hash'] == 'undefined') $last_hop = ''; $current_route = (($arr['route']) ? $arr['route'] . ',' : '') . $sender['hash']; if($last_hop && $last_hop != $sender['hash']) { logger('comment route mismatch: parent route = ' . $r[0]['route'] . ' expected = ' . $current_route, LOGGER_DEBUG); logger('comment route mismatch: parent msg = ' . $r[0]['id'],LOGGER_DEBUG); $DR->update('comment route mismatch'); $result[] = $DR->get(); continue; } // we'll add sender['hash'] onto this when we deliver it. $last_prior_route now has the previously stored route // *except* for the sender['hash'] which would've been the last hop before it got to us. $arr['route'] = $last_prior_route; } } $ab = q("select * from abook where abook_channel = %d and abook_xchan = '%s'", intval($channel['channel_id']), dbesc($arr['owner_xchan']) ); $abook = (($ab) ? $ab[0] : null); if(intval($arr['item_deleted'])) { // remove_community_tag is a no-op if this isn't a community tag activity remove_community_tag($sender,$arr,$channel['channel_id']); // set these just in case we need to store a fresh copy of the deleted post. // This could happen if the delete got here before the original post did. $arr['aid'] = $channel['channel_account_id']; $arr['uid'] = $channel['channel_id']; $item_id = delete_imported_item($sender,$arr,$channel['channel_id'],$relay); $DR->update(($item_id) ? 'deleted' : 'delete_failed'); $result[] = $DR->get(); if($relay && $item_id) { logger('process_delivery: invoking relay'); Zotlabs\Daemon\Master::Summon(array('Notifier','relay',intval($item_id))); $DR->update('relayed'); $result[] = $DR->get(); } continue; } $r = q("select * from item where mid = '%s' and uid = %d limit 1", dbesc($arr['mid']), intval($channel['channel_id']) ); if($r) { // We already have this post. $item_id = $r[0]['id']; if(intval($r[0]['item_deleted'])) { // It was deleted locally. $DR->update('update ignored'); $result[] = $DR->get(); continue; } // Maybe it has been edited? elseif($arr['edited'] > $r[0]['edited']) { $arr['id'] = $r[0]['id']; $arr['uid'] = $channel['channel_id']; if(($arr['mid'] == $arr['parent_mid']) && (! post_is_importable($arr,$abook))) { $DR->update('update ignored'); $result[] = $DR->get(); } else { update_imported_item($sender,$arr,$r[0],$channel['channel_id']); $DR->update('updated'); $result[] = $DR->get(); if(! $relay) add_source_route($item_id,$sender['hash']); } } else { $DR->update('update ignored'); $result[] = $DR->get(); // We need this line to ensure wall-to-wall comments are relayed (by falling through to the relay bit), // and at the same time not relay any other relayable posts more than once, because to do so is very wasteful. if(! intval($r[0]['item_origin'])) continue; } } else { $arr['aid'] = $channel['channel_account_id']; $arr['uid'] = $channel['channel_id']; // if it's a sourced post, call the post_local hooks as if it were // posted locally so that crosspost connectors will be triggered. if(check_item_source($arr['uid'], $arr)) call_hooks('post_local', $arr); $item_id = 0; if(($arr['mid'] == $arr['parent_mid']) && (! post_is_importable($arr,$abook))) { $DR->update('post ignored'); $result[] = $DR->get(); } else { $item_result = item_store($arr); if($item_result['success']) { $item_id = $item_result['item_id']; $parr = array('item_id' => $item_id,'item' => $arr,'sender' => $sender,'channel' => $channel); call_hooks('activity_received',$parr); // don't add a source route if it's a relay or later recipients will get a route mismatch if(! $relay) add_source_route($item_id,$sender['hash']); } $DR->update(($item_id) ? 'posted' : 'storage failed: ' . $item_result['message']); $result[] = $DR->get(); } } if($relay && $item_id) { logger('process_delivery: invoking relay'); Zotlabs\Daemon\Master::Summon(array('Notifier','relay',intval($item_id))); $DR->addto_update('relayed'); $result[] = $DR->get(); } } if(! $deliveries) $result[] = array('', 'no recipients', '', $arr['mid']); logger('process_delivery: local results: ' . print_r($result, true), LOGGER_DEBUG); return $result; } /** * @brief * * @param array $sender an associative array with * * \e string \b hash a xchan_hash * @param array $arr an associative array * * \e int \b verb * * \e int \b obj_type * * \e int \b mid * @param int $uid */ function remove_community_tag($sender, $arr, $uid) { if(! (activity_match($arr['verb'], ACTIVITY_TAG) && ($arr['obj_type'] == ACTIVITY_OBJ_TAGTERM))) return; logger('remove_community_tag: invoked'); if(! get_pconfig($uid,'system','blocktags')) { logger('remove_community tag: permission denied.'); return; } $r = q("select * from item where mid = '%s' and uid = %d limit 1", dbesc($arr['mid']), intval($uid) ); if(! $r) { logger('remove_community_tag: no item'); return; } if(($sender['hash'] != $r[0]['owner_xchan']) && ($sender['hash'] != $r[0]['author_xchan'])) { logger('remove_community_tag: sender not authorised.'); return; } $i = $r[0]; if($i['target']) $i['target'] = json_decode($i['target'],true); if($i['object']) $i['object'] = json_decode($i['object'],true); if(! ($i['target'] && $i['object'])) { logger('remove_community_tag: no target/object'); return; } $message_id = $i['target']['id']; $r = q("select id from item where mid = '%s' and uid = %d limit 1", dbesc($message_id), intval($uid) ); if(! $r) { logger('remove_community_tag: no parent message'); return; } q("delete from term where uid = %d and oid = %d and otype = %d and ttype in ( %d, %d ) and term = '%s' and url = '%s'", intval($uid), intval($r[0]['id']), intval(TERM_OBJ_POST), intval(TERM_HASHTAG), intval(TERM_COMMUNITYTAG), dbesc($i['object']['title']), dbesc(get_rel_link($i['object']['link'],'alternate')) ); } /** * @brief Just calls item_store_update() and logs result. * * @see item_store_update() * @param array $sender (unused) * @param array $item * @param int $uid (unused) */ function update_imported_item($sender, $item, $orig, $uid) { // If this is a comment being updated, remove any privacy information // so that item_store_update will set it from the original. if($item['mid'] !== $item['parent_mid']) { unset($item['allow_cid']); unset($item['allow_gid']); unset($item['deny_cid']); unset($item['deny_gid']); unset($item['item_private']); } $x = item_store_update($item); // If we're updating an event that we've saved locally, we store the item info first // because event_addtocal will parse the body to get the 'new' event details if($orig['resource_type'] === 'event') { $res = event_addtocal($orig['id'],$uid); if(! $res) logger('update event: failed'); } if(! $x['item_id']) logger('update_imported_item: failed: ' . $x['message']); else logger('update_imported_item'); } /** * @brief Deletes an imported item. * * @param array $sender * * \e string \b hash a xchan_hash * @param array $item * @param int $uid * @param boolean $relay * @return boolean|int post_id */ function delete_imported_item($sender, $item, $uid, $relay) { logger('delete_imported_item invoked', LOGGER_DEBUG); $ownership_valid = false; $item_found = false; $post_id = 0; $r = q("select id, author_xchan, owner_xchan, source_xchan, item_deleted from item where ( author_xchan = '%s' or owner_xchan = '%s' or source_xchan = '%s' ) and mid = '%s' and uid = %d limit 1", dbesc($sender['hash']), dbesc($sender['hash']), dbesc($sender['hash']), dbesc($item['mid']), intval($uid) ); if ($r) { if ($r[0]['author_xchan'] === $sender['hash'] || $r[0]['owner_xchan'] === $sender['hash'] || $r[0]['source_xchan'] === $sender['hash']) $ownership_valid = true; $post_id = $r[0]['id']; $item_found = true; } else { // perhaps the item is still in transit and the delete notification got here before the actual item did. Store it with the deleted flag set. // item_store() won't try to deliver any notifications or start delivery chains if this flag is set. // This means we won't end up with potentially even more delivery threads trying to push this delete notification. // But this will ensure that if the (undeleted) original post comes in at a later date, we'll reject it because it will have an older timestamp. logger('delete received for non-existent item - storing item data.'); /** @BUG $arr is undefined here, so this is dead code */ if ($arr['author_xchan'] === $sender['hash'] || $arr['owner_xchan'] === $sender['hash'] || $arr['source_xchan'] === $sender['hash']) { $ownership_valid = true; $item_result = item_store($arr); $post_id = $item_result['item_id']; } } if ($ownership_valid === false) { logger('delete_imported_item: failed: ownership issue'); return false; } require_once('include/items.php'); if ($item_found) { if (intval($r[0]['item_deleted'])) { logger('delete_imported_item: item was already deleted'); if (! $relay) return false; // This is a bit hackish, but may have to suffice until the notification/delivery loop is optimised // a bit further. We're going to strip the ITEM_ORIGIN on this item if it's a comment, because // it was already deleted, and we're already relaying, and this ensures that no other process or // code path downstream can relay it again (causing a loop). Since it's already gone it's not coming // back, and we aren't going to (or shouldn't at any rate) delete it again in the future - so losing // this information from the metadata should have no other discernible impact. if (($r[0]['id'] != $r[0]['parent']) && intval($r[0]['item_origin'])) { q("update item set item_origin = 0 where id = %d and uid = %d", intval($r[0]['id']), intval($r[0]['uid']) ); } } require_once('include/items.php'); // Use phased deletion to set the deleted flag, call both tag_deliver and the notifier to notify downstream channels // and then clean up after ourselves with a cron job after several days to do the delete_item_lowlevel() (DROPITEM_PHASE2). drop_item($post_id, false, DROPITEM_PHASE1); tag_deliver($uid, $post_id); } return $post_id; } function process_mail_delivery($sender, $arr, $deliveries) { $result = array(); if($sender['hash'] != $arr['from_xchan']) { logger('process_mail_delivery: sender is not mail author'); return; } foreach($deliveries as $d) { $DR = new Zotlabs\Zot\DReport(z_root(),$sender['hash'],$d['hash'],$arr['mid']); $r = q("select * from channel where channel_hash = '%s' limit 1", dbesc($d['hash']) ); if(! $r) { $DR->update('recipient not found'); $result[] = $DR->get(); continue; } $channel = $r[0]; $DR->addto_recipient($channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . App::get_hostname() . '>'); /* blacklisted channels get a permission denied, no special message to tip them off */ if(! check_channelallowed($sender['hash'])) { $DR->update('permission denied'); $result[] = $DR->get(); continue; } if(! perm_is_allowed($channel['channel_id'],$sender['hash'],'post_mail')) { logger("permission denied for mail delivery {$channel['channel_id']}"); $DR->update('permission denied'); $result[] = $DR->get(); continue; } $r = q("select id from mail where mid = '%s' and channel_id = %d limit 1", dbesc($arr['mid']), intval($channel['channel_id']) ); if($r) { if(intval($arr['mail_recalled'])) { $x = q("delete from mail where id = %d and channel_id = %d", intval($r[0]['id']), intval($channel['channel_id']) ); $DR->update('mail recalled'); $result[] = $DR->get(); logger('mail_recalled'); } else { $DR->update('duplicate mail received'); $result[] = $DR->get(); logger('duplicate mail received'); } continue; } else { $arr['account_id'] = $channel['channel_account_id']; $arr['channel_id'] = $channel['channel_id']; $item_id = mail_store($arr); $DR->update('mail delivered'); $result[] = $DR->get(); } } return $result; } /** * @brief Processes delivery of rating. * * @param array $sender * * \e string \b hash a xchan_hash * @param array $arr */ function process_rating_delivery($sender, $arr) { logger('process_rating_delivery: ' . print_r($arr,true)); if(! $arr['target']) return; $z = q("select xchan_pubkey from xchan where xchan_hash = '%s' limit 1", dbesc($sender['hash']) ); if((! $z) || (! rsa_verify($arr['target'] . '.' . $arr['rating'] . '.' . $arr['rating_text'], base64url_decode($arr['signature']),$z[0]['xchan_pubkey']))) { logger('failed to verify rating'); return; } $r = q("select * from xlink where xlink_xchan = '%s' and xlink_link = '%s' and xlink_static = 1 limit 1", dbesc($sender['hash']), dbesc($arr['target']) ); if($r) { if($r[0]['xlink_updated'] >= $arr['edited']) { logger('rating message duplicate'); return; } $x = q("update xlink set xlink_rating = %d, xlink_rating_text = '%s', xlink_sig = '%s', xlink_updated = '%s' where xlink_id = %d", intval($arr['rating']), dbesc($arr['rating_text']), dbesc($arr['signature']), dbesc(datetime_convert()), intval($r[0]['xlink_id']) ); logger('rating updated'); } else { $x = q("insert into xlink ( xlink_xchan, xlink_link, xlink_rating, xlink_rating_text, xlink_sig, xlink_updated, xlink_static ) values( '%s', '%s', %d, '%s', '%s', '%s', 1 ) ", dbesc($sender['hash']), dbesc($arr['target']), intval($arr['rating']), dbesc($arr['rating_text']), dbesc($arr['signature']), dbesc(datetime_convert()) ); logger('rating created'); } } /** * @brief Processes delivery of profile. * * @see import_directory_profile() * @param array $sender an associative array * * \e string \b hash a xchan_hash * @param array $arr * @param array $deliveries (unused) */ function process_profile_delivery($sender, $arr, $deliveries) { logger('process_profile_delivery', LOGGER_DEBUG); $r = q("select xchan_addr from xchan where xchan_hash = '%s' limit 1", dbesc($sender['hash']) ); if($r) import_directory_profile($sender['hash'], $arr, $r[0]['xchan_addr'], UPDATE_FLAGS_UPDATED, 0); } function process_location_delivery($sender,$arr,$deliveries) { // deliveries is irrelevant logger('process_location_delivery', LOGGER_DEBUG); $r = q("select xchan_pubkey from xchan where xchan_hash = '%s' limit 1", dbesc($sender['hash']) ); if($r) $sender['key'] = $r[0]['xchan_pubkey']; if(array_key_exists('locations',$arr) && $arr['locations']) { $x = sync_locations($sender,$arr,true); logger('process_location_delivery: results: ' . print_r($x,true), LOGGER_DEBUG); if($x['changed']) { $guid = random_string() . '@' . App::get_hostname(); update_modtime($sender['hash'],$sender['guid'],$arr['locations'][0]['address'],UPDATE_FLAGS_UPDATED); } } } /** * @brief checks for a moved UNO channel and sets the channel_moved flag * * Currently the effect of this flag is to turn the channel into 'read-only' mode. * New content will not be processed (there was still an issue with blocking the * ability to post comments as of 10-Mar-2016). * We do not physically remove the channel at this time. The hub admin may choose * to do so, but is encouraged to allow a grace period of several days in case there * are any issues migrating content. This packet will generally be received by the * original site when the basic channel import has been processed. * * This will only be executed on the UNO system which is the old location * if a new location is reported and there is only one location record. * The rest of the hubloc syncronisation will be handled within * sync_locations */ function check_location_move($sender_hash,$locations) { if(! $locations) return; if(get_config('system','server_role') !== 'basic') return; if(count($locations) != 1) return; $loc = $locations[0]; $r = q("select * from channel where channel_hash = '%s' limit 1", dbesc($sender_hash) ); if(! $r) return; if($loc['url'] !== z_root()) { $x = q("update channel set channel_moved = '%s' where channel_hash = '%s' limit 1", dbesc($loc['url']), dbesc($sender_hash) ); // federation plugins may wish to notify connections // of the move on singleton networks $arr = array('channel' => $r[0],'locations' => $locations); call_hooks('location_move',$arr); } } /** * @brief Synchronises locations. * * @param array $sender * @param array $arr * @param boolean $absolute (optional) default false * @return array */ function sync_locations($sender, $arr, $absolute = false) { $ret = array(); if($arr['locations']) { if($absolute) check_location_move($sender['hash'],$arr['locations']); $xisting = q("select hubloc_id, hubloc_url, hubloc_sitekey from hubloc where hubloc_hash = '%s'", dbesc($sender['hash']) ); // See if a primary is specified $has_primary = false; foreach($arr['locations'] as $location) { if($location['primary']) { $has_primary = true; break; } } // Ensure that they have one primary hub if(! $has_primary) $arr['locations'][0]['primary'] = true; foreach($arr['locations'] as $location) { if(! rsa_verify($location['url'],base64url_decode($location['url_sig']),$sender['key'])) { logger('sync_locations: Unable to verify site signature for ' . $location['url']); $ret['message'] .= sprintf( t('Unable to verify site signature for %s'), $location['url']) . EOL; continue; } for($x = 0; $x < count($xisting); $x ++) { if(($xisting[$x]['hubloc_url'] === $location['url']) && ($xisting[$x]['hubloc_sitekey'] === $location['sitekey'])) { $xisting[$x]['updated'] = true; } } if(! $location['sitekey']) { logger('sync_locations: empty hubloc sitekey. ' . print_r($location,true)); continue; } // Catch some malformed entries from the past which still exist if(strpos($location['address'],'/') !== false) $location['address'] = substr($location['address'],0,strpos($location['address'],'/')); // match as many fields as possible in case anything at all changed. $r = q("select * from hubloc where hubloc_hash = '%s' and hubloc_guid = '%s' and hubloc_guid_sig = '%s' and hubloc_url = '%s' and hubloc_url_sig = '%s' and hubloc_host = '%s' and hubloc_addr = '%s' and hubloc_callback = '%s' and hubloc_sitekey = '%s' ", dbesc($sender['hash']), dbesc($sender['guid']), dbesc($sender['guid_sig']), dbesc($location['url']), dbesc($location['url_sig']), dbesc($location['host']), dbesc($location['address']), dbesc($location['callback']), dbesc($location['sitekey']) ); if($r) { logger('sync_locations: hub exists: ' . $location['url'], LOGGER_DEBUG); // update connection timestamp if this is the site we're talking to // This only happens when called from import_xchan $current_site = false; $t = datetime_convert('UTC','UTC','now - 15 minutes'); if(array_key_exists('site',$arr) && $location['url'] == $arr['site']['url']) { q("update hubloc set hubloc_connected = '%s', hubloc_updated = '%s' where hubloc_id = %d and hubloc_connected < '%s'", dbesc(datetime_convert()), dbesc(datetime_convert()), intval($r[0]['hubloc_id']), dbesc($t) ); $current_site = true; } if($current_site && intval($r[0]['hubloc_error'])) { q("update hubloc set hubloc_error = 0 where hubloc_id = %d", intval($r[0]['hubloc_id']) ); if(intval($r[0]['hubloc_orphancheck'])) { q("update hubloc set hubloc_orphancheck = 0 where hubloc_id = %d", intval($r[0]['hubloc_id']) ); } q("update xchan set xchan_orphan = 0 where xchan_orphan = 1 and xchan_hash = '%s'", dbesc($sender['hash']) ); } // Remove pure duplicates if(count($r) > 1) { for($h = 1; $h < count($r); $h ++) { q("delete from hubloc where hubloc_id = %d", intval($r[$h]['hubloc_id']) ); $what .= 'duplicate_hubloc_removed '; $changed = true; } } if(intval($r[0]['hubloc_primary']) && (! $location['primary'])) { $m = q("update hubloc set hubloc_primary = 0, hubloc_updated = '%s' where hubloc_id = %d", dbesc(datetime_convert()), intval($r[0]['hubloc_id']) ); $r[0]['hubloc_primary'] = intval($location['primary']); hubloc_change_primary($r[0]); $what .= 'primary_hub '; $changed = true; } elseif((! intval($r[0]['hubloc_primary'])) && ($location['primary'])) { $m = q("update hubloc set hubloc_primary = 1, hubloc_updated = '%s' where hubloc_id = %d", dbesc(datetime_convert()), intval($r[0]['hubloc_id']) ); // make sure hubloc_change_primary() has current data $r[0]['hubloc_primary'] = intval($location['primary']); hubloc_change_primary($r[0]); $what .= 'primary_hub '; $changed = true; } elseif($absolute) { // Absolute sync - make sure the current primary is correctly reflected in the xchan $pr = hubloc_change_primary($r[0]); if($pr) { $what .= 'xchan_primary '; $changed = true; } } if(intval($r[0]['hubloc_deleted']) && (! intval($location['deleted']))) { $n = q("update hubloc set hubloc_deleted = 0, hubloc_updated = '%s' where hubloc_id = %d", dbesc(datetime_convert()), intval($r[0]['hubloc_id']) ); $what .= 'undelete_hub '; $changed = true; } elseif((! intval($r[0]['hubloc_deleted'])) && (intval($location['deleted']))) { logger('deleting hubloc: ' . $r[0]['hubloc_addr']); $n = q("update hubloc set hubloc_deleted = 1, hubloc_updated = '%s' where hubloc_id = %d", dbesc(datetime_convert()), intval($r[0]['hubloc_id']) ); $what .= 'delete_hub '; $changed = true; } continue; } // Existing hubs are dealt with. Now let's process any new ones. // New hub claiming to be primary. Make it so by removing any existing primaries. if(intval($location['primary'])) { $r = q("update hubloc set hubloc_primary = 0, hubloc_updated = '%s' where hubloc_hash = '%s' and hubloc_primary = 1", dbesc(datetime_convert()), dbesc($sender['hash']) ); } logger('sync_locations: new hub: ' . $location['url']); $r = q("insert into hubloc ( hubloc_guid, hubloc_guid_sig, hubloc_hash, hubloc_addr, hubloc_network, hubloc_primary, hubloc_url, hubloc_url_sig, hubloc_host, hubloc_callback, hubloc_sitekey, hubloc_updated, hubloc_connected) values ( '%s','%s','%s','%s', '%s', %d ,'%s','%s','%s','%s','%s','%s','%s')", dbesc($sender['guid']), dbesc($sender['guid_sig']), dbesc($sender['hash']), dbesc($location['address']), dbesc('zot'), intval($location['primary']), dbesc($location['url']), dbesc($location['url_sig']), dbesc($location['host']), dbesc($location['callback']), dbesc($location['sitekey']), dbesc(datetime_convert()), dbesc(datetime_convert()) ); $what .= 'newhub '; $changed = true; if($location['primary']) { $r = q("select * from hubloc where hubloc_addr = '%s' and hubloc_sitekey = '%s' limit 1", dbesc($location['address']), dbesc($location['sitekey']) ); if($r) hubloc_change_primary($r[0]); } } // get rid of any hubs we have for this channel which weren't reported. if($absolute && $xisting) { foreach($xisting as $x) { if(! array_key_exists('updated',$x)) { logger('sync_locations: deleting unreferenced hub location ' . $x['hubloc_addr']); $r = q("update hubloc set hubloc_deleted = 1, hubloc_updated = '%s' where hubloc_id = %d", dbesc(datetime_convert()), intval($x['hubloc_id']) ); $what .= 'removed_hub '; $changed = true; } } } } else { logger('No locations to sync!'); } $ret['change_message'] = $what; $ret['changed'] = $changed; return $ret; } /** * @brief Returns an array with all known distinct hubs for this channel. * * @see zot_get_hublocs() * @param array $channel an associative array which must contain * * \e string \b channel_hash the hash of the channel * @return array an array with associative arrays */ function zot_encode_locations($channel) { $ret = array(); $x = zot_get_hublocs($channel['channel_hash']); if($x && count($x)) { foreach($x as $hub) { // if this is a local channel that has been deleted, the hubloc is no good - make sure it is marked deleted // so that nobody tries to use it. if(intval($channel['channel_removed']) && $hub['hubloc_url'] === z_root()) $hub['hubloc_deleted'] = 1; $ret[] = array( 'host' => $hub['hubloc_host'], 'address' => $hub['hubloc_addr'], 'primary' => (intval($hub['hubloc_primary']) ? true : false), 'url' => $hub['hubloc_url'], 'url_sig' => $hub['hubloc_url_sig'], 'callback' => $hub['hubloc_callback'], 'sitekey' => $hub['hubloc_sitekey'], 'deleted' => (intval($hub['hubloc_deleted']) ? true : false) ); } } return $ret; } /** * @brief Imports a directory profile. * * @param string $hash * @param array $profile * @param string $addr * @param number $ud_flags * @param number $suppress_update default 0 * @return boolean $updated if something changed */ function import_directory_profile($hash, $profile, $addr, $ud_flags = UPDATE_FLAGS_UPDATED, $suppress_update = 0) { logger('import_directory_profile', LOGGER_DEBUG); if (! $hash) return false; $arr = array(); $arr['xprof_hash'] = $hash; $arr['xprof_dob'] = datetime_convert('','',$profile['birthday'],'Y-m-d'); // !!!! check this for 0000 year $arr['xprof_age'] = (($profile['age']) ? intval($profile['age']) : 0); $arr['xprof_desc'] = (($profile['description']) ? htmlspecialchars($profile['description'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_gender'] = (($profile['gender']) ? htmlspecialchars($profile['gender'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_marital'] = (($profile['marital']) ? htmlspecialchars($profile['marital'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_sexual'] = (($profile['sexual']) ? htmlspecialchars($profile['sexual'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_locale'] = (($profile['locale']) ? htmlspecialchars($profile['locale'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_region'] = (($profile['region']) ? htmlspecialchars($profile['region'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_postcode'] = (($profile['postcode']) ? htmlspecialchars($profile['postcode'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_country'] = (($profile['country']) ? htmlspecialchars($profile['country'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_about'] = (($profile['about']) ? htmlspecialchars($profile['about'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_homepage'] = (($profile['homepage']) ? htmlspecialchars($profile['homepage'], ENT_COMPAT,'UTF-8',false) : ''); $arr['xprof_hometown'] = (($profile['hometown']) ? htmlspecialchars($profile['hometown'], ENT_COMPAT,'UTF-8',false) : ''); $clean = array(); if (array_key_exists('keywords', $profile) and is_array($profile['keywords'])) { import_directory_keywords($hash,$profile['keywords']); foreach ($profile['keywords'] as $kw) { $kw = trim(htmlspecialchars($kw,ENT_COMPAT, 'UTF-8', false)); $kw = trim($kw, ','); $clean[] = $kw; } } $arr['xprof_keywords'] = implode(' ',$clean); // Self censored, make it so // These are not translated, so the German "erwachsenen" keyword will not censor the directory profile. Only the English form - "adult". if(in_arrayi('nsfw',$clean) || in_arrayi('adult',$clean)) { q("update xchan set xchan_selfcensored = 1 where xchan_hash = '%s'", dbesc($hash) ); } $r = q("select * from xprof where xprof_hash = '%s' limit 1", dbesc($hash) ); if ($arr['xprof_age'] > 150) $arr['xprof_age'] = 150; if ($arr['xprof_age'] < 0) $arr['xprof_age'] = 0; if ($r) { $update = false; foreach ($r[0] as $k => $v) { if ((array_key_exists($k,$arr)) && ($arr[$k] != $v)) { logger('import_directory_profile: update ' . $k . ' => ' . $arr[$k]); $update = true; break; } } if ($update) { q("update xprof set xprof_desc = '%s', xprof_dob = '%s', xprof_age = %d, xprof_gender = '%s', xprof_marital = '%s', xprof_sexual = '%s', xprof_locale = '%s', xprof_region = '%s', xprof_postcode = '%s', xprof_country = '%s', xprof_about = '%s', xprof_homepage = '%s', xprof_hometown = '%s', xprof_keywords = '%s' where xprof_hash = '%s'", dbesc($arr['xprof_desc']), dbesc($arr['xprof_dob']), intval($arr['xprof_age']), dbesc($arr['xprof_gender']), dbesc($arr['xprof_marital']), dbesc($arr['xprof_sexual']), dbesc($arr['xprof_locale']), dbesc($arr['xprof_region']), dbesc($arr['xprof_postcode']), dbesc($arr['xprof_country']), dbesc($arr['xprof_about']), dbesc($arr['xprof_homepage']), dbesc($arr['xprof_hometown']), dbesc($arr['xprof_keywords']), dbesc($arr['xprof_hash']) ); } } else { $update = true; logger('import_directory_profile: new profile '); q("insert into xprof (xprof_hash, xprof_desc, xprof_dob, xprof_age, xprof_gender, xprof_marital, xprof_sexual, xprof_locale, xprof_region, xprof_postcode, xprof_country, xprof_about, xprof_homepage, xprof_hometown, xprof_keywords) values ('%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s') ", dbesc($arr['xprof_hash']), dbesc($arr['xprof_desc']), dbesc($arr['xprof_dob']), intval($arr['xprof_age']), dbesc($arr['xprof_gender']), dbesc($arr['xprof_marital']), dbesc($arr['xprof_sexual']), dbesc($arr['xprof_locale']), dbesc($arr['xprof_region']), dbesc($arr['xprof_postcode']), dbesc($arr['xprof_country']), dbesc($arr['xprof_about']), dbesc($arr['xprof_homepage']), dbesc($arr['xprof_hometown']), dbesc($arr['xprof_keywords']) ); } $d = array('xprof' => $arr, 'profile' => $profile, 'update' => $update); call_hooks('import_directory_profile', $d); if (($d['update']) && (! $suppress_update)) update_modtime($arr['xprof_hash'],random_string() . '@' . App::get_hostname(), $addr, $ud_flags); return $d['update']; } /** * @brief * * @param string $hash * @param array $keywords */ function import_directory_keywords($hash, $keywords) { $existing = array(); $r = q("select * from xtag where xtag_hash = '%s' and xtag_flags = 0", dbesc($hash) ); if($r) { foreach($r as $rr) $existing[] = $rr['xtag_term']; } $clean = array(); foreach($keywords as $kw) { $kw = trim(htmlspecialchars($kw,ENT_COMPAT, 'UTF-8', false)); $kw = trim($kw, ','); $clean[] = $kw; } foreach($existing as $x) { if(! in_array($x, $clean)) $r = q("delete from xtag where xtag_hash = '%s' and xtag_term = '%s' and xtag_flags = 0", dbesc($hash), dbesc($x) ); } foreach($clean as $x) { if(! in_array($x, $existing)) { $r = q("insert into xtag ( xtag_hash, xtag_term, xtag_flags) values ( '%s' ,'%s', 0 )", dbesc($hash), dbesc($x) ); } } } /** * @brief * * @param string $hash * @param string $guid * @param string $addr * @param int $flags (optional) default 0 */ function update_modtime($hash, $guid, $addr, $flags = 0) { $dirmode = intval(get_config('system', 'directory_mode')); if($dirmode == DIRECTORY_MODE_NORMAL) return; if($flags) { q("insert into updates (ud_hash, ud_guid, ud_date, ud_flags, ud_addr ) values ( '%s', '%s', '%s', %d, '%s' )", dbesc($hash), dbesc($guid), dbesc(datetime_convert()), intval($flags), dbesc($addr) ); } else { q("update updates set ud_flags = ( ud_flags | %d ) where ud_addr = '%s' and not (ud_flags & %d)>0 ", intval(UPDATE_FLAGS_UPDATED), dbesc($addr), intval(UPDATE_FLAGS_UPDATED) ); } } /** * @brief * * @param array $arr * @param string $pubkey * @return boolean true if updated or inserted */ function import_site($arr, $pubkey) { if( (! is_array($arr)) || (! $arr['url']) || (! $arr['url_sig'])) return false; if(! rsa_verify($arr['url'], base64url_decode($arr['url_sig']), $pubkey)) { logger('import_site: bad url_sig'); return false; } $update = false; $exists = false; $r = q("select * from site where site_url = '%s' limit 1", dbesc($arr['url']) ); if($r) { $exists = true; $siterecord = $r[0]; } $site_directory = 0; if($arr['directory_mode'] == 'normal') $site_directory = DIRECTORY_MODE_NORMAL; if($arr['directory_mode'] == 'primary') $site_directory = DIRECTORY_MODE_PRIMARY; if($arr['directory_mode'] == 'secondary') $site_directory = DIRECTORY_MODE_SECONDARY; if($arr['directory_mode'] == 'standalone') $site_directory = DIRECTORY_MODE_STANDALONE; $register_policy = 0; if($arr['register_policy'] == 'closed') $register_policy = REGISTER_CLOSED; if($arr['register_policy'] == 'open') $register_policy = REGISTER_OPEN; if($arr['register_policy'] == 'approve') $register_policy = REGISTER_APPROVE; $access_policy = 0; if(array_key_exists('access_policy',$arr)) { if($arr['access_policy'] === 'private') $access_policy = ACCESS_PRIVATE; if($arr['access_policy'] === 'paid') $access_policy = ACCESS_PAID; if($arr['access_policy'] === 'free') $access_policy = ACCESS_FREE; if($arr['access_policy'] === 'tiered') $access_policy = ACCESS_TIERED; } // don't let insecure sites register as public hubs if(strpos($arr['url'],'https://') === false) $access_policy = ACCESS_PRIVATE; if($access_policy != ACCESS_PRIVATE) { $x = z_fetch_url($arr['url'] . '/siteinfo/json'); if(! $x['success']) $access_policy = ACCESS_PRIVATE; } $directory_url = htmlspecialchars($arr['directory_url'],ENT_COMPAT,'UTF-8',false); $url = htmlspecialchars(strtolower($arr['url']),ENT_COMPAT,'UTF-8',false); $sellpage = htmlspecialchars($arr['sellpage'],ENT_COMPAT,'UTF-8',false); $site_location = htmlspecialchars($arr['location'],ENT_COMPAT,'UTF-8',false); $site_realm = htmlspecialchars($arr['realm'],ENT_COMPAT,'UTF-8',false); $site_project = htmlspecialchars($arr['project'],ENT_COMPAT,'UTF-8',false); // You can have one and only one primary directory per realm. // Downgrade any others claiming to be primary. As they have // flubbed up this badly already, don't let them be directory servers at all. if(($site_directory === DIRECTORY_MODE_PRIMARY) && ($site_realm === get_directory_realm()) && ($arr['url'] != get_directory_primary())) { $site_directory = DIRECTORY_MODE_NORMAL; } if($exists) { if(($siterecord['site_flags'] != $site_directory) || ($siterecord['site_access'] != $access_policy) || ($siterecord['site_directory'] != $directory_url) || ($siterecord['site_sellpage'] != $sellpage) || ($siterecord['site_location'] != $site_location) || ($siterecord['site_register'] != $register_policy) || ($siterecord['site_project'] != $site_project) || ($siterecord['site_realm'] != $site_realm)) { $update = true; // logger('import_site: input: ' . print_r($arr,true)); // logger('import_site: stored: ' . print_r($siterecord,true)); $r = q("update site set site_dead = 0, site_location = '%s', site_flags = %d, site_access = %d, site_directory = '%s', site_register = %d, site_update = '%s', site_sellpage = '%s', site_realm = '%s', site_type = %d, site_project = '%s' where site_url = '%s'", dbesc($site_location), intval($site_directory), intval($access_policy), dbesc($directory_url), intval($register_policy), dbesc(datetime_convert()), dbesc($sellpage), dbesc($site_realm), intval(SITE_TYPE_ZOT), dbesc($site_project), dbesc($url) ); if(! $r) { logger('import_site: update failed. ' . print_r($arr,true)); } } else { // update the timestamp to indicate we communicated with this site q("update site set site_dead = 0, site_update = '%s' where site_url = '%s'", dbesc(datetime_convert()), dbesc($url) ); } } else { $update = true; $r = q("insert into site ( site_location, site_url, site_access, site_flags, site_update, site_directory, site_register, site_sellpage, site_realm, site_type, site_project ) values ( '%s', '%s', %d, %d, '%s', '%s', %d, '%s', '%s', %d, '%s' )", dbesc($site_location), dbesc($url), intval($access_policy), intval($site_directory), dbesc(datetime_convert()), dbesc($directory_url), intval($register_policy), dbesc($sellpage), dbesc($site_realm), intval(SITE_TYPE_ZOT), dbesc($site_project) ); if(! $r) { logger('import_site: record create failed. ' . print_r($arr,true)); } } return $update; } /** * Send a zot packet to all hubs where this channel is duplicated, refreshing * such things as personal settings, channel permissions, address book updates, etc. * * @param int $uid * @param array $packet (optional) default null * @param boolean $groups_changed (optional) default false */ function build_sync_packet($uid = 0, $packet = null, $groups_changed = false) { if(get_config('system','server_role') === 'basic') return; logger('build_sync_packet'); if($packet) logger('packet: ' . print_r($packet, true),LOGGER_DATA, LOG_DEBUG); if(! $uid) $uid = local_channel(); if(! $uid) return; $r = q("select * from channel where channel_id = %d limit 1", intval($uid) ); if(! $r) return; $channel = $r[0]; translate_channel_perms_outbound($channel); if($packet && array_key_exists('abook',$packet) && $packet['abook']) { for($x = 0; $x < count($packet['abook']); $x ++) { translate_abook_perms_outbound($packet['abook'][$x]); } } if(intval($channel['channel_removed'])) return; $h = q("select * from hubloc where hubloc_hash = '%s' and hubloc_deleted = 0", dbesc($channel['channel_hash']) ); if(! $h) return; $synchubs = array(); foreach($h as $x) { if($x['hubloc_host'] == App::get_hostname()) continue; $y = q("select site_dead from site where site_url = '%s' limit 1", dbesc($x['hubloc_url']) ); if((! $y) || ($y[0]['site_dead'] == 0)) $synchubs[] = $x; } if(! $synchubs) return; $r = q("select xchan_guid, xchan_guid_sig from xchan where xchan_hash = '%s' limit 1", dbesc($channel['channel_hash']) ); if(! $r) return; $env_recips = array(); $env_recips[] = array('guid' => $r[0]['xchan_guid'],'guid_sig' => $r[0]['xchan_guid_sig']); $info = (($packet) ? $packet : array()); $info['type'] = 'channel_sync'; $info['encoding'] = 'red'; // note: not zot, this packet is very platform specific $info['relocate'] = ['channel_address' => $channel['channel_address'], 'url' => z_root() ]; if(array_key_exists($uid,App::$config) && array_key_exists('transient',App::$config[$uid])) { $settings = App::$config[$uid]['transient']; if($settings) { $info['config'] = $settings; } } if($channel) { $info['channel'] = array(); foreach($channel as $k => $v) { // filter out any joined tables like xchan if(strpos($k,'channel_') !== 0) continue; // don't pass these elements, they should not be synchronised $disallowed = array('channel_id','channel_account_id','channel_primary','channel_prvkey','channel_address','channel_deleted','channel_removed','channel_system'); if(in_array($k,$disallowed)) continue; $info['channel'][$k] = $v; } } if($groups_changed) { $r = q("select hash as collection, visible, deleted, gname as name from groups where uid = %d", intval($uid) ); if($r) $info['collections'] = $r; $r = q("select groups.hash as collection, group_member.xchan as member from groups left join group_member on groups.id = group_member.gid where group_member.uid = %d", intval($uid) ); if($r) $info['collection_members'] = $r; } $interval = ((get_config('system','delivery_interval') !== false) ? intval(get_config('system','delivery_interval')) : 2 ); logger('build_sync_packet: packet: ' . print_r($info,true), LOGGER_DATA, LOG_DEBUG); $total = count($synchubs); foreach($synchubs as $hub) { $hash = random_string(); $n = zot_build_packet($channel,'notify',$env_recips,$hub['hubloc_sitekey'],$hash); queue_insert(array( 'hash' => $hash, 'account_id' => $channel['channel_account_id'], 'channel_id' => $channel['channel_id'], 'posturl' => $hub['hubloc_callback'], 'notify' => $n, 'msg' => json_encode($info) )); Zotlabs\Daemon\Master::Summon(array('Deliver', $hash)); $total = $total - 1; if($interval && $total) @time_sleep_until(microtime(true) + (float) $interval); } } /** * @brief * * @param array $sender * @param array $arr * @param array $deliveries * @return array */ function process_channel_sync_delivery($sender, $arr, $deliveries) { if(get_config('system','server_role') === 'basic') return; require_once('include/import.php'); /** @FIXME this will sync red structures (channel, pconfig and abook). Eventually we need to make this application agnostic. */ $result = array(); foreach ($deliveries as $d) { $r = q("select * from channel where channel_hash = '%s' limit 1", dbesc($d['hash']) ); if (! $r) { $result[] = array($d['hash'],'not found'); continue; } $channel = $r[0]; $max_friends = service_class_fetch($channel['channel_id'],'total_channels'); $max_feeds = account_service_class_fetch($channel['channel_account_id'],'total_feeds'); if($channel['channel_hash'] != $sender['hash']) { logger('process_channel_sync_delivery: possible forgery. Sender ' . $sender['hash'] . ' is not ' . $channel['channel_hash']); $result[] = array($d['hash'],'channel mismatch',$channel['channel_name'],''); continue; } if(array_key_exists('config',$arr) && is_array($arr['config']) && count($arr['config'])) { foreach($arr['config'] as $cat => $k) { foreach($arr['config'][$cat] as $k => $v) set_pconfig($channel['channel_id'],$cat,$k,$v); } } if(array_key_exists('obj',$arr) && $arr['obj']) sync_objs($channel,$arr['obj']); if(array_key_exists('likes',$arr) && $arr['likes']) import_likes($channel,$arr['likes']); if(array_key_exists('app',$arr) && $arr['app']) sync_apps($channel,$arr['app']); if(array_key_exists('chatroom',$arr) && $arr['chatroom']) sync_chatrooms($channel,$arr['chatroom']); if(array_key_exists('conv',$arr) && $arr['conv']) import_conv($channel,$arr['conv']); if(array_key_exists('mail',$arr) && $arr['mail']) sync_mail($channel,$arr['mail']); if(array_key_exists('event',$arr) && $arr['event']) sync_events($channel,$arr['event']); if(array_key_exists('event_item',$arr) && $arr['event_item']) sync_items($channel,$arr['event_item'],((array_key_exists('relocate',$arr)) ? $arr['relocate'] : null)); if(array_key_exists('item',$arr) && $arr['item']) sync_items($channel,$arr['item'],((array_key_exists('relocate',$arr)) ? $arr['relocate'] : null)); // deprecated, maintaining for a few months for upward compatibility // this should sync webpages, but the logic is a bit subtle if(array_key_exists('item_id',$arr) && $arr['item_id']) sync_items($channel,$arr['item_id']); if(array_key_exists('menu',$arr) && $arr['menu']) sync_menus($channel,$arr['menu']); if(array_key_exists('file',$arr) && $arr['file']) sync_files($channel,$arr['file']); if(array_key_exists('channel',$arr) && is_array($arr['channel']) && count($arr['channel'])) { translate_channel_perms_inbound($arr['channel']); if(array_key_exists('channel_pageflags',$arr['channel']) && intval($arr['channel']['channel_pageflags'])) { // These flags cannot be sync'd. // remove the bits from the incoming flags. // These correspond to PAGE_REMOVED and PAGE_SYSTEM on redmatrix if($arr['channel']['channel_pageflags'] & 0x8000) $arr['channel']['channel_pageflags'] = $arr['channel']['channel_pageflags'] - 0x8000; if($arr['channel']['channel_pageflags'] & 0x1000) $arr['channel']['channel_pageflags'] = $arr['channel']['channel_pageflags'] - 0x1000; } $disallowed = [ 'channel_id', 'channel_account_id', 'channel_primary', 'channel_prvkey', 'channel_address', 'channel_notifyflags', 'channel_removed', 'channel_deleted', 'channel_system', 'channel_r_stream', 'channel_r_profile', 'channel_r_abook', 'channel_r_storage', 'channel_r_pages', 'channel_w_stream', 'channel_w_wall', 'channel_w_comment', 'channel_w_mail', 'channel_w_like', 'channel_w_tagwall', 'channel_w_chat', 'channel_w_storage', 'channel_w_pages', 'channel_a_republish', 'channel_a_delegate' ]; $clean = array(); foreach($arr['channel'] as $k => $v) { if(in_array($k,$disallowed)) continue; $clean[$k] = $v; } if(count($clean)) { foreach($clean as $k => $v) { $r = dbq("UPDATE channel set " . dbesc($k) . " = '" . dbesc($v) . "' where channel_id = " . intval($channel['channel_id']) ); } } } if(array_key_exists('abook',$arr) && is_array($arr['abook']) && count($arr['abook'])) { $total_friends = 0; $total_feeds = 0; $r = q("select abook_id, abook_feed from abook where abook_channel = %d", intval($channel['channel_id']) ); if($r) { // don't count yourself $total_friends = ((count($r) > 0) ? count($r) - 1 : 0); foreach($r as $rr) if(intval($rr['abook_feed'])) $total_feeds ++; } $disallowed = array('abook_id','abook_account','abook_channel','abook_rating','abook_rating_text'); foreach($arr['abook'] as $abook) { $abconfig = null; if(array_key_exists('abconfig',$abook) && is_array($abook['abconfig']) && count($abook['abconfig'])) $abconfig = $abook['abconfig']; if(! array_key_exists('abook_blocked',$abook)) { // convert from redmatrix $abook['abook_blocked'] = (($abook['abook_flags'] & 0x0001) ? 1 : 0); $abook['abook_ignored'] = (($abook['abook_flags'] & 0x0002) ? 1 : 0); $abook['abook_hidden'] = (($abook['abook_flags'] & 0x0004) ? 1 : 0); $abook['abook_archived'] = (($abook['abook_flags'] & 0x0008) ? 1 : 0); $abook['abook_pending'] = (($abook['abook_flags'] & 0x0010) ? 1 : 0); $abook['abook_unconnected'] = (($abook['abook_flags'] & 0x0020) ? 1 : 0); $abook['abook_self'] = (($abook['abook_flags'] & 0x0080) ? 1 : 0); $abook['abook_feed'] = (($abook['abook_flags'] & 0x0100) ? 1 : 0); } $clean = array(); if($abook['abook_xchan'] && $abook['entry_deleted']) { logger('process_channel_sync_delivery: removing abook entry for ' . $abook['abook_xchan']); $r = q("select abook_id, abook_feed from abook where abook_xchan = '%s' and abook_channel = %d and abook_self = 0 limit 1", dbesc($abook['abook_xchan']), intval($channel['channel_id']) ); if($r) { contact_remove($channel['channel_id'],$r[0]['abook_id']); if($total_friends) $total_friends --; if(intval($r[0]['abook_feed'])) $total_feeds --; } continue; } // Perform discovery if the referenced xchan hasn't ever been seen on this hub. // This relies on the undocumented behaviour that red sites send xchan info with the abook // and import_author_xchan will look them up on all federated networks if($abook['abook_xchan'] && $abook['xchan_addr']) { $h = zot_get_hublocs($abook['abook_xchan']); if(! $h) { $xhash = import_author_xchan(encode_item_xchan($abook)); if(! $xhash) { logger('process_channel_sync_delivery: import of ' . $abook['xchan_addr'] . ' failed.'); continue; } } } foreach($abook as $k => $v) { if(in_array($k,$disallowed) || (strpos($k,'abook') !== 0)) continue; $clean[$k] = $v; } if(! array_key_exists('abook_xchan',$clean)) continue; $r = q("select * from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($clean['abook_xchan']), intval($channel['channel_id']) ); // make sure we have an abook entry for this xchan on this system if(! $r) { if($max_friends !== false && $total_friends > $max_friends) { logger('process_channel_sync_delivery: total_channels service class limit exceeded'); continue; } if($max_feeds !== false && intval($clean['abook_feed']) && $total_feeds > $max_feeds) { logger('process_channel_sync_delivery: total_feeds service class limit exceeded'); continue; } q("insert into abook ( abook_xchan, abook_account, abook_channel ) values ('%s', %d, %d ) ", dbesc($clean['abook_xchan']), intval($channel['channel_account_id']), intval($channel['channel_id']) ); $total_friends ++; if(intval($clean['abook_feed'])) $total_feeds ++; } if(count($clean)) { foreach($clean as $k => $v) { if($k == 'abook_dob') $v = dbescdate($v); $r = dbq("UPDATE abook set " . dbesc($k) . " = '" . dbesc($v) . "' where abook_xchan = '" . dbesc($clean['abook_xchan']) . "' and abook_channel = " . intval($channel['channel_id'])); } } // This will set abconfig vars if the sender is using old-style fixed permissions // using the raw abook record as passed to us. New-style permissions will fall through // and be set using abconfig translate_abook_perms_inbound($channel,$abook); if($abconfig) { // @fixme does not handle sync of del_abconfig foreach($abconfig as $abc) { set_abconfig($channel['channel_id'],$abc['xchan'],$abc['cat'],$abc['k'],$abc['v']); } } } } // sync collections (privacy groups) oh joy... if(array_key_exists('collections',$arr) && is_array($arr['collections']) && count($arr['collections'])) { $x = q("select * from groups where uid = %d", intval($channel['channel_id']) ); foreach($arr['collections'] as $cl) { $found = false; if($x) { foreach($x as $y) { if($cl['collection'] == $y['hash']) { $found = true; break; } } if($found) { if(($y['gname'] != $cl['name']) || ($y['visible'] != $cl['visible']) || ($y['deleted'] != $cl['deleted'])) { q("update groups set gname = '%s', visible = %d, deleted = %d where hash = '%s' and uid = %d", dbesc($cl['name']), intval($cl['visible']), intval($cl['deleted']), dbesc($cl['hash']), intval($channel['channel_id']) ); } if(intval($cl['deleted']) && (! intval($y['deleted']))) { q("delete from group_member where gid = %d", intval($y['id']) ); } } } if(! $found) { $r = q("INSERT INTO `groups` ( hash, uid, visible, deleted, gname ) VALUES( '%s', %d, %d, %d, '%s' ) ", dbesc($cl['collection']), intval($channel['channel_id']), intval($cl['visible']), intval($cl['deleted']), dbesc($cl['name']) ); } // now look for any collections locally which weren't in the list we just received. // They need to be removed by marking deleted and removing the members. // This shouldn't happen except for clones created before this function was written. if($x) { $found_local = false; foreach($x as $y) { foreach($arr['collections'] as $cl) { if($cl['collection'] == $y['hash']) { $found_local = true; break; } } if(! $found_local) { q("delete from group_member where gid = %d", intval($y['id']) ); q("update groups set deleted = 1 where id = %d and uid = %d", intval($y['id']), intval($channel['channel_id']) ); } } } } // reload the group list with any updates $x = q("select * from groups where uid = %d", intval($channel['channel_id']) ); // now sync the members if(array_key_exists('collection_members', $arr) && is_array($arr['collection_members']) && count($arr['collection_members'])) { // first sort into groups keyed by the group hash $members = array(); foreach($arr['collection_members'] as $cm) { if(! array_key_exists($cm['collection'],$members)) $members[$cm['collection']] = array(); $members[$cm['collection']][] = $cm['member']; } // our group list is already synchronised if($x) { foreach($x as $y) { // for each group, loop on members list we just received foreach($members[$y['hash']] as $member) { $found = false; $z = q("select xchan from group_member where gid = %d and uid = %d and xchan = '%s' limit 1", intval($y['id']), intval($channel['channel_id']), dbesc($member) ); if($z) $found = true; // if somebody is in the group that wasn't before - add them if(! $found) { q("INSERT INTO `group_member` (`uid`, `gid`, `xchan`) VALUES( %d, %d, '%s' ) ", intval($channel['channel_id']), intval($y['id']), dbesc($member) ); } } // now retrieve a list of members we have on this site $m = q("select xchan from group_member where gid = %d and uid = %d", intval($y['id']), intval($channel['channel_id']) ); if($m) { foreach($m as $mm) { // if the local existing member isn't in the list we just received - remove them if(! in_array($mm['xchan'],$members[$y['hash']])) { q("delete from group_member where xchan = '%s' and gid = %d and uid = %d", dbesc($mm['xchan']), intval($y['id']), intval($channel['channel_id']) ); } } } } } } } if(array_key_exists('profile',$arr) && is_array($arr['profile']) && count($arr['profile'])) { $disallowed = array('id','aid','uid','guid'); foreach($arr['profile'] as $profile) { $x = q("select * from profile where profile_guid = '%s' and uid = %d limit 1", dbesc($profile['profile_guid']), intval($channel['channel_id']) ); if(! $x) { q("insert into profile ( profile_guid, aid, uid ) values ('%s', %d, %d)", dbesc($profile['profile_guid']), intval($channel['channel_account_id']), intval($channel['channel_id']) ); $x = q("select * from profile where profile_guid = '%s' and uid = %d limit 1", dbesc($profile['profile_guid']), intval($channel['channel_id']) ); if(! $x) continue; } $clean = array(); foreach($profile as $k => $v) { if(in_array($k,$disallowed)) continue; if($k === 'name') $clean['fullname'] = $v; elseif($k === 'with') $clean['partner'] = $v; elseif($k === 'work') $clean['employment'] = $v; elseif(array_key_exists($k,$x[0])) $clean[$k] = $v; /** * @TODO * We also need to import local photos if a custom photo is selected */ } if(count($clean)) { foreach($clean as $k => $v) { $r = dbq("UPDATE profile set `" . dbesc($k) . "` = '" . dbesc($v) . "' where profile_guid = '" . dbesc($profile['profile_guid']) . "' and uid = " . intval($channel['channel_id'])); } } } } $addon = array('channel' => $channel,'data' => $arr); call_hooks('process_channel_sync_delivery',$addon); // we should probably do this for all items, but usually we only send one. if(array_key_exists('item',$arr) && is_array($arr['item'][0])) { $DR = new Zotlabs\Zot\DReport(z_root(),$d['hash'],$d['hash'],$arr['item'][0]['message_id'],'channel sync processed'); $DR->addto_recipient($channel['channel_name'] . ' <' . $channel['channel_address'] . '@' . App::get_hostname() . '>'); } else $DR = new Zotlabs\Zot\DReport(z_root(),$d['hash'],$d['hash'],'sync packet','channel sync delivered'); $result[] = $DR->get(); } return $result; } /** * @brief Returns path to /rpost * * @todo We probably should make rpost discoverable. * * @param array $observer * * \e string \b xchan_url * @return string */ function get_rpost_path($observer) { if(! $observer) return ''; $parsed = parse_url($observer['xchan_url']); return $parsed['scheme'] . '://' . $parsed['host'] . (($parsed['port']) ? ':' . $parsed['port'] : '') . '/rpost?f='; } /** * @brief * * @param array $x * @return boolean|string return false or a hash */ function import_author_zot($x) { $hash = make_xchan_hash($x['guid'],$x['guid_sig']); $r = q("select hubloc_url from hubloc where hubloc_guid = '%s' and hubloc_guid_sig = '%s' and hubloc_primary = 1 limit 1", dbesc($x['guid']), dbesc($x['guid_sig']) ); if ($r) { logger('import_author_zot: in cache', LOGGER_DEBUG); return $hash; } logger('import_author_zot: entry not in cache - probing: ' . print_r($x,true), LOGGER_DEBUG); $them = array('hubloc_url' => $x['url'], 'xchan_guid' => $x['guid'], 'xchan_guid_sig' => $x['guid_sig']); if (zot_refresh($them)) return $hash; return false; } /** * @brief Process a message request. * * If a site receives a comment to a post but finds they have no parent to attach it with, they * may send a 'request' packet containing the message_id of the missing parent. This is the handler * for that packet. We will create a message_list array of the entire conversation starting with * the missing parent and invoke delivery to the sender of the packet. * * include/deliver.php (for local delivery) and mod/post.php (for web delivery) detect the existence of * this 'message_list' at the destination and split it into individual messages which are * processed/delivered in order. * * Called from mod/post.php * * @param array $data * @return array */ function zot_reply_message_request($data) { $ret = array('success' => false); if (! $data['message_id']) { $ret['message'] = 'no message_id'; logger('no message_id'); json_return_and_die($ret); } $sender = $data['sender']; $sender_hash = make_xchan_hash($sender['guid'], $sender['guid_sig']); /* * Find the local channel in charge of this post (the first and only recipient of the request packet) */ $arr = $data['recipients'][0]; $recip_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']); $c = q("select * from channel left join xchan on channel_hash = xchan_hash where channel_hash = '%s' limit 1", dbesc($recip_hash) ); if (! $c) { logger('recipient channel not found.'); $ret['message'] .= 'recipient not found.' . EOL; json_return_and_die($ret); } /* * fetch the requested conversation */ $messages = zot_feed($c[0]['channel_id'],$sender_hash,array('message_id' => $data['message_id'])); if ($messages) { $env_recips = null; $r = q("select * from hubloc where hubloc_hash = '%s' and hubloc_error = 0 and hubloc_deleted = 0 group by hubloc_sitekey", dbesc($sender_hash) ); if (! $r) { logger('no hubs'); json_return_and_die($ret); } $hubs = $r; $private = ((array_key_exists('flags', $messages[0]) && in_array('private',$messages[0]['flags'])) ? true : false); if($private) $env_recips = array('guid' => $sender['guid'], 'guid_sig' => $sender['guid_sig'], 'hash' => $sender_hash); $data_packet = json_encode(array('message_list' => $messages)); foreach($hubs as $hub) { $hash = random_string(); /* * create a notify packet and drop the actual message packet in the queue for pickup */ $n = zot_build_packet($c[0],'notify',$env_recips,(($private) ? $hub['hubloc_sitekey'] : null),$hash,array('message_id' => $data['message_id'])); queue_insert(array( 'hash' => $hash, 'account_id' => $c[0]['channel_account_id'], 'channel_id' => $c[0]['channel_id'], 'posturl' => $hub['hubloc_callback'], 'notify' => $n, 'msg' => $data_packet )); /* * invoke delivery to send out the notify packet */ Zotlabs\Daemon\Master::Summon(array('Deliver', $hash)); } } $ret['success'] = true; json_return_and_die($ret); } function zotinfo($arr) { $ret = array('success' => false); $zhash = ((x($arr,'guid_hash')) ? $arr['guid_hash'] : ''); $zguid = ((x($arr,'guid')) ? $arr['guid'] : ''); $zguid_sig = ((x($arr,'guid_sig')) ? $arr['guid_sig'] : ''); $zaddr = ((x($arr,'address')) ? $arr['address'] : ''); $ztarget = ((x($arr,'target')) ? $arr['target'] : ''); $zsig = ((x($arr,'target_sig')) ? $arr['target_sig'] : ''); $zkey = ((x($arr,'key')) ? $arr['key'] : ''); $mindate = ((x($arr,'mindate')) ? $arr['mindate'] : ''); $token = ((x($arr,'token')) ? $arr['token'] : ''); $feed = ((x($arr,'feed')) ? intval($arr['feed']) : 0); if($ztarget) { if((! $zkey) || (! $zsig) || (! rsa_verify($ztarget,base64url_decode($zsig),$zkey))) { logger('zfinger: invalid target signature'); $ret['message'] = t("invalid target signature"); return($ret); } } $ztarget_hash = (($ztarget && $zsig) ? make_xchan_hash($ztarget,$zsig) : '' ); $r = null; if(strlen($zhash)) { $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_hash = '%s' limit 1", dbesc($zhash) ); } elseif(strlen($zguid) && strlen($zguid_sig)) { $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_guid = '%s' and channel_guid_sig = '%s' limit 1", dbesc($zguid), dbesc($zguid_sig) ); } elseif(strlen($zaddr)) { if(strpos($zaddr,'[system]') === false) { /* normal address lookup */ $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where ( channel_address = '%s' or xchan_addr = '%s' ) limit 1", dbesc($zaddr), dbesc($zaddr) ); } else { /** * The special address '[system]' will return a system channel if one has been defined, * Or the first valid channel we find if there are no system channels. * * This is used by magic-auth if we have no prior communications with this site - and * returns an identity on this site which we can use to create a valid hub record so that * we can exchange signed messages. The precise identity is irrelevant. It's the hub * information that we really need at the other end - and this will return it. * */ $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_system = 1 order by channel_id limit 1"); if(! $r) { $r = q("select channel.*, xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_removed = 0 order by channel_id limit 1"); } } } else { $ret['message'] = 'Invalid request'; return($ret); } if(! $r) { $ret['message'] = 'Item not found.'; return($ret); } $e = $r[0]; $id = $e['channel_id']; $sys_channel = (intval($e['channel_system']) ? true : false); $special_channel = (($e['channel_pageflags'] & PAGE_PREMIUM) ? true : false); $adult_channel = (($e['channel_pageflags'] & PAGE_ADULT) ? true : false); $censored = (($e['channel_pageflags'] & PAGE_CENSORED) ? true : false); $searchable = (($e['channel_pageflags'] & PAGE_HIDDEN) ? false : true); $deleted = (intval($e['xchan_deleted']) ? true : false); if($deleted || $censored || $sys_channel) $searchable = false; $public_forum = false; $role = get_pconfig($e['channel_id'],'system','permissions_role'); if($role === 'forum' || $role === 'repository') { $public_forum = true; } elseif($ztarget_hash) { // check if it has characteristics of a public forum based on custom permissions. $t = q("select * from abconfig where abconfig.cat = 'my_perms' and abconfig.chan = %d and abconfig.xchan = '%s' and abconfig.k in ('tag_deliver', 'send_stream') ", intval($e['channel_id']), dbesc($ztarget_hash) ); $ch = 0; if($t) { foreach($t as $tt) { if($tt['k'] == 'tag_deliver' && $tt['v'] == 1) $ch ++; if($tt['k'] == 'send_stream' && $tt['v'] == 0) $ch ++; } if($ch == 2) $public_forum = true; } } // This is for birthdays and keywords, but must check access permissions $p = q("select * from profile where uid = %d and is_default = 1", intval($e['channel_id']) ); $profile = array(); if($p) { if(! intval($p[0]['publish'])) $searchable = false; $profile['description'] = $p[0]['pdesc']; $profile['birthday'] = $p[0]['dob']; if(($profile['birthday'] != '0000-00-00') && (($bd = z_birthday($p[0]['dob'],$e['channel_timezone'])) !== '')) $profile['next_birthday'] = $bd; if($age = age($p[0]['dob'],$e['channel_timezone'],'')) $profile['age'] = $age; $profile['gender'] = $p[0]['gender']; $profile['marital'] = $p[0]['marital']; $profile['sexual'] = $p[0]['sexual']; $profile['locale'] = $p[0]['locality']; $profile['region'] = $p[0]['region']; $profile['postcode'] = $p[0]['postal_code']; $profile['country'] = $p[0]['country_name']; $profile['about'] = $p[0]['about']; $profile['homepage'] = $p[0]['homepage']; $profile['hometown'] = $p[0]['hometown']; if($p[0]['keywords']) { $tags = array(); $k = explode(' ',$p[0]['keywords']); if($k) { foreach($k as $kk) { if(trim($kk," \t\n\r\0\x0B,")) { $tags[] = trim($kk," \t\n\r\0\x0B,"); } } } if($tags) $profile['keywords'] = $tags; } } $ret['success'] = true; // Communication details if($token) $ret['signed_token'] = base64url_encode(rsa_sign('token.' . $token,$e['channel_prvkey'])); $ret['guid'] = $e['xchan_guid']; $ret['guid_sig'] = $e['xchan_guid_sig']; $ret['key'] = $e['xchan_pubkey']; $ret['name'] = $e['xchan_name']; $ret['name_updated'] = $e['xchan_name_date']; $ret['address'] = $e['xchan_addr']; $ret['photo_mimetype'] = $e['xchan_photo_mimetype']; $ret['photo'] = $e['xchan_photo_l']; $ret['photo_updated'] = $e['xchan_photo_date']; $ret['url'] = $e['xchan_url']; $ret['connections_url']= (($e['xchan_connurl']) ? $e['xchan_connurl'] : z_root() . '/poco/' . $e['channel_address']); $ret['target'] = $ztarget; $ret['target_sig'] = $zsig; $ret['searchable'] = $searchable; $ret['adult_content'] = $adult_channel; $ret['public_forum'] = $public_forum; if($deleted) $ret['deleted'] = $deleted; if(intval($e['channel_removed'])) $ret['deleted_locally'] = true; // premium or other channel desiring some contact with potential followers before connecting. // This is a template - %s will be replaced with the follow_url we discover for the return channel. if($special_channel) $ret['connect_url'] = z_root() . '/connect/' . $e['channel_address']; // This is a template for our follow url, %s will be replaced with a webbie $ret['follow_url'] = z_root() . '/follow?f=&url=%s'; $permissions = get_all_perms($e['channel_id'],$ztarget_hash,false); if($ztarget_hash) { $permissions['connected'] = false; $b = q("select * from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($ztarget_hash), intval($e['channel_id']) ); if($b) $permissions['connected'] = true; } $ret['permissions'] = (($ztarget && $zkey) ? crypto_encapsulate(json_encode($permissions),$zkey) : $permissions); if($permissions['view_profile']) $ret['profile'] = $profile; // array of (verified) hubs this channel uses $x = zot_encode_locations($e); if($x) $ret['locations'] = $x; $ret['site'] = array(); $ret['site']['url'] = z_root(); $ret['site']['url_sig'] = base64url_encode(rsa_sign(z_root(),$e['channel_prvkey'])); $ret['site']['zot_auth'] = z_root() . '/magic'; $dirmode = get_config('system','directory_mode'); if(($dirmode === false) || ($dirmode == DIRECTORY_MODE_NORMAL)) $ret['site']['directory_mode'] = 'normal'; if($dirmode == DIRECTORY_MODE_PRIMARY) $ret['site']['directory_mode'] = 'primary'; elseif($dirmode == DIRECTORY_MODE_SECONDARY) $ret['site']['directory_mode'] = 'secondary'; elseif($dirmode == DIRECTORY_MODE_STANDALONE) $ret['site']['directory_mode'] = 'standalone'; if($dirmode != DIRECTORY_MODE_NORMAL) $ret['site']['directory_url'] = z_root() . '/dirsearch'; // hide detailed site information if you're off the grid if($dirmode != DIRECTORY_MODE_STANDALONE) { $register_policy = intval(get_config('system','register_policy')); if($register_policy == REGISTER_CLOSED) $ret['site']['register_policy'] = 'closed'; if($register_policy == REGISTER_APPROVE) $ret['site']['register_policy'] = 'approve'; if($register_policy == REGISTER_OPEN) $ret['site']['register_policy'] = 'open'; $access_policy = intval(get_config('system','access_policy')); if($access_policy == ACCESS_PRIVATE) $ret['site']['access_policy'] = 'private'; if($access_policy == ACCESS_PAID) $ret['site']['access_policy'] = 'paid'; if($access_policy == ACCESS_FREE) $ret['site']['access_policy'] = 'free'; if($access_policy == ACCESS_TIERED) $ret['site']['access_policy'] = 'tiered'; $ret['site']['accounts'] = account_total(); require_once('include/channel.php'); $ret['site']['channels'] = channel_total(); $ret['site']['version'] = Zotlabs\Lib\System::get_platform_name() . ' ' . STD_VERSION . '[' . DB_UPDATE_VERSION . ']'; $ret['site']['admin'] = get_config('system','admin_email'); $visible_plugins = array(); if(is_array(App::$plugins) && count(App::$plugins)) { $r = q("select * from addon where hidden = 0"); if($r) foreach($r as $rr) $visible_plugins[] = $rr['name']; } $ret['site']['plugins'] = $visible_plugins; $ret['site']['sitehash'] = get_config('system','location_hash'); $ret['site']['sitename'] = get_config('system','sitename'); $ret['site']['sellpage'] = get_config('system','sellpage'); $ret['site']['location'] = get_config('system','site_location'); $ret['site']['realm'] = get_directory_realm(); $ret['site']['project'] = Zotlabs\Lib\System::get_platform_name() . ' ' . Zotlabs\Lib\System::get_server_role(); } check_zotinfo($e,$x,$ret); call_hooks('zot_finger',$ret); return($ret); } function check_zotinfo($channel,$locations,&$ret) { // logger('locations: ' . print_r($locations,true),LOGGER_DATA, LOG_DEBUG); // This function will likely expand as we find more things to detect and fix. // 1. Because magic-auth is reliant on it, ensure that the system channel has a valid hubloc // Force this to be the case if anything is found to be wrong with it. // @FIXME ensure that the system channel exists in the first place and has an xchan if($channel['channel_system']) { // the sys channel must have a location (hubloc) $valid_location = false; if((count($locations) === 1) && ($locations[0]['primary']) && (! $locations[0]['deleted'])) { if((rsa_verify($locations[0]['url'],base64url_decode($locations[0]['url_sig']),$channel['channel_pubkey'])) && ($locations[0]['sitekey'] === get_config('system','pubkey')) && ($locations[0]['url'] === z_root())) $valid_location = true; else logger('sys channel: invalid url signature'); } if((! $locations) || (! $valid_location)) { logger('System channel locations are not valid. Attempting repair.'); // Don't trust any existing records. Just get rid of them, but only do this // for the sys channel as normal channels will be trickier. q("delete from hubloc where hubloc_hash = '%s'", dbesc($channel['channel_hash']) ); $r = q("insert into hubloc ( hubloc_guid, hubloc_guid_sig, hubloc_hash, hubloc_addr, hubloc_primary, hubloc_url, hubloc_url_sig, hubloc_host, hubloc_callback, hubloc_sitekey, hubloc_network ) values ( '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s' )", dbesc($channel['channel_guid']), dbesc($channel['channel_guid_sig']), dbesc($channel['channel_hash']), dbesc($channel['channel_address'] . '@' . App::get_hostname()), intval(1), dbesc(z_root()), dbesc(base64url_encode(rsa_sign(z_root(),$channel['channel_prvkey']))), dbesc(App::get_hostname()), dbesc(z_root() . '/post'), dbesc(get_config('system','pubkey')), dbesc('zot') ); if($r) { $x = zot_encode_locations($channel); if($x) { $ret['locations'] = $x; } } else { logger('Unable to store sys hub location'); } } } } function delivery_report_is_storable($dr) { if(get_config('system','disable_dreport')) return false; call_hooks('dreport_is_storable',$dr); // let plugins accept or reject - if neither, continue on if(array_key_exists('accept',$dr) && intval($dr['accept'])) return true; if(array_key_exists('reject',$dr) && intval($dr['reject'])) return false; if(! ($dr['sender'])) return false; // Is the sender one of our channels? $c = q("select channel_id from channel where channel_hash = '%s' limit 1", dbesc($dr['sender']) ); if(! $c) return false; // is the recipient one of our connections, or do we want to store every report? $r = explode(' ', $dr['recipient']); $rxchan = $r[0]; $pcf = get_pconfig($c[0]['channel_id'],'system','dreport_store_all'); if($pcf) return true; // We always add ourself as a recipient to private and relayed posts // So if a remote site says they can't find us, that's no big surprise // and just creates a lot of extra report noise if(($dr['location'] !== z_root()) && ($dr['sender'] === $rxchan) && ($dr['status'] === 'recipient_not_found')) return false; // If you have a private post with a recipient list, every single site is going to report // back a failed delivery for anybody on that list that isn't local to them. We're only // concerned about this if we have a local hubloc record which says we expected them to // have a channel on that site. $r = q("select hubloc_id from hubloc where hubloc_hash = '%s' and hubloc_url = '%s'", dbesc($rxchan), dbesc($dr['location']) ); if((! $r) && ($dr['status'] === 'recipient_not_found')) return false; $r = q("select abook_id from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($rxchan), intval($c[0]['channel_id']) ); if($r) return true; return false; } function update_hub_connected($hub,$sitekey = '') { if($sitekey) { /* * This hub has now been proven to be valid. * Any hub with the same URL and a different sitekey cannot be valid. * Get rid of them (mark them deleted). There's a good chance they were re-installs. */ q("update hubloc set hubloc_deleted = 1, hubloc_error = 1 where hubloc_url = '%s' and hubloc_sitekey != '%s' ", dbesc($hub['hubloc_url']), dbesc($sitekey) ); } else { $sitekey = $hub['sitekey']; } // $sender['sitekey'] is a new addition to the protocol to distinguish // hublocs coming from re-installed sites. Older sites will not provide // this field and we have to still mark them valid, since we can't tell // if this hubloc has the same sitekey as the packet we received. // Update our DB to show when we last communicated successfully with this hub // This will allow us to prune dead hubs from using up resources $t = datetime_convert('UTC','UTC','now - 15 minutes'); $r = q("update hubloc set hubloc_connected = '%s' where hubloc_id = %d and hubloc_sitekey = '%s' and hubloc_connected < '%s' ", dbesc(datetime_convert()), intval($hub['hubloc_id']), dbesc($sitekey), dbesc($t) ); // a dead hub came back to life - reset any tombstones we might have if(intval($hub['hubloc_error'])) { q("update hubloc set hubloc_error = 0 where hubloc_id = %d and hubloc_sitekey = '%s' ", intval($hub['hubloc_id']), dbesc($sitekey) ); if(intval($r[0]['hubloc_orphancheck'])) { q("update hubloc set hubloc_orhpancheck = 0 where hubloc_id = %d and hubloc_sitekey = '%s' ", intval($hub['hubloc_id']), dbesc($sitekey) ); } q("update xchan set xchan_orphan = 0 where xchan_orphan = 1 and xchan_hash = '%s'", dbesc($hub['hubloc_hash']) ); } return $hub['hubloc_url']; } function zot_reply_ping() { $ret = array('success'=> false); // Useful to get a health check on a remote site. // This will let us know if any important communication details // that we may have stored are no longer valid, regardless of xchan details. logger('POST: got ping send pong now back: ' . z_root() , LOGGER_DEBUG ); $ret['success'] = true; $ret['site'] = array(); $ret['site']['url'] = z_root(); $ret['site']['url_sig'] = base64url_encode(rsa_sign(z_root(),get_config('system','prvkey'))); $ret['site']['sitekey'] = get_config('system','pubkey'); json_return_and_die($ret); } function zot_reply_pickup($data) { $ret = array('success'=> false); /* * The 'pickup' message arrives with a tracking ID which is associated with a particular outq_hash * First verify that that the returned signatures verify, then check that we have an outbound queue item * with the correct hash. * If everything verifies, find any/all outbound messages in the queue for this hubloc and send them back */ if((! $data['secret']) || (! $data['secret_sig'])) { $ret['message'] = 'no verification signature'; logger('mod_zot: pickup: ' . $ret['message'], LOGGER_DEBUG); json_return_and_die($ret); } $r = q("select distinct hubloc_sitekey from hubloc where hubloc_url = '%s' and hubloc_callback = '%s' and hubloc_sitekey != '' group by hubloc_sitekey ", dbesc($data['url']), dbesc($data['callback']) ); if(! $r) { $ret['message'] = 'site not found'; logger('mod_zot: pickup: ' . $ret['message']); json_return_and_die($ret); } foreach ($r as $hubsite) { // verify the url_sig // If the server was re-installed at some point, there could be multiple hubs with the same url and callback. // Only one will have a valid key. $forgery = true; $secret_fail = true; $sitekey = $hubsite['hubloc_sitekey']; logger('mod_zot: Checking sitekey: ' . $sitekey, LOGGER_DATA, LOG_DEBUG); if(rsa_verify($data['callback'],base64url_decode($data['callback_sig']),$sitekey)) { $forgery = false; } if(rsa_verify($data['secret'],base64url_decode($data['secret_sig']),$sitekey)) { $secret_fail = false; } if((! $forgery) && (! $secret_fail)) break; } if($forgery) { $ret['message'] = 'possible site forgery'; logger('mod_zot: pickup: ' . $ret['message']); json_return_and_die($ret); } if($secret_fail) { $ret['message'] = 'secret validation failed'; logger('mod_zot: pickup: ' . $ret['message']); json_return_and_die($ret); } /* * If we made it to here, the signatures verify, but we still don't know if the tracking ID is valid. * It wouldn't be an error if the tracking ID isn't found, because we may have sent this particular * queue item with another pickup (after the tracking ID for the other pickup was verified). */ $r = q("select outq_posturl from outq where outq_hash = '%s' and outq_posturl = '%s' limit 1", dbesc($data['secret']), dbesc($data['callback']) ); if(! $r) { $ret['message'] = 'nothing to pick up'; logger('mod_zot: pickup: ' . $ret['message']); json_return_and_die($ret); } /* * Everything is good if we made it here, so find all messages that are going to this location * and send them all. */ $r = q("select * from outq where outq_posturl = '%s'", dbesc($data['callback']) ); if($r) { logger('mod_zot: successful pickup message received from ' . $data['callback'] . ' ' . count($r) . ' message(s) picked up', LOGGER_DEBUG); $ret['success'] = true; $ret['pickup'] = array(); foreach($r as $rr) { if($rr['outq_msg']) { $x = json_decode($rr['outq_msg'],true); if(! $x) continue; if(is_array($x) && array_key_exists('message_list',$x)) { foreach($x['message_list'] as $xx) { $ret['pickup'][] = array('notify' => json_decode($rr['outq_notify'],true),'message' => $xx); } } else $ret['pickup'][] = array('notify' => json_decode($rr['outq_notify'],true),'message' => $x); remove_queue_item($rr['outq_hash']); } } } $encrypted = crypto_encapsulate(json_encode($ret),$sitekey); json_return_and_die($encrypted); /* pickup: end */ } function zot_reply_auth_check($data,$encrypted_packet) { $ret = array('success' => false); /* * Requestor visits /magic/?dest=somewhere on their own site with a browser * magic redirects them to $destsite/post [with auth args....] * $destsite sends an auth_check packet to originator site * The auth_check packet is handled here by the originator's site * - the browser session is still waiting * inside $destsite/post for everything to verify * If everything checks out we'll return a token to $destsite * and then $destsite will verify the token, authenticate the browser * session and then redirect to the original destination. * If authentication fails, the redirection to the original destination * will still take place but without authentication. */ logger('mod_zot: auth_check', LOGGER_DEBUG); if (! $encrypted_packet) { logger('mod_zot: auth_check packet was not encrypted.'); $ret['message'] .= 'no packet encryption' . EOL; json_return_and_die($ret); } $arr = $data['sender']; $sender_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']); // garbage collect any old unused notifications // This was and should be 10 minutes but my hosting provider has time lag between the DB and // the web server. We should probably convert this to webserver time rather than DB time so // that the different clocks won't affect it and allow us to keep the time short. Zotlabs\Zot\Verify::purge('auth','30 MINUTE'); $y = q("select xchan_pubkey from xchan where xchan_hash = '%s' limit 1", dbesc($sender_hash) ); // We created a unique hash in mod/magic.php when we invoked remote auth, and stored it in // the verify table. It is now coming back to us as 'secret' and is signed by a channel at the other end. // First verify their signature. We will have obtained a zot-info packet from them as part of the sender // verification. if ((! $y) || (! rsa_verify($data['secret'], base64url_decode($data['secret_sig']),$y[0]['xchan_pubkey']))) { logger('mod_zot: auth_check: sender not found or secret_sig invalid.'); $ret['message'] .= 'sender not found or sig invalid ' . print_r($y,true) . EOL; json_return_and_die($ret); } // There should be exactly one recipient, the original auth requestor $ret['message'] .= 'recipients ' . print_r($recipients,true) . EOL; if ($data['recipients']) { $arr = $data['recipients'][0]; $recip_hash = make_xchan_hash($arr['guid'], $arr['guid_sig']); $c = q("select channel_id, channel_account_id, channel_prvkey from channel where channel_hash = '%s' limit 1", dbesc($recip_hash) ); if (! $c) { logger('mod_zot: auth_check: recipient channel not found.'); $ret['message'] .= 'recipient not found.' . EOL; json_return_and_die($ret); } $confirm = base64url_encode(rsa_sign($data['secret'] . $recip_hash,$c[0]['channel_prvkey'])); // This additionally checks for forged sites since we already stored the expected result in meta // and we've already verified that this is them via zot_gethub() and that their key signed our token $z = Zotlabs\Zot\Verify::match('auth',$c[0]['channel_id'],$data['secret'],$data['sender']['url']); if (! $z) { logger('mod_zot: auth_check: verification key not found.'); $ret['message'] .= 'verification key not found' . EOL; json_return_and_die($ret); } $u = q("select account_service_class from account where account_id = %d limit 1", intval($c[0]['channel_account_id']) ); logger('mod_zot: auth_check: success', LOGGER_DEBUG); $ret['success'] = true; $ret['confirm'] = $confirm; if ($u && $u[0]['account_service_class']) $ret['service_class'] = $u[0]['account_service_class']; // Set "do not track" flag if this site or this channel's profile is restricted // in some way if (intval(get_config('system','block_public'))) $ret['DNT'] = true; if (! perm_is_allowed($c[0]['channel_id'],'','view_profile')) $ret['DNT'] = true; if (get_pconfig($c[0]['channel_id'],'system','do_not_track')) $ret['DNT'] = true; if (get_pconfig($c[0]['channel_id'],'system','hide_online_status')) $ret['DNT'] = true; json_return_and_die($ret); } json_return_and_die($ret); } function zot_reply_purge($sender,$recipients) { $ret = array('success' => false); if ($recipients) { // basically this means "unfriend" foreach ($recipients as $recip) { $r = q("select channel.*,xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_guid = '%s' and channel_guid_sig = '%s' limit 1", dbesc($recip['guid']), dbesc($recip['guid_sig']) ); if ($r) { $r = q("select abook_id from abook where uid = %d and abook_xchan = '%s' limit 1", intval($r[0]['channel_id']), dbesc(make_xchan_hash($sender['guid'],$sender['guid_sig'])) ); if ($r) { contact_remove($r[0]['channel_id'],$r[0]['abook_id']); } } } $ret['success'] = true; } else { // Unfriend everybody - basically this means the channel has committed suicide $arr = $sender; $sender_hash = make_xchan_hash($arr['guid'],$arr['guid_sig']); remove_all_xchan_resources($sender_hash); $ret['success'] = true; } json_return_and_die($ret); } function zot_reply_refresh($sender,$recipients) { $ret = array('success' => false); // remote channel info (such as permissions or photo or something) // has been updated. Grab a fresh copy and sync it. // The difference between refresh and force_refresh is that // force_refresh unconditionally creates a directory update record, // even if no changes were detected upon processing. if($recipients) { // This would be a permissions update, typically for one connection foreach ($recipients as $recip) { $r = q("select channel.*,xchan.* from channel left join xchan on channel_hash = xchan_hash where channel_guid = '%s' and channel_guid_sig = '%s' limit 1", dbesc($recip['guid']), dbesc($recip['guid_sig']) ); $x = zot_refresh(array( 'xchan_guid' => $sender['guid'], 'xchan_guid_sig' => $sender['guid_sig'], 'hubloc_url' => $sender['url'] ), $r[0], (($msgtype === 'force_refresh') ? true : false)); } } else { // system wide refresh $x = zot_refresh(array( 'xchan_guid' => $sender['guid'], 'xchan_guid_sig' => $sender['guid_sig'], 'hubloc_url' => $sender['url'] ), null, (($msgtype === 'force_refresh') ? true : false)); } $ret['success'] = true; json_return_and_die($ret); } function zot_reply_notify($data) { $ret = array('success' => false); logger('notify received from ' . $data['sender']['url']); $async = get_config('system','queued_fetch'); if($async) { // add to receive queue // qreceive_add($data); } else { $x = zot_fetch($data); $ret['delivery_report'] = $x; } $ret['success'] = true; json_return_and_die($ret); }
HaakonME/hubzilla
include/zot.php
PHP
mit
147,068
/** * */ package org.edtoktay.dynamic.compiler; /** * @author deniz.toktay * */ public interface ExampleInterface { void addObject(String arg1, String arg2); Object getObject(String arg1); }
edtoktay/DynamicCompiler
Example/src/main/java/org/edtoktay/dynamic/compiler/ExampleInterface.java
Java
mit
200
import React, { Component } from 'react'; import { StyleSheet, Text, View, Navigator, ScrollView, ListView, } from 'react-native' import NavigationBar from 'react-native-navbar'; var REQUEST_URL = 'https://calm-garden-29993.herokuapp.com/index/groupsinfo/?'; class GroupDetails extends Component { constructor(props, context) { super(props, context); this.state = { loggedIn: true, loaded: false, rando: "a", }; this.fetchData(); } backOnePage () { this.props.navigator.pop(); } renderRide (ride) { return ( <View> <Text style={styles.title}>{ride.title}</Text> </View> ); } componentDidMount () { this.fetchData(); } toQueryString(obj) { return obj ? Object.keys(obj).sort().map(function (key) { var val = obj[key]; if (Array.isArray(val)) { return val.sort().map(function (val2) { return encodeURIComponent(key) + '=' + encodeURIComponent(val2); }).join('&'); } return encodeURIComponent(key) + '=' + encodeURIComponent(val); }).join('&') : ''; } fetchData() { console.log(this.props.group_info.pk); fetch(REQUEST_URL + this.toQueryString({"group": this.props.group_info.pk})) .then((response) => response.json()) .then((responseData) => { console.log(responseData); this.setState({ group_info: responseData, loaded: true, }); }) .done(); } render () { if (!this.state.loaded) { return (<View> <Text>Loading!</Text> </View>); } else if (this.state.loggedIn) { console.log(this.props.group_info.fields); console.log(this.state); console.log(this.state.group_info[0]); const backButton = { title: "Back", handler: () => this.backOnePage(), }; return ( <ScrollView> <NavigationBar style={{ backgroundColor: "white", }} leftButton={backButton} statusBar={{ tintColor: "white", }} /> <Text style={styles.headTitle}> Group Name: {this.state.group_info.name} </Text> <Text style={styles.headerOtherText}>Group Leader: {this.state.group_info.admin}</Text> <Text style={styles.headerOtherText}>{this.state.group_info.users} people in this group.</Text> </ScrollView> ); } else { this.props.navigator.push({id: "LoginPage", name:"Index"}) } } } var styles = StyleSheet.create({ headerOtherText : { color: 'black', fontSize: 15 , fontWeight: 'normal', fontFamily: 'Helvetica Neue', alignSelf: "center", }, headTitle: { color: 'black', fontSize: 30 , fontWeight: 'normal', fontFamily: 'Helvetica Neue', alignSelf: "center", }, header: { marginTop: 20, flex: 1, flexDirection: "column", justifyContent: "center", alignItems: "center", }, container: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: '#ff7f50', }, rightContainer: { flex: 1, }, title: { fontSize: 20, marginBottom: 8, textAlign: 'center', }, year: { textAlign: 'center', }, thumbnail: { width: 53, height: 81, }, listView: { backgroundColor: '#0000ff', paddingBottom: 200, }, }); module.exports = GroupDetails;
adnanhemani/RideApp
App/GroupDetails.js
JavaScript
mit
3,798
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me cantango_user end
stanislaw/cantango_editor
spec/dummy/app/models/user.rb
Ruby
mit
460
process.stderr.write('Test');
patrick-steele-idem/child-process-promise
test/fixtures/stderr.js
JavaScript
mit
29
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wellspring.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
ushatil/wellness-tracker
ws/manage.py
Python
mit
253
package org.squirrel; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.Timer; import org.squirrel.managers.PrisonerControllor; import org.squirrel.managers.inputManager; import org.squirrel.objects.Player; import org.squirrel.ui.Hud; import org.squirrel.world.World; public class Game extends JPanel implements ActionListener{ private static final long serialVersionUID = -8805039320208612585L; public static String name = JOptionPane.showInputDialog(null,"What is your name?","Welcome to Prison Survival", JOptionPane.QUESTION_MESSAGE); Timer gameLoop; Player player; PrisonerControllor prict; Hud hud; World world1; public Game(){ setFocusable(true); gameLoop = new Timer(10, this); gameLoop.start(); player = new Player(300, 300); prict = new PrisonerControllor(); hud = new Hud(); world1 = new World(); addKeyListener(new inputManager(player)); } public void paint(Graphics g){ super.paint(g); Graphics2D g2d = (Graphics2D) g; //Camera int offsetMaxX = 1600 - 800; int offsetMaxY = 1200 - 600; int offsetMinX = 0; int offsetMinY = 0; int camX = player.getxPos() - 800 /2; int camY = player.getyPos() - 600 /2; //if (camX > offsetMaxX){ // camX = offsetMaxX; //} //else if (camX < offsetMinX){ // camX = offsetMinX; //} //if (camY > offsetMaxY){ // camY = offsetMaxY; //} //else if (camY < offsetMinY){ // camY = offsetMinY; //} g2d.translate(-camX, -camY); // Render everything world1.draw(g2d); hud.draw(g2d); prict.draw(g2d); player.draw(g2d); g.translate(camX, camY); } @Override public void actionPerformed(ActionEvent e) { try { player.update(); hud.update(); prict.update(); world1.update(); repaint(); } catch (Exception e1) { e1.printStackTrace(); } } }
DemSquirrel/Prison-Survival
src/org/squirrel/Game.java
Java
mit
1,974
(function () { 'use strict'; angular .module('app') .service('UploadUserLogoService', UploadUserLogoService); function UploadUserLogoService($http, $log, TokenService, UserService, $rootScope) { this.uploadImage = uploadImage; //// /** * Upload Image * @description For correct uploading we must send FormData object * With 'transformRequest: angular.identity' prevents Angular to do anything on our data (like serializing it). * By setting ‘Content-Type’: undefined, the browser sets the Content-Type to multipart/form-data for us * and fills in the correct boundary. * Manually setting ‘Content-Type’: multipart/form-data will fail to fill in the boundary parameter of the request * All this for correct request typing and uploading * @param formdata * @param callback */ function uploadImage(formdata, callback) { let userToken = TokenService.get(); let request = { method: 'POST', url: '/api/user/avatar', transformRequest: angular.identity, headers: { 'Content-Type': undefined, 'Autorization': userToken }, data: formdata }; let goodResponse = function successCallback(response) { let res = response.data; if (res.success) { let currentUser = UserService.get(); currentUser.avatarUrl = res.data.avatarUrl; UserService.save(currentUser); } if (callback && typeof callback === 'function') { callback(res); } }; let badResponse = function errorCallback(response) { $log.debug('Bad, some problems ', response); if (callback && typeof callback === 'function') { callback(response); } }; $http(request).then(goodResponse, badResponse); } } })();
royalrangers-ck/rr-web-app
app/utils/upload.user.logo/upload.user.logo.service.js
JavaScript
mit
2,187
<?php include 'vendor/autoload.php'; ini_set('error_reporting', E_ALL); ini_set('display_errors', '1'); ini_set('display_startup_errors', '1');
mkosolofski/houseseats-monitor
phpunit_bootstrap.php
PHP
mit
145
class Sprite(object): def __init__(self, xPos, yPos): self.x = xPos self.y = yPos self.th = 32 self.tw = 32 def checkCollision(self, otherSprite): if (self.x < otherSprite.x + otherSprite.tw and otherSprite.x < self.x + self.tw and self.y < otherSprite.y + otherSprite.th and otherSprite.y < self.y + self.th): return True else: return False class Actor(Sprite): def __init__(self, xPos, yPos): super(Actor, self).__init__(xPos, yPos) self.speed = 5 self.dy = 0 self.d = 3 self.dir = "right" # self.newdir = "right" self.state = "standing" self.walkR = [] self.walkL = [] def loadPics(self): self.standing = loadImage("gripe_stand.png") self.falling = loadImage("grfalling.png") for i in range(8): imageName = "gr" + str(i) + ".png" self.walkR.append(loadImage(imageName)) for i in range(8): imageName = "gl" + str(i) + ".png" self.walkL.append(loadImage(imageName)) def checkWall(self, wall): if wall.state == "hidden": if (self.x >= wall.x - self.d and (self.x + 32 <= wall.x + 32 + self.d)): return False def move(self): if self.dir == "right": if self.state == "walking": self.im = self.walkR[frameCount % 8] self.dx = self.speed elif self.state == "standing": self.im = self.standing self.dx = 0 elif self.state == "falling": self.im = self.falling self.dx = 0 self.dy = 5 elif self.dir == "left": if self.state == "walking": self.im = self.walkL[frameCount % 8] self.dx = -self.speed elif self.state == "standing": self.im = self.standing self.dx = 0 elif self.state == "falling": self.im = self.falling self.dx = 0 self.dy = 5 else: self.dx = 0 self.x += self.dx self.y += self.dy if self.x <= 0: self.x = 0 if self.x >= 640 - self.tw: self.x = 640 -self.tw def display(self): image(self.im, self.x, self.y) class Block(Sprite): def __init__(self, xPos, yPos): super(Block, self).__init__(xPos, yPos) self.state = "visible" def loadPics(self): self.im = loadImage("block.png") def display(self): if self.state == "visible": image(self.im, self.x, self.y)
kantel/processingpy
sketches/Apple_Invaders/sprites.py
Python
mit
2,805
<?php /** * This file is part of the Carrot framework. * * Copyright (c) 2011 Ricky Christie <seven.rchristie@gmail.com>. * * Licensed under the MIT License. * */ /** * Docs storage. * * Represents a documents storage and provides ways to access * the documents inside the storage. This class reads folders and * .html files inside a directory and creates a hierarchical docs * structure from it. * * @author Ricky Christie <seven.rchristie@gmail.com> * @license http://www.opensource.org/licenses/mit-license.php MIT License * */ namespace Carrot\Docs; use Exception, InvalidArgumentException, DirectoryIterator; class Storage { /** * @var string The directory that contains the document files, * without trailing directory separator. */ protected $rootDirectory; /** * Constructor. * * If no path was given, the root directory will default to: * * <code> * __DIR__ . DIRECTORY_SEPARATOR . 'Files' * </code> * * The directory contains documentation files in HTML format and * can contain as many folders as you need. You can provide * 'section.html' file on each directory to be loaded when that * section is requested. * * @param string $rootDirectory The directory that contains the * document files. * */ public function __construct($rootDirectory = NULL) { if ($rootDirectory == NULL) { $rootDirectory = __DIR__ . DIRECTORY_SEPARATOR . 'Files'; } $this->setRootDirectory($rootDirectory); } /** * Set the directory that contains the document files. * * @throws InvalidArgumentException If the root directory given * is not a valid path or it's not a directory. * @param string $rootDirectory The directory that contains the * document files. * */ protected function setRootDirectory($rootDirectory) { $rootDirectoryAbsolute = realpath($rootDirectory); if ($rootDirectoryAbsolute == FALSE) { throw new InvalidArgumentException("Storage error in instantiation. The given path '{$rootDirectory}' does not exist."); } if (is_dir($rootDirectoryAbsolute) == FALSE) { throw new InvalidArgumentException("Storage error in instantiation. The given path '{$rootDirectory}' is not directory."); } $this->rootDirectory = $rootDirectoryAbsolute; } /** * Get an instance of page from the given hierarchical path. * * The path array contains the hierarchical path to the * documentation. The array contains item IDs. Example: * * <code> * $path = array( * '1-introduction', * '1-calculator-tutorial', * '1-creating-your-controller' * ); * </code> * * @param array $pagePathArray The hierarchical path to the * documentation page to retrieve. * @return Page|FALSE The documentation page, or FALSE if failed. * */ public function getPage(array $pagePathArray) { if (empty($pagePathArray)) { return $this->getIndexPage(); } $pageInfo = $this->getPageInfo($pagePathArray); if (!is_array($pageInfo)) { return FALSE; } return new Page( $pageInfo['title'], $pageInfo['content'], $pageInfo['parentSections'], $pageInfo['navigation'] ); } /** * Get the page containing the index to be returned. * * Will try to load the contents of the 'section.html' file in * the route, if it fails, will simply return an empty body with * the root navigation. * * @return Page * */ public function getIndexPage() { $parentSections = array(); $navigation = $this->getNavigationItemsFromDirectory($this->rootDirectory, array()); $title = ''; $content = $this->getSectionIndexContent($this->rootDirectory); return new Page( $title, $content, $parentSections, $navigation ); } /** * Get information about the page from the given hierarchical * path. * * Assumes the array is not empty. The structure of the array * returned is as follows: * * <code> * $pageInfo = array( * 'parentSections' => $parentSections, * 'navigation' => $navigation, * 'title' => $title, * 'content' => $content * ); * </code> * * The array $parentSections contains the page's parent sections. * Each section is represented by a {@see NavigationItem} * instance: * * <code> * $parentSections = array( * 0 => $sectionA, * 1 => $sectionB, * 2 => $sectionC * ... * ); * </code> * * The array $navigation contains the list of accessible items * for the current open section, be it a page or another section, * but with the item ID as the indexes: * * <code> * $navigation = array( * '1-introduction' => $navItemA, * '2-autoloading' => $navItemB, * '3-dependency-injection' => $navItemC, * ... * ); * </code> * * @param array $pagePathArray The hierarchical path to the * documentation page to retrieve. * */ protected function getPageInfo(array $pagePathArray) { $parentSections = array(); $navigation = array(); $title = ''; $content = ''; $directory = $this->rootDirectory; $segmentsTraversed = array(); $highestLevel = count($pagePathArray) - 1; foreach ($pagePathArray as $level => $itemID) { $isHighestLevel = ($level == $highestLevel); $availableItems = $this->getNavigationItemsFromDirectory( $directory, $segmentsTraversed ); if (!array_key_exists($itemID, $availableItems)) { return FALSE; } $navItem = $availableItems[$itemID]; if ($isHighestLevel) { if ($navItem->isSection()) { $parentSections[] = $navItem; $segmentsTraversed[] = $itemID; $directory = $navItem->getRealPath(); $navigation = $this->getNavigationItemsFromDirectory( $directory, $segmentsTraversed ); $content = $this->getSectionIndexContent($directory); } else { $navigation = $availableItems; $navigation[$itemID]->markAsCurrent(); $content = $this->getFileContent($navItem->getRealPath()); } return array( 'parentSections' => $parentSections, 'navigation' => $navigation, 'title' => $navItem->getTitle(), 'content' => $content ); } $parentSections[] = $navItem; $segmentsTraversed[] = $itemID; $directory = $navItem->getRealPath(); } } /** * Get the list of navigational items from the given directory. * * Iterates through the given directory and creates instances of * {@see NavigationItem} from its contents. Uses the given root * path segments to construct routing argument arrays of each * NavigationItem instance. * * The root path segments array structure: * * <code> * $rootPathSegments = array( * '1-Introduction', * '1-Calculator-Tutorial' * ); * </code> * * Returns an array containing instances of NavigationItem: * * <code> * $navigationItems = array( * $navItemA, * $navItemB, * $navItemC, * ... * ); * </code> * * @param string $directory Absolute path to the directory to * search the files from. * @param array $rootPathSegments The root path segments leading * to the given directory, to be used in constructing * routing arguments on each NavigationItem instances. * @return array Array containing instances of * {@see NavigationItem}. Returns an empty array if it * fails to retrieve data from the directory. * */ protected function getNavigationItemsFromDirectory($directory, array $rootPathSegments) { $items = array(); try { $iterator = new DirectoryIterator($directory); } catch (Exception $exception) { return $items; } foreach ($iterator as $key => $content) { $navItem = NULL; if ($content->isFile()) { $fileName = $content->getFilename(); $realPath = $content->getPathname(); $navItem = $this->getNavigationItemFromFile( $fileName, $realPath, $rootPathSegments ); } if ($content->isDir() AND $content->isDot() == FALSE) { $fileName = $content->getFilename(); $realPath = $content->getPathname(); $navItem = $this->getNavigationItemFromDirectory( $fileName, $realPath, $rootPathSegments ); } if ($navItem instanceof NavigationItem) { $items[$navItem->getItemID()] = $navItem; } } return $items; } /** * Get a {@see NavigationItem} instance from the given file name * and file path. * * Only accepts '.html' files with the following pattern as the * file name: * * <code> * 1. File Name.html * A. File Name.html * a. File Name.html * </code> * * @see getNavigationItemsFromDirectory() * @param string $fileName The name of the file. * @param string $realPath The real path to the file. * @param array $rootPathSegments The root path segments leading * to the given file, to be used in constructing routing * arguments array. * @return NavigationItem * */ protected function getNavigationItemFromFile($fileName, $realPath, array $rootPathSegments) { $fileNamePattern = '/^([A-Za-z0-9]+\\. (.+))\.html$/uD'; $replaceDotAndSpacesPattern = '/[\\. ]+/u'; if (preg_match($fileNamePattern, $fileName, $matches)) { $title = $matches[2]; $itemID = preg_replace($replaceDotAndSpacesPattern, '-', $matches[1]); $routingArgs = $rootPathSegments; $routingArgs[] = $itemID; return new NavigationItem( $title, 'doc', $routingArgs, $realPath ); } } /** * Get a {@see NavigationItem} instance from the given directory. * * All directory names are accepted. * * @see getNavigationItemsFromDirectory() * @param string $fileName The name of the file. * @param string $realPath The real path to the file. * @param array $rootPathSegments The root path segments leading * to the given file, to be used in constructing routing * arguments array. * @return NavigationItem * */ protected function getNavigationItemFromDirectory($directoryName, $realPath, array $rootPathSegments) { $directoryPattern = '/^([A-Za-z0-9]+\\. (.+))$/uD'; $replaceDotAndSpacesPattern = '/[\\. ]+/u'; if (preg_match($directoryPattern, $directoryName, $matches)) { $title = $matches[2]; $itemID = preg_replace($replaceDotAndSpacesPattern, '-', $matches[1]); $routingArgs = $rootPathSegments; $routingArgs[] = $itemID; return new NavigationItem( $title, 'section', $routingArgs, $realPath ); } } /** * Get the content for section index. * * Will try to get an 'section.html' file on the given directory. * If none found, an empty string will be returned instead. * * @param string $directory The physical counterpart of the * section whose index content we wanted to get, without * trailing directory separator. * @return string * */ protected function getSectionIndexContent($directory) { $filePath = $directory . DIRECTORY_SEPARATOR . 'section.html'; return $this->getFilecontent($filePath); } /** * Get the content from the give file. * * If the file doesn't exist, will return an empty string * instead. * * @param string $filePath Path to the file to get. * */ protected function getFileContent($filePath) { if (!file_exists($filePath)) { return ''; } return file_get_contents($filePath); } }
rickchristie/carrot-old
library/Carrot/Docs/Storage.php
PHP
mit
13,874
class CreateTeams < ActiveRecord::Migration def self.up create_table :teams do |t| t.string :name t.string :abbreviation t.string :hometown t.timestamps end end def self.down drop_table :teams end end
wndxlori/wndx-multiselect
spec/rails2/app_root/db/migrate.notnow/001_create_teams.rb
Ruby
mit
246
angular.module('tips.tips').controller('TipsController', ['$scope', '$routeParams', '$location', 'Global', 'Tips', function ($scope, $routeParams, $location, Global, Tips) { $scope.global = Global; $scope.createTip = function () { var tips = new Tips({ text: this.text, likes: this.likes, category: this.category }); tips.$save(function (response) { $location.path("/"); }); this.title = ""; }; $scope.showTip = function () { Tips.query(function (tips) { $scope.tips = tips; tips.linkEdit = 'tips/edit/'; // show tips size function Settings (minLikes, maxLikes) { var that = this; that.size = { min: 26, max: 300 }; that.maxLikes = maxLikes; that.minLikes = tips[0].likes; that.valueOfdivision = (function(){ return (that.size.max - that.size.min)/that.maxLikes })() } function startIsotope(){ var el = $('#isotope-container'); el.isotope({ itemSelector: '.isotope-element', layoutMode: 'fitRows', sortBy: 'number', sortAscending: true, }); return el; } var maxLikes = 0; var minLikes = 0; for (var i = 0; i < tips.length; i++) { if(maxLikes <= tips[i].likes)maxLikes = tips[i].likes; if(minLikes >= tips[i].likes)minLikes = tips[i].likes; }; tips.settingsView = new Settings(minLikes, maxLikes); $scope.$watch('tips', function () { $scope.$evalAsync(function () { var isotope = startIsotope(); }); }) }); }; $scope.updateTip = function (tip) { var tip = new Tips(tip); tip.$update(tip, function(){ console.log("update updateTip: ", tip._id); }, function(){ console.warn("error updateTip:", tip._id); }); }; $scope.getTip = function () { Tips.query(function (tip) { $scope.tip = tip; console.log(tip); }); }; $scope.editTip = function(tip){ console.log("edit tip"); }; }])
Arsey/tips-of-the-day
public/js/controllers/tips.js
JavaScript
mit
2,505
package com.xeiam.xchange.cryptotrade.dto; import java.io.IOException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.xeiam.xchange.cryptotrade.dto.CryptoTradeOrderType.CryptTradeOrderTypeDeserializer; @JsonDeserialize(using = CryptTradeOrderTypeDeserializer.class) public enum CryptoTradeOrderType { Buy, Sell; static class CryptTradeOrderTypeDeserializer extends JsonDeserializer<CryptoTradeOrderType> { @Override public CryptoTradeOrderType deserialize(final JsonParser jsonParser, final DeserializationContext ctxt) throws IOException, JsonProcessingException { final ObjectCodec oc = jsonParser.getCodec(); final JsonNode node = oc.readTree(jsonParser); final String orderType = node.asText(); return CryptoTradeOrderType.valueOf(orderType); } } }
Achterhoeker/XChange
xchange-cryptotrade/src/main/java/com/xeiam/xchange/cryptotrade/dto/CryptoTradeOrderType.java
Java
mit
1,150
module Mailplug class Plugin::Example < Mailplug::Middleware # Message Envelope Methods def return_path end def recipients end def message # returns Mail::Message end # Hash of state and inter-stack data memo[classname][key]=value def memo end # SMTP State Changes def open(remote_ip) end def helo(server_name) end def mail_from(email) end def rcpt_to(email) end def data end def data_line(line) end def data_stop end def save # false(i don't queue), true (i queued), error msg end def quit end def close end def header(name, value) end def abort(code, msg) # Stop it with reason end def continue # don't stop end def log(msg) end def status(number, message, close, waitseconds=0) end # SMTP Responses http://www.greenend.org.uk/r def service_ready # 220 end end end
afair/mailplug
lib/mailplug/plugin/example.rb
Ruby
mit
969
import apiConfig from './MovieDBConfig'; import TmdbApi from 'moviedb-api'; var api = new TmdbApi({ consume: false, apiKey: apiConfig.apiKey }); const makeAndList = (list) => { return list.map(item => item.value).join(); }; export const getGenres = (input='', callback) => { api.request('/genre/movie/list', 'GET') .then(res => { return res.genres.map(item => { return {label: item.name, value: item.id}; }) }) .then(json => callback(null, {options: json, complete: false})) .catch(err => console.log(err)); }; export const getKeywords = (input='', callback) => { api.request('/search/keyword', 'GET', {query: input}) .then(res => { return res.results.map(item => { return {label: item.name, value: item.id}; }); }) .then(json => callback(null, {options: json, complete: false})) .catch(err => console.log(err)); }; export const getActors = (input='', callback) => { api.request('/search/person', 'GET', {query: input}) .then(res => { return res.results.map(item => { return {label: item.name, value: item.id}; }); }) .then(json => callback(null, {options: json, complete: false})) .catch(err => console.log(err)); }; export const discover = (genres=null, keywords=null, actors, minYear, maxYear, page=1) => { let g = genres ? makeAndList(genres) : null; let k = keywords ? makeAndList(keywords) : null; let a = actors ? makeAndList(actors) : null; return api.request('/discover/movie', 'GET', { with_genres: g, with_keywords: k, with_cast: a, "release_date.gte": minYear, "release_date.lte": maxYear, page }) .then(res => res) }; export const getVideos = (id, language='en') => { return api.request(`/movie/${id}/videos`, 'GET', {language}) }; export const getMovieKeywords = (id, language='en') => { return api.request(`/movie/${id}/keywords`, 'GET', {language}) }; export const discoverWithVideo = (genres=null, keywords=null, actors, minYear, maxYear) => { return discover(genres, keywords, actors, minYear, maxYear) .then(res => { return Promise.all( res.results.map(item => getVideos(item.id) .then(videos => videos.results[0]) ) ).then(list => { return { ...res, results: res.results.map((item, index) => { item.youtube = list[index]; return item; }) } }) }) }; export const getDetails = (id, language='en') => { return api.request(`/movie/${id}`, 'GET', {language, append_to_response: "keywords,videos"}) };
arddor/MovieAdvisor
app/utils/api.js
JavaScript
mit
2,618
const excludedTables = ["blacklist", "musicCache", "timedEvents"]; const statPoster = require("../../modules/statPoster.js"); module.exports = async guild => { let tables = await r.tableList().run(); for(let table of tables) { let indexes = await r.table(table).indexList().run(); if(~indexes.indexOf("guildID")) r.table(table).getAll(guild.id, { index: "guildID" }).delete().run(); else r.table(table).filter({ guildID: guild.id }).delete().run(); } if(bot.config.bot.serverChannel) { let owner = bot.users.get(guild.ownerID); let botCount = guild.members.filter(member => member.bot).length; let botPercent = ((botCount / guild.memberCount) * 100).toFixed(2); let userCount = guild.memberCount - botCount; let userPercent = ((userCount / guild.memberCount) * 100).toFixed(2); let content = "❌ LEFT GUILD ❌\n"; content += `Guild: ${guild.name} (${guild.id})\n`; content += `Owner: ${owner.username}#${owner.discriminator} (${owner.id})\n`; content += `Members: ${guild.memberCount} **|** `; content += `Users: ${userCount} (${userPercent}%) **|** `; content += `Bots: ${botCount} (${botPercent}%)`; try { await bot.createMessage(bot.config.bot.serverChannel, content); } catch(err) { console.error(`Failed to send message to server log: ${err.message}`); } } statPoster(); };
minemidnight/oxyl
src/bot/listeners/on/guildDelete.js
JavaScript
mit
1,331
using System.Collections.Generic; using System.IO; using System.Reflection; using IDI.Core.Common.Extensions; namespace IDI.Core.Localization { public abstract class Package { public List<PackageItem> Items { get; private set; } = new List<PackageItem>(); public Package(string assemblyName, string packageName) { var assembly = Assembly.Load(new AssemblyName(assemblyName)); if (assembly == null) return; using (Stream stream = assembly.GetManifestResourceStream(packageName)) { if (stream == null) return; using (StreamReader reader = new StreamReader(stream)) { string json = reader.ReadToEnd(); this.Items = json.To<List<PackageItem>>(); } } } } }
idi-studio/com.idi.central.api
src/IDI.Core/Localization/Package.cs
C#
mit
905
import { computed, get } from '@ember/object'; import { getOwner } from '@ember/application'; import { deprecate } from '@ember/debug'; export function ability(abilityName, resourceName) { deprecate( 'Using ability() computed property is deprecated. Use getters and Can service directly.', false, { for: 'ember-can', since: { enabled: '4.0.0', }, id: 'ember-can.deprecate-ability-computed', until: '5.0.0', } ); resourceName = resourceName || abilityName; return computed(resourceName, function () { let canService = getOwner(this).lookup('service:abilities'); return canService.abilityFor(abilityName, get(this, resourceName)); }).readOnly(); }
minutebase/ember-can
addon/computed.js
JavaScript
mit
721
/* global requirejs, require */ /*jslint node: true */ 'use strict'; import Ember from 'ember'; import _keys from 'lodash/object/keys'; /* This function looks through all files that have been loaded by Ember CLI and finds the ones under /mirage/[factories, fixtures, scenarios, models]/, and exports a hash containing the names of the files as keys and the data as values. */ export default function(prefix) { let modules = ['factories', 'fixtures', 'scenarios', 'models', 'serializers']; let mirageModuleRegExp = new RegExp(`^${prefix}/mirage/(${modules.join("|")})`); let modulesMap = modules.reduce((memo, name) => { memo[name] = {}; return memo; }, {}); _keys(requirejs.entries).filter(function(key) { return mirageModuleRegExp.test(key); }).forEach(function(moduleName) { if (moduleName.match('.jshint')) { // ignore autogenerated .jshint files return; } let moduleParts = moduleName.split('/'); let moduleType = moduleParts[moduleParts.length - 2]; let moduleKey = moduleParts[moduleParts.length - 1]; Ember.assert('Subdirectories under ' + moduleType + ' are not supported', moduleParts[moduleParts.length - 3] === 'mirage'); if (moduleType === 'scenario'){ Ember.assert('Only scenario/default.js is supported at this time.', moduleKey !== 'default'); } let module = require(moduleName, null, null, true); if (!module) { throw new Error(moduleName + ' must export a ' + moduleType); } let data = module['default']; modulesMap[moduleType][moduleKey] = data; }); return modulesMap; }
ballPointPenguin/ember-cli-mirage
addon/utils/read-modules.js
JavaScript
mit
1,627
<?php /** * @author tshirtecommerce - www.tshirtecommerce.com * @date: 2015-01-10 * * @copyright Copyright (C) 2015 tshirtecommerce.com. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE * */ if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> <script src="<?php echo base_url('assets/plugins/jquery-fancybox/jquery.fancybox.js'); ?>" type="text/javascript"></script> <script src="<?php echo base_url('assets/plugins/validate/validate.js'); ?>" type="text/javascript"></script> <link href="<?php echo base_url('assets/plugins/jquery-fancybox/jquery.fancybox.css'); ?>" rel="stylesheet"/> <form name="setting" class="setting-save" method="POST" action="<?php echo site_url('m_product/admin/setting/save/'.$id); ?>"> <div class="tabpanel" role="tabpanel"> <!-- Nav tabs --> <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#tab-general" aria-controls="tab-general" role="tab" data-toggle="tab"><?php echo lang('general');?></a></li> <li role="presentation"><a href="#tab-design" aria-controls="tab-design" role="tab" data-toggle="tab"><?php echo lang('design_options'); ?></a></li> <li class="button-back pull-right"><a href="javascript:void(0)" onclick="grid.module.setting('m_product')" title="Back to list"><i class="clip-arrow-left-2"></i></a></li> </ul> <!-- Tab panes --> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="tab-general"> <div class="form-group"> <label><?php echo lang('title');?><span class="symbol required"></span></label> <input type="text" class="form-control input-sm validate required" name="title" placeholder="<?php echo lang('title');?>" value="<?php echo $m_product->title; ?>" data-minlength="2" data-maxlength="200" data-msg="<?php echo lang('m_product_admin_setting_title_validate');?>"> </div> <?php $options = json_decode($m_product->options); ?> <div class="form-group"> <div class="row"> <div class="col-sm-6"> <label><?php echo lang('m_product_admin_setting_show_title');?></label> <?php $show_title = array( 'yes'=>lang('yes'), 'no'=>lang('no'), ); if(isset($options->show_title)) $default = $options->show_title; else $default = ''; echo form_dropdown('options[show_title]', $show_title, $default, 'class="form-control input-sm"'); ?> </div> <div class="col-sm-6"> <label><?php echo lang('m_product_admin_setting_count_cols_title');?></label> <?php $cols = array( '1'=>1, '2'=>2, '3'=>3, '4'=>4, '6'=>6, ); if(isset($options->cols)) $default = $options->cols; else $default = ''; echo form_dropdown('options[cols]', $cols, $default, 'class="form-control input-sm"'); ?> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-sm-6"> <label><?php echo lang('m_product_admin_setting_show_product_title');?></label> <?php $show_product = array( 'lastest'=>lang('m_product_admin_setting_lastest_title'), 'future'=>lang('m_product_admin_setting_future_title'), 'sale_price'=>lang('m_product_admin_setting_sale_title'), ); if(isset($options->show_product)) $default = $options->show_product; else $default = ''; echo form_dropdown('options[show_product]', $show_product, $default, 'class="form-control input-sm"'); ?> </div> <div class="col-sm-6"> <label><?php echo lang('m_product_admin_setting_count_product_title');?></label> <input type="text" name="options[count]" class="form-control input-sm" value="<?php if(isset($options->count) && $options->count != '') echo $options->count; else echo 8; ?>" placeholder="<?php echo lang('m_product_admin_setting_count_product_title');?>"/> </div> </div> </div> </div> <!-- design options --> <?php $params = json_decode($m_product->params, true); ?> <div role="tabpanel" class="tab-pane" id="tab-design"> <div class="design-box"> <div class="design-box-left"> <div class="box-css"> <label><?php echo lang('css');?></label> <div class="box-margin"> <label><?php echo lang('margin');?></label> <input type="text" class="box-input" name="params[margin][left]" value="<?php echo setParams($params, 'margin', 'left'); ?>" id="margin-left"> <input type="text" class="box-input" name="params[margin][right]" value="<?php echo setParams($params, 'margin', 'right'); ?>" id="margin-right"> <input type="text" class="box-input" name="params[margin][top]" value="<?php echo setParams($params, 'margin', 'top'); ?>" id="margin-top"> <input type="text" class="box-input" name="params[margin][bottom]" value="<?php echo setParams($params, 'margin', 'bottom'); ?>" id="margin-bottom"> <div class="box-border"> <label><?php echo lang('border');?></label> <input type="text" class="box-input" name="params[border][left]" value="<?php echo setParams($params, 'border', 'left'); ?>" id="border-left"> <input type="text" class="box-input" name="params[border][right]" value="<?php echo setParams($params, 'border', 'right'); ?>" id="border-right"> <input type="text" class="box-input" name="params[border][top]" value="<?php echo setParams($params, 'border', 'top'); ?>" id="border-top"> <input type="text" class="box-input" name="params[border][bottom]" value="<?php echo setParams($params, 'border', 'bottom'); ?>" id="border-bottom"> <div class="box-padding"> <label><?php echo lang('padding');?></label> <input type="text" class="box-input" name="params[padding][left]" value="<?php echo setParams($params, 'padding', 'left'); ?>" id="padding-left"> <input type="text" class="box-input" name="params[padding][right]" value="<?php echo setParams($params, 'padding', 'right'); ?>" id="padding-right"> <input type="text" class="box-input" name="params[padding][top]" value="<?php echo setParams($params, 'padding', 'top'); ?>" id="padding-top"> <input type="text" class="box-input" name="params[padding][bottom]" value="<?php echo setParams($params, 'padding', 'bottom'); ?>" id="padding-bottom"> <div class="box-elment"> </div> </div> </div> </div> </div> </div> <div class="design-box-right"> <label><?php echo lang('border');?></label> <div class="row col-md-12"> <div class="form-group pick-color"> <div class="input-group"> <input type="text" class="form-control color input-sm" name="params[borderColor]" value="<?php echo setParams($params, 'borderColor'); ?>"> <div class="input-group-addon pick-color-btn"><?php echo lang('select_color');?></div> </div> <a href="#" class="btn btn-default btn-sm pick-color-clear"><?php echo lang('clear');?></a> </div> </div> <div class="row col-md-12"> <div class="form-group"> <?php $options = array('Defaults', 'Solid','Dotted','Dashed','None','Hidden','Double','Groove','Ridge','Inset','Outset','Initial','Inherit'); ?> <select class="form-control input-sm" name="params[borderStyle]"> <?php for($i=0; $i<12; $i++){ ?> <?php $border_style = setParams($params, 'borderStyle'); if($border_style == $options[$i]) $check = 'selected="selected"'; else $check = ''; ?> <option value="<?php echo $options[$i]; ?>" <?php echo $check;?>><?php echo $options[$i]; ?></option> <?php } ?> </select> </div> </div> <label><?php echo lang('background');?></label> <div class="row col-md-12"> <div class="form-group pick-color"> <div class="input-group"> <input type="text" class="form-control color input-sm" name="params[background][color]" value="<?php echo setParams($params, 'background', 'color'); ?>"> <div class="input-group-addon pick-color-btn"><?php echo lang('select_color');?></div> </div> <a href="#" class="btn btn-default btn-sm pick-color-clear"><?php echo lang('clear');?></a> </div> </div> <div class="row col-md-12"> <div class="form-group"> <?php $image = setParams($params, 'background', 'image'); if($image != '') { echo '<div id="gird-box-bg" style="display:inline;">'; echo '<img src="'.base_url($image).'" class="pull-left box-image" style="width: 80px;" alt="" width="100" />'; }else { echo '<div id="gird-box-bg" style="display:none;">'; } ?> <a href="javascript:void(0)" class="gird-box-bg-remove" onclick="gridRemoveImg(this)"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></a> </div> <input type="hidden" name="params[background][image]" id="gird-box-bg-img" value="<?php echo $image; ?>"> <a class="gird-box-image" href="javascript:void(0)" onclick="jQuery.fancybox( {href : '<?php echo site_url().'admin/media/modals/productImg/1'; ?>', type: 'iframe'} );"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span></a> </div> </div> <div class="row col-md-12"> <div class="form-group"> <?php $options = array('Defaults','Repeat','No repeat'); ?> <select class="form-control input-sm" name="params[background][style]"> <?php for($i=0; $i<3; $i++){ ?> <?php $background_style = setParams($params, 'background', 'style'); if($background_style == $options[$i]) $check = 'selected="selected"'; else $check = ''; ?> <option value="<?php echo $options[$i]; ?>" <?php echo $check; ?>><?php echo $options[$i]; ?></option> <?php } ?> </select> </div> </div> </div> </div> </div> </div> </div> </form> <script type="text/javascript"> function productImg(images) { if(images.length > 0) { var e = jQuery('#gird-box-bg'); if(e.children('img').length > 0) e.children('img').attr('src', images[0]); else e.append('<img src="'+images[0]+'" class="pull-left box-image" style="width: 80px;" alt="" width="100" />'); e.css('display', 'inline'); var str = images[0]; str = str.replace("<?php echo base_url();?>", ""); jQuery('#gird-box-bg-img').val(str); jQuery.fancybox.close(); } } function gridRemoveImg(e){ var e = jQuery('#gird-box-bg'); e.children('img').remove(); e.css('display', 'none'); jQuery('#gird-box-bg-img').val(''); } </script>
Nnamso/tbox
application/modules/m_product/views/admin/setting.php
PHP
mit
11,129
package com.github.aureliano.evtbridge.output.file; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.Set; import org.junit.Test; import com.github.aureliano.evtbridge.annotation.validation.NotNull; import com.github.aureliano.evtbridge.annotation.validation.apply.ConstraintViolation; import com.github.aureliano.evtbridge.annotation.validation.apply.ObjectValidator; import com.github.aureliano.evtbridge.core.config.OutputConfigTypes; public class FileOutputConfigTest { ObjectValidator validator = ObjectValidator.instance(); @Test public void testGetDefaults() { FileOutputConfig c = new FileOutputConfig(); assertNull(c.getFile()); assertEquals("UTF-8", c.getEncoding()); assertFalse(c.isAppend()); assertTrue(c.isUseBuffer()); } @Test public void testConfiguration() { FileOutputConfig c = new FileOutputConfig() .withAppend(true) .withEncoding("ISO-8859-1") .withFile("/there/is/not/file"); assertEquals("/there/is/not/file", c.getFile().getPath()); assertEquals("ISO-8859-1", c.getEncoding()); assertTrue(c.isAppend()); } @Test public void testClone() { FileOutputConfig c1 = new FileOutputConfig() .withAppend(true) .withUseBuffer(false) .withEncoding("ISO-8859-1") .withFile("/there/is/not/file") .putMetadata("test", "my test"); FileOutputConfig c2 = c1.clone(); assertEquals(c1.getFile(), c2.getFile()); assertEquals(c1.getEncoding(), c2.getEncoding()); assertEquals(c1.isAppend(), c2.isAppend()); assertEquals(c1.isUseBuffer(), c2.isUseBuffer()); assertEquals(c1.getMetadata("test"), c2.getMetadata("test")); } @Test public void testOutputType() { assertEquals(OutputConfigTypes.FILE_OUTPUT.name(), new FileOutputConfig().id()); } @Test public void testValidation() { FileOutputConfig c = this.createValidConfiguration(); assertTrue(this.validator.validate(c).isEmpty()); this._testValidateFile(); } private void _testValidateFile() { FileOutputConfig c = new FileOutputConfig(); Set<ConstraintViolation> violations = this.validator.validate(c); assertTrue(violations.size() == 1); assertEquals(NotNull.class, violations.iterator().next().getValidator()); } private FileOutputConfig createValidConfiguration() { return new FileOutputConfig().withFile("/path/to/file"); } }
aureliano/da-mihi-logs
evt-bridge-output/file-output/src/test/java/com/github/aureliano/evtbridge/output/file/FileOutputConfigTest.java
Java
mit
2,450
// THIS CODE IS MACHINE-GENERATED, DO NOT EDIT! package fallk.jfunktion; /** * Represents a predicate (boolean-valued function) of a {@code float}-valued and a generic argument. * This is the primitive type specialization of * {@link java.util.function.BiPredicate} for {@code float}/{@code char}. * * @see java.util.function.BiPredicate */ @FunctionalInterface public interface FloatObjectPredicate<E> { /** * Evaluates this predicate on the given arguments. * * @param v1 the {@code float} argument * @param v2 the generic argument * @return {@code true} if the input arguments match the predicate, * otherwise {@code false} */ boolean apply(float v1, E v2); }
fallk/JFunktion
src/main/java/fallk/jfunktion/FloatObjectPredicate.java
Java
mit
715
console.log("VS: loading content_script.js..." + new Date()); // Check if the communication between page and background.js has broken. var last_message_time = new Date().getTime(); new Promise((resolve) => setTimeout(resolve, 1000000)).then(() => { var now = new Date().getTime(); if (now - last_message_time > 500000) { sendAlert('Not having message from background for at least 500s, force reloading'); reloadPage(); } }); chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { // Update timestamp first. last_message_time = new Date().getTime(); console.log("VS: received data from content_script.js" + new Date()); console.log(request); var action = request["action"]; takeAction(action, request); }); var already_logging_in = false; function takeAction(action, request) { var url = window.location.href; console.log("VS: Taking action: " + action + " in " + url); if (action === ACTION_FOR_HOMEPAGE) { homePage(request); } else if (action === ACTION_FOR_LOGIN_PAGE) { loginPage(request); } else if (action === ACTION_FOR_ASYNC_LOGIN) { loginPage(request); } else if (action === ACTION_FOR_DASHBOARD_PAGE) { dashboardPage(request); } else { // Other cases. console.log("VS: unknown action:" + new Date()); console.log(action); return; } } function dashboardPage(request) { console.log("VS: In dashboard page" + new Date()); //var val = $('[data-reactid=".0.0.3.0.0.0.0.0.1.0.0.1.0"]'); //if (val) { // var ts = new Date().getTime(); // var amount = val.text(); // if (!amount) { // console.log("Failed to parse data from html page. " + new Date()); // } else { // saveGenerationData({'amount': amount, 'time': ts}); // } //} else { // sendAlert('Failed to read data from Dashboard page' + window.location.href); //} //console.log("VS: setting to reload page in 60s: " + new Date()); //window.setInterval(function() { console.log("VS: polling account data" + new Date()); $.ajax({url: "/api/fusion/accounts"}).done(function(msg) { console.log("VS: got account data" + new Date()); var j = msg; if (typeof(j) === "object" && 'accounts' in j) { console.log(j['accounts']); var acct = j['accounts'][0]['account_no']; var newUrl = '/api/fusion/accounts/' + acct; console.log("VS: polling account detail data" + new Date()); $.ajax({url: newUrl}).done(function(msg) { console.log("VS: got account detail data" + new Date()); var j = msg; if (typeof(j) === "object" && 'energyToday' in j) { var ts = new Date().getTime(); var amount = j['energyToday'] / 1000.0; console.log("VS: saveing energy data" + new Date()); saveGenerationData({'time': ts, 'amount': amount}); return; } sendAlert("Failed parse detailed account info from AJAX for: " + textStatus); reloadPage(); }).fail(function(jqXHR, textStatus) { sendAlert("Request failed for loading detailed account info from AJAX for: " + textStatus); reloadPage(); }); return; } sendAlert('Failed to parse account data'); reloadPage(); }).fail(function(jqXHR, textStatus) { sendAlert("Request failed for loading accounts AJAX for: " + textStatus); reloadPage(); }); //}, 60000); } function loginPage(request) { if (request) { asyncLogin(request); } else { chrome.runtime.sendMessage({"action": ACTION_FOR_ASYNC_LOGIN}); } } function homePage(request) { var links = $('A'); for (var i in links) { var link = links[i]; if (link.href == LOGIN_PAGE) { link.click(); } } } function asyncLogin(request) { if (already_logging_in) { console.log("VS: already logging in. This is possible, ignoring.." + new Date()); return; } already_logging_in = true; console.log("VS: gettting new data to login" + new Date()); console.log(request); context = request['data']; if ($("INPUT[data-reactid='.0.0.0.0.0.1.1']").val(context.username).length > 0 && $("INPUT[data-reactid='.0.0.0.0.0.2.0']").val(context.passwd).length > 0) { $("BUTTON[data-reactid='.0.0.0.0.0.4.0']").click(); new Promise((resolve) => setTimeout(resolve, 100000)).then(() => { sendAlert('Login failed for username' + context.username + ' and passwd: ' + context.passwd); }); } $('.email-input.js-initial-focus').val(context.username); $('.js-password-field').val(context.passwd); new Promise((resolve) => setTimeout(resolve, 1500)).then(() => { $('button.submit').click(); }); } var action = urlToAction(window.location.href); console.log("VS: intercepted action:" + action + " at " + new Date()); if (action != '') { takeAction(action, null); } console.log("VS: loaded:" + window.location.href); console.log("VS: registered on load event here handler in content_script.js" + new Date());
redisliu/chrome-extensions
vivintsolar-monitor/content_script.js
JavaScript
mit
5,501
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Books extends Model { protected $table = 'books'; protected $fillable = [ 'guid', 'author', 'title', 'description', 'abstract', 'edition', 'publish_date', 'status']; }
krsrk/laravel-5.3-web-app
app/Models/Books.php
PHP
mit
319
namespace gView.Plugins.DbTools.Relates { partial class TableRelationsDialog { /// <summary> /// Erforderliche Designervariable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Verwendete Ressourcen bereinigen. /// </summary> /// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Vom Windows Form-Designer generierter Code /// <summary> /// Erforderliche Methode für die Designerunterstützung. /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. /// </summary> private void InitializeComponent() { this.btnRemove = new System.Windows.Forms.Button(); this.btnEdit = new System.Windows.Forms.Button(); this.btnAdd = new System.Windows.Forms.Button(); this.btnClose = new System.Windows.Forms.Button(); this.lstRelates = new System.Windows.Forms.ListBox(); this.SuspendLayout(); // // btnRemove // this.btnRemove.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnRemove.Enabled = false; this.btnRemove.Location = new System.Drawing.Point(323, 60); this.btnRemove.Name = "btnRemove"; this.btnRemove.Size = new System.Drawing.Size(125, 23); this.btnRemove.TabIndex = 9; this.btnRemove.Text = "Remove"; this.btnRemove.UseVisualStyleBackColor = true; this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click); // // btnEdit // this.btnEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnEdit.Enabled = false; this.btnEdit.Location = new System.Drawing.Point(323, 31); this.btnEdit.Name = "btnEdit"; this.btnEdit.Size = new System.Drawing.Size(125, 23); this.btnEdit.TabIndex = 8; this.btnEdit.Text = "Edit..."; this.btnEdit.UseVisualStyleBackColor = true; this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click); // // btnAdd // this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnAdd.Location = new System.Drawing.Point(323, 2); this.btnAdd.Name = "btnAdd"; this.btnAdd.Size = new System.Drawing.Size(125, 23); this.btnAdd.TabIndex = 7; this.btnAdd.Text = "Add..."; this.btnAdd.UseVisualStyleBackColor = true; this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // btnClose // this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnClose.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnClose.Location = new System.Drawing.Point(323, 180); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(125, 23); this.btnClose.TabIndex = 6; this.btnClose.Text = "Close"; this.btnClose.UseVisualStyleBackColor = true; // // lstRelates // this.lstRelates.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lstRelates.FormattingEnabled = true; this.lstRelates.Location = new System.Drawing.Point(2, 2); this.lstRelates.Name = "lstRelates"; this.lstRelates.Size = new System.Drawing.Size(315, 199); this.lstRelates.TabIndex = 5; this.lstRelates.SelectedIndexChanged += new System.EventHandler(this.lstRelates_SelectedIndexChanged); // // TableRelatesDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(450, 206); this.Controls.Add(this.btnRemove); this.Controls.Add(this.btnEdit); this.Controls.Add(this.btnAdd); this.Controls.Add(this.btnClose); this.Controls.Add(this.lstRelates); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow; this.Name = "TableRelatesDialog"; this.Text = "Relates Dialog"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnRemove; private System.Windows.Forms.Button btnEdit; private System.Windows.Forms.Button btnAdd; private System.Windows.Forms.Button btnClose; private System.Windows.Forms.ListBox lstRelates; } }
jugstalt/gViewGisOS
gView.Plugins.DbTools/Plugins/DbTools/Relates/TableRelationsDialog.Designer.cs
C#
mit
5,681
<?php /* * This file is part of the Schemer package. * * Copyright © 2013 Erin Millard * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Eloquent\Schemer\Constraint; interface SchemaInterface extends ConstraintInterface { }
eloquent/schemer
src/Eloquent/Schemer/Constraint/SchemaInterface.php
PHP
mit
325
namespace QuanLySinhVien_GUI { partial class frmtimkiemdiemsinhvientheomasv { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmtimkiemdiemsinhvientheomasv)); this.btnThoat = new System.Windows.Forms.Button(); this.cmbMaMH = new System.Windows.Forms.ComboBox(); this.dgvKetQua = new System.Windows.Forms.DataGridView(); this.btnTim = new System.Windows.Forms.Button(); this.txtMaSV = new System.Windows.Forms.TextBox(); this.lblMaMH = new System.Windows.Forms.Label(); this.lblMaSV = new System.Windows.Forms.Label(); this.lblTittle = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.dgvKetQua)).BeginInit(); this.SuspendLayout(); // // btnThoat // this.btnThoat.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnThoat.BackgroundImage"))); this.btnThoat.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.btnThoat.Location = new System.Drawing.Point(580, 418); this.btnThoat.Name = "btnThoat"; this.btnThoat.Size = new System.Drawing.Size(72, 30); this.btnThoat.TabIndex = 32; this.btnThoat.Text = " Thoát"; this.btnThoat.UseVisualStyleBackColor = true; // // cmbMaMH // this.cmbMaMH.FormattingEnabled = true; this.cmbMaMH.Location = new System.Drawing.Point(382, 109); this.cmbMaMH.Name = "cmbMaMH"; this.cmbMaMH.Size = new System.Drawing.Size(121, 21); this.cmbMaMH.TabIndex = 31; // // dgvKetQua // this.dgvKetQua.AllowUserToAddRows = false; this.dgvKetQua.AllowUserToDeleteRows = false; this.dgvKetQua.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgvKetQua.Location = new System.Drawing.Point(96, 183); this.dgvKetQua.Name = "dgvKetQua"; this.dgvKetQua.ReadOnly = true; this.dgvKetQua.Size = new System.Drawing.Size(537, 214); this.dgvKetQua.TabIndex = 30; // // btnTim // this.btnTim.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnTim.BackgroundImage"))); this.btnTim.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.btnTim.Location = new System.Drawing.Point(580, 105); this.btnTim.Name = "btnTim"; this.btnTim.Size = new System.Drawing.Size(72, 30); this.btnTim.TabIndex = 29; this.btnTim.Text = " Tìm"; this.btnTim.UseVisualStyleBackColor = true; // // txtMaSV // this.txtMaSV.Location = new System.Drawing.Point(114, 111); this.txtMaSV.Name = "txtMaSV"; this.txtMaSV.Size = new System.Drawing.Size(125, 20); this.txtMaSV.TabIndex = 28; // // lblMaMH // this.lblMaMH.AutoSize = true; this.lblMaMH.Location = new System.Drawing.Point(302, 111); this.lblMaMH.Name = "lblMaMH"; this.lblMaMH.Size = new System.Drawing.Size(60, 13); this.lblMaMH.TabIndex = 26; this.lblMaMH.Text = "Mã Học Kỳ"; // // lblMaSV // this.lblMaSV.AutoSize = true; this.lblMaSV.Location = new System.Drawing.Point(43, 111); this.lblMaSV.Name = "lblMaSV"; this.lblMaSV.Size = new System.Drawing.Size(39, 13); this.lblMaSV.TabIndex = 27; this.lblMaSV.Text = "Mã SV"; // // lblTittle // this.lblTittle.AutoSize = true; this.lblTittle.Font = new System.Drawing.Font("Times New Roman", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblTittle.ForeColor = System.Drawing.Color.Red; this.lblTittle.Location = new System.Drawing.Point(151, 30); this.lblTittle.Name = "lblTittle"; this.lblTittle.Size = new System.Drawing.Size(408, 31); this.lblTittle.TabIndex = 25; this.lblTittle.Text = "Tìm Kiếm Điểm Theo Mã Sinh Viên"; // // frmtimkiemdiemsinhvientheomasv // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(695, 479); this.Controls.Add(this.btnThoat); this.Controls.Add(this.cmbMaMH); this.Controls.Add(this.dgvKetQua); this.Controls.Add(this.btnTim); this.Controls.Add(this.txtMaSV); this.Controls.Add(this.lblMaMH); this.Controls.Add(this.lblMaSV); this.Controls.Add(this.lblTittle); this.Name = "frmtimkiemdiemsinhvientheomasv"; this.Text = "TÌM KIẾM ĐIỂM SINH VIÊN"; ((System.ComponentModel.ISupportInitialize)(this.dgvKetQua)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnThoat; private System.Windows.Forms.ComboBox cmbMaMH; private System.Windows.Forms.DataGridView dgvKetQua; private System.Windows.Forms.Button btnTim; private System.Windows.Forms.TextBox txtMaSV; private System.Windows.Forms.Label lblMaMH; private System.Windows.Forms.Label lblMaSV; private System.Windows.Forms.Label lblTittle; } }
F4Team-DHCN1A/QLSV
QuanLySinhVien_MaNguonMo/QuanLySinhVien_GUI/frmtimkiemdiemsinhvientheomasv.Designer.cs
C#
mit
6,855
## Your Names # 1) Michael Yao # 2) Benjamin Heidebrink # We spent [1.25] hours on this challenge. # Bakery Serving Size portion calculator. def serving_size_calc(item_to_make, num_of_ingredients) library = {"cookie" => 1, "cake" => 5, "pie" => 7} raise ArgumentError.new("#{item_to_make} is not a valid input") unless library[item_to_make] # fail ArgumentError, "#{item_to_make} is not a valid input" unless library.key?(item_to_make) serving_size = library[item_to_make] remaining_ingredients = num_of_ingredients % serving_size baking_plan = "Calculations complete: Make #{num_of_ingredients / serving_size} of #{item_to_make}" return baking_plan if remaining_ingredients.zero? baking_plan + ", you have #{remaining_ingredients} leftover ingredients. Suggested baking items: #{leftovers(remaining_ingredients)}" end def leftovers(remaining_ingredients) cakes=remaining_ingredients/5 cookies=remaining_ingredients%5 "#{cakes} cakes and #{cookies} cookies." end p serving_size_calc("pie", 7) p serving_size_calc("pie", 8) p serving_size_calc("cake", 5) p serving_size_calc("cake", 7) p serving_size_calc("cookie", 1) p serving_size_calc("cookie", 10) p serving_size_calc("THIS IS AN ERROR", 5) # Reflection # What did you learn about making code readable by working on this challenge? # It's preeettty important. Also we learned some new methods/syntax to make it more readable and truthy/falsey # Did you learn any new methods? What did you learn about them? # .zero? .key? .nil? .values_at # What did you learn about accessing data in hashes? # .values_at returns an array, .key checks for keys., if we show one argument it will return an array of hash/key # What concepts were solidified when working through this challenge? # refactoring, some syntax
MichaelYao88/phase-0
week-6/gps.rb
Ruby
mit
1,806
module PalmTasksHelper end
wizardbeard/agency-iq
app/helpers/palm_tasks_helper.rb
Ruby
mit
27
import 'css.escape' import { createFootnote, FootnoteElements } from './footnote' import { bindScrollHandler } from './scroll' import { Adapter } from '../core' import { addClass, removeClass, unmount } from './element' export const CLASS_CONTENT = 'littlefoot__content' export const CLASS_WRAPPER = 'littlefoot__wrapper' export type HTMLAdapterSettings = Readonly<{ allowDuplicates: boolean anchorParentSelector: string anchorPattern: RegExp buttonTemplate: string contentTemplate: string footnoteSelector: string numberResetSelector: string scope: string }> type TemplateData = Readonly<{ number: number id: string content: string reference: string }> type Original = Readonly<{ reference: HTMLElement referenceId: string body: HTMLElement }> type OriginalData = Readonly<{ original: Original data: TemplateData }> const CLASS_PRINT_ONLY = 'littlefoot--print' const CLASS_HOST = 'littlefoot' const setPrintOnly = (el: Element) => addClass(el, CLASS_PRINT_ONLY) function queryAll<E extends Element>( parent: ParentNode, selector: string ): readonly E[] { return Array.from(parent.querySelectorAll<E>(selector)) } function getByClassName<E extends Element>(element: E, className: string): E { return ( element.querySelector<E>('.' + className) || (element.firstElementChild as E | null) || element ) } function createElementFromHTML(html: string): HTMLElement { const container = document.createElement('div') container.innerHTML = html return container.firstElementChild as HTMLElement } function children(element: Element, selector: string): readonly Element[] { return Array.from(element.children).filter( (child) => child.nodeType !== 8 && child.matches(selector) ) } function isDefined<T>(value?: T): value is T { return value !== undefined } function findFootnoteLinks( document: Document, pattern: RegExp, scope: string ): readonly HTMLAnchorElement[] { return queryAll<HTMLAnchorElement>(document, scope + ' a[href*="#"]').filter( (link) => (link.href + link.rel).match(pattern) ) } function findReference( document: Document, allowDuplicates: boolean, anchorParentSelector: string, footnoteSelector: string ) { const processed: Element[] = [] return (link: HTMLAnchorElement): Original | undefined => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const fragment = link.href.split('#')[1]! const related = queryAll(document, '#' + CSS.escape(fragment)).find( (footnote) => allowDuplicates || !processed.includes(footnote) ) const body = related?.closest<HTMLElement>(footnoteSelector) if (body) { processed.push(body) const reference = link.closest<HTMLElement>(anchorParentSelector) || link const referenceId = reference.id || link.id return { reference, referenceId, body } } } } function recursiveHideFootnoteContainer(element: HTMLElement): void { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const container = element.parentElement! const visibleElements = children(container, `:not(.${CLASS_PRINT_ONLY})`) const visibleSeparators = visibleElements.filter((el) => el.tagName === 'HR') if (visibleElements.length === visibleSeparators.length) { visibleSeparators.concat(container).forEach(setPrintOnly) recursiveHideFootnoteContainer(container) } } function recursiveUnmount(element: HTMLElement) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const parent = element.parentElement! unmount(element) const html = parent.innerHTML.replace('[]', '').replace('&nbsp;', ' ').trim() if (!html) { recursiveUnmount(parent) } } function prepareTemplateData(original: Original, idx: number): OriginalData { const content = createElementFromHTML(original.body.outerHTML) const backlinkSelector = '[href$="#' + original.referenceId + '"]' queryAll<HTMLElement>(content, backlinkSelector).forEach(recursiveUnmount) const html = content.innerHTML.trim() return { original, data: { id: String(idx + 1), number: idx + 1, reference: 'lf-' + original.referenceId, content: html.startsWith('<') ? html : '<p>' + html + '</p>', }, } } const resetNumbers = (resetSelector: string) => { let current = 0 let previousParent: Element | null = null return ({ original, data }: OriginalData): OriginalData => { const parent = original.reference.closest(resetSelector) current = previousParent === parent ? current + 1 : 1 previousParent = parent return { original, data: { ...data, number: current } } } } function interpolate(template: string) { const pattern = /<%=?\s*(\w+?)\s*%>/g return (replacement: TemplateData) => template.replace(pattern, (_, key: keyof TemplateData) => String(replacement[key] ?? '') ) } function createElements(buttonTemplate: string, popoverTemplate: string) { const renderButton = interpolate(buttonTemplate) const renderPopover = interpolate(popoverTemplate) return ({ original, data, }: OriginalData): OriginalData & FootnoteElements => { const id = data.id const host = createElementFromHTML( `<span class="${CLASS_HOST}">${renderButton(data)}</span>` ) const button = host.firstElementChild as HTMLElement button.setAttribute('aria-expanded', 'false') button.dataset.footnoteButton = '' button.dataset.footnoteId = id const popover = createElementFromHTML(renderPopover(data)) popover.dataset.footnotePopover = '' popover.dataset.footnoteId = id const wrapper = getByClassName(popover, CLASS_WRAPPER) const content = getByClassName(popover, CLASS_CONTENT) bindScrollHandler(content, popover) return { original, data, id, button, host, popover, content, wrapper } } } function attachFootnote(reference: HTMLElement, host: HTMLElement): void { reference.insertAdjacentElement('beforebegin', host) } export function setup({ allowDuplicates, anchorParentSelector, anchorPattern, buttonTemplate, contentTemplate, footnoteSelector, numberResetSelector, scope, }: HTMLAdapterSettings): Adapter<HTMLElement> { const footnoteElements = findFootnoteLinks(document, anchorPattern, scope) .map( findReference( document, allowDuplicates, anchorParentSelector, footnoteSelector ) ) .filter(isDefined) .map(prepareTemplateData) .map(numberResetSelector ? resetNumbers(numberResetSelector) : (i) => i) .map(createElements(buttonTemplate, contentTemplate)) footnoteElements.forEach(({ original, host }) => { setPrintOnly(original.reference) setPrintOnly(original.body) recursiveHideFootnoteContainer(original.body) attachFootnote(original.reference, host) }) const footnotes = footnoteElements.map(createFootnote) return { footnotes, unmount() { footnotes.forEach((footnote) => footnote.destroy()) queryAll(document, '.' + CLASS_PRINT_ONLY).forEach((element) => removeClass(element, CLASS_PRINT_ONLY) ) }, } }
goblindegook/littlefoot
src/dom/document.ts
TypeScript
mit
7,139
require File.expand_path("spec_helper", File.dirname(File.dirname(__FILE__))) describe 'response.cache_control' do it 'sets the Cache-Control header' do app(:caching) do |r| response.cache_control :public=>true, :no_cache=>true, :max_age => 60 end header('Cache-Control').split(', ').sort.should == ['max-age=60', 'no-cache', 'public'] end it 'does not add a Cache-Control header if it would be empty' do app(:caching) do |r| response.cache_control({}) end header('Cache-Control').should == nil end end describe 'response.expires' do it 'sets the Cache-Control and Expires header' do app(:caching) do |r| response.expires 60, :public=>true, :no_cache=>true end header('Cache-Control').split(', ').sort.should == ['max-age=60', 'no-cache', 'public'] ((Time.httpdate(header('Expires')) - Time.now).round - 60).abs.should <= 1 end it 'can be called with only one argument' do app(:caching) do |r| response.expires 60 end header('Cache-Control').split(', ').sort.should == ['max-age=60'] ((Time.httpdate(header('Expires')) - Time.now).round - 60).abs.should <= 1 end end describe 'response.finish' do it 'removes Content-Type and Content-Length for 304 responses' do app(:caching) do |r| response.status = 304 end header('Content-Type').should == nil header('Content-Length').should == nil end it 'does not change non-304 responses' do app(:caching) do |r| response.status = 200 end header('Content-Type').should == 'text/html' header('Content-Length').should == '0' end end describe 'request.last_modified' do it 'ignores nil' do app(:caching) do |r| r.last_modified nil end header('Last-Modified').should == nil end it 'does not change a status other than 200' do app(:caching) do |r| response.status = 201 r.last_modified Time.now end status.should == 201 status('HTTP_IF_MODIFIED_SINCE' => 'Sun, 26 Sep 2030 23:43:52 GMT').should == 201 status('HTTP_IF_MODIFIED_SINCE' => 'Sun, 26 Sep 2000 23:43:52 GMT').should == 201 end end describe 'request.last_modified' do def res(a={}) s, h, b = req(a) h['Last-Modified'].should == @last_modified.httpdate [s, b.join] end before(:all) do lm = @last_modified = Time.now app(:caching) do |r| r.last_modified lm 'ok' end end it 'just sets Last-Modified if no If-Modified-Since header' do res.should == [200, 'ok'] end it 'just sets Last-Modified if bogus If-Modified-Since header' do res('HTTP_IF_MODIFIED_SINCE' => 'a really weird date').should == [200, 'ok'] end it 'just sets Last-Modified if modified since If-Modified-Since header' do res('HTTP_IF_MODIFIED_SINCE' => (@last_modified - 1).httpdate).should == [200, 'ok'] end it 'sets Last-Modified and returns 304 if modified on If-Modified-Since header' do res('HTTP_IF_MODIFIED_SINCE' => @last_modified.httpdate).should == [304, ''] end it 'sets Last-Modified and returns 304 if modified before If-Modified-Since header' do res('HTTP_IF_MODIFIED_SINCE' => (@last_modified + 1).httpdate).should == [304, ''] end it 'sets Last-Modified if If-None-Match header present' do res('HTTP_IF_NONE_MATCH' => '*', 'HTTP_IF_MODIFIED_SINCE' => (@last_modified + 1).httpdate).should == [200, 'ok'] end it 'sets Last-Modified if modified before If-Unmodified-Since header' do res('HTTP_IF_UNMODIFIED_SINCE' => (@last_modified + 1).httpdate).should == [200, 'ok'] end it 'sets Last-Modified if modified on If-Unmodified-Since header' do res('HTTP_IF_UNMODIFIED_SINCE' => @last_modified.httpdate).should == [200, 'ok'] end it 'sets Last-Modified and returns 412 if modified after If-Unmodified-Since header' do res('HTTP_IF_UNMODIFIED_SINCE' => (@last_modified - 1).httpdate).should == [412, ''] end end describe 'request.etag' do before(:all) do app(:caching) do |r| r.is "" do response.status = r.env['status'] if r.env['status'] etag_opts = {} etag_opts[:new_resource] = r.env['new_resource'] if r.env.has_key?('new_resource') etag_opts[:weak] = r.env['weak'] if r.env.has_key?('weak') r.etag 'foo', etag_opts 'ok' end end end it 'uses a weak etag with the :weak option' do header('ETag', 'weak'=>true).should == 'W/"foo"' end describe 'for GET requests' do def res(a={}) s, h, b = req(a) h['ETag'].should == '"foo"' [s, b.join] end it "sets etag if no If-None-Match" do res.should == [200, 'ok'] end it "sets etag and returns 304 if If-None-Match is *" do res('HTTP_IF_NONE_MATCH' => '*').should == [304, ''] end it "sets etag and if If-None-Match is * and it is a new resource" do res('HTTP_IF_NONE_MATCH' => '*', 'new_resource'=>true).should == [200, 'ok'] end it "sets etag and returns 304 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"').should == [304, ''] end it "sets etag and returns 304 if If-None-Match includes etag" do res('HTTP_IF_NONE_MATCH' => '"bar", "foo"').should == [304, ''] end it "sets etag if If-None-Match does not include etag" do res('HTTP_IF_NONE_MATCH' => '"bar", "baz"').should == [200, 'ok'] end it "sets etag and does not change status code if status code set and not 2xx or 304 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>499).should == [499, 'ok'] end it "sets etag and returns 304 if status code set to 2xx if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>201).should == [304, ''] end it "sets etag and returns 304 if status code is already 304 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>304).should == [304, ''] end it "sets etag if If-Match is *" do res('HTTP_IF_MATCH' => '*').should == [200, 'ok'] end it "sets etag if If-Match is etag" do res('HTTP_IF_MATCH' => '"foo"').should == [200, 'ok'] end it "sets etag if If-Match includes etag" do res('HTTP_IF_MATCH' => '"bar", "foo"').should == [200, 'ok'] end it "sets etag and returns 412 if If-Match is * for new resources" do res('HTTP_IF_MATCH' => '*', 'new_resource'=>true).should == [412, ''] end it "sets etag if If-Match does not include etag" do res('HTTP_IF_MATCH' => '"bar", "baz"', 'new_resource'=>true).should == [412, ''] end end describe 'for PUT requests' do def res(a={}) s, h, b = req(a.merge('REQUEST_METHOD'=>'PUT')) h['ETag'].should == '"foo"' [s, b.join] end it "sets etag if no If-None-Match" do res.should == [200, 'ok'] end it "sets etag and returns 412 if If-None-Match is *" do res('HTTP_IF_NONE_MATCH' => '*').should == [412, ''] end it "sets etag and if If-None-Match is * and it is a new resource" do res('HTTP_IF_NONE_MATCH' => '*', 'new_resource'=>true).should == [200, 'ok'] end it "sets etag and returns 412 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"').should == [412, ''] end it "sets etag and returns 412 if If-None-Match includes etag" do res('HTTP_IF_NONE_MATCH' => '"bar", "foo"').should == [412, ''] end it "sets etag if If-None-Match does not include etag" do res('HTTP_IF_NONE_MATCH' => '"bar", "baz"').should == [200, 'ok'] end it "sets etag and does not change status code if status code set and not 2xx or 304 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>499).should == [499, 'ok'] end it "sets etag and returns 304 if status code set to 2xx if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>201).should == [412, ''] end it "sets etag and returns 304 if status code is already 304 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>304).should == [412, ''] end it "sets etag if If-Match is *" do res('HTTP_IF_MATCH' => '*').should == [200, 'ok'] end it "sets etag if If-Match is etag" do res('HTTP_IF_MATCH' => '"foo"').should == [200, 'ok'] end it "sets etag if If-Match includes etag" do res('HTTP_IF_MATCH' => '"bar", "foo"').should == [200, 'ok'] end it "sets etag and returns 412 if If-Match is * for new resources" do res('HTTP_IF_MATCH' => '*', 'new_resource'=>true).should == [412, ''] end it "sets etag if If-Match does not include etag" do res('HTTP_IF_MATCH' => '"bar", "baz"', 'new_resource'=>true).should == [412, ''] end end describe 'for POST requests' do def res(a={}) s, h, b = req(a.merge('REQUEST_METHOD'=>'POST')) h['ETag'].should == '"foo"' [s, b.join] end it "sets etag if no If-None-Match" do res.should == [200, 'ok'] end it "sets etag and returns 412 if If-None-Match is * and it is not a new resource" do res('HTTP_IF_NONE_MATCH' => '*', 'new_resource'=>false).should == [412, ''] end it "sets etag and if If-None-Match is *" do res('HTTP_IF_NONE_MATCH' => '*').should == [200, 'ok'] end it "sets etag and returns 412 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"').should == [412, ''] end it "sets etag and returns 412 if If-None-Match includes etag" do res('HTTP_IF_NONE_MATCH' => '"bar", "foo"').should == [412, ''] end it "sets etag if If-None-Match does not include etag" do res('HTTP_IF_NONE_MATCH' => '"bar", "baz"').should == [200, 'ok'] end it "sets etag and does not change status code if status code set and not 2xx or 304 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>499).should == [499, 'ok'] end it "sets etag and returns 304 if status code set to 2xx if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>201).should == [412, ''] end it "sets etag and returns 304 if status code is already 304 if If-None-Match is etag" do res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>304).should == [412, ''] end it "sets etag if If-Match is * and this is not a new resource" do res('HTTP_IF_MATCH' => '*', 'new_resource'=>false).should == [200, 'ok'] end it "sets etag if If-Match is etag" do res('HTTP_IF_MATCH' => '"foo"').should == [200, 'ok'] end it "sets etag if If-Match includes etag" do res('HTTP_IF_MATCH' => '"bar", "foo"').should == [200, 'ok'] end it "sets etag and returns 412 if If-Match is * for new resources" do res('HTTP_IF_MATCH' => '*').should == [412, ''] end it "sets etag if If-Match does not include etag" do res('HTTP_IF_MATCH' => '"bar", "baz"', 'new_resource'=>true).should == [412, ''] end end end
janko-m/roda
spec/plugin/caching_spec.rb
Ruby
mit
10,994
class RemoveOdTokenFromUsers < ActiveRecord::Migration def change remove_column :users, :od_token end end
jphager2/john-hager-info
db/migrate/20160627182212_remove_od_token_from_users.rb
Ruby
mit
114
(function() { angular.module('starter.controllers').controller('DetailController', DetailController); DetailController.$inject = ['CarService', '$stateParams']; function DetailController (CarService, $stateParams) { var vm = this; CarService.getCar($stateParams.id).$promise.then(function(data) { vm.car = data; CarService.setCurrentCar(data); } ); } })();
jyen/corporate-challenge
mobile/www/app/car/detail/detail.controller.js
JavaScript
mit
401
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\DependencyResolver; use Composer\Filter\PlatformRequirementFilter\IgnoreListPlatformRequirementFilter; use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterFactory; use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterInterface; use Composer\Package\BasePackage; use Composer\Package\AliasPackage; /** * @author Nils Adermann <naderman@naderman.de> * @phpstan-import-type ReasonData from Rule */ class RuleSetGenerator { /** @var PolicyInterface */ protected $policy; /** @var Pool */ protected $pool; /** @var RuleSet */ protected $rules; /** @var array<int, BasePackage> */ protected $addedMap = array(); /** @var array<string, BasePackage[]> */ protected $addedPackagesByNames = array(); public function __construct(PolicyInterface $policy, Pool $pool) { $this->policy = $policy; $this->pool = $pool; $this->rules = new RuleSet; } /** * Creates a new rule for the requirements of a package * * This rule is of the form (-A|B|C), where B and C are the providers of * one requirement of the package A. * * @param BasePackage $package The package with a requirement * @param BasePackage[] $providers The providers of the requirement * @param Rule::RULE_* $reason A RULE_* constant describing the reason for generating this rule * @param mixed $reasonData Any data, e.g. the requirement name, that goes with the reason * @return Rule|null The generated rule or null if tautological * * @phpstan-param ReasonData $reasonData */ protected function createRequireRule(BasePackage $package, array $providers, $reason, $reasonData = null): ?Rule { $literals = array(-$package->id); foreach ($providers as $provider) { // self fulfilling rule? if ($provider === $package) { return null; } $literals[] = $provider->id; } return new GenericRule($literals, $reason, $reasonData); } /** * Creates a rule to install at least one of a set of packages * * The rule is (A|B|C) with A, B and C different packages. If the given * set of packages is empty an impossible rule is generated. * * @param BasePackage[] $packages The set of packages to choose from * @param Rule::RULE_* $reason A RULE_* constant describing the reason for * generating this rule * @param mixed $reasonData Additional data like the root require or fix request info * @return Rule The generated rule * * @phpstan-param ReasonData $reasonData */ protected function createInstallOneOfRule(array $packages, $reason, $reasonData): Rule { $literals = array(); foreach ($packages as $package) { $literals[] = $package->id; } return new GenericRule($literals, $reason, $reasonData); } /** * Creates a rule for two conflicting packages * * The rule for conflicting packages A and B is (-A|-B). A is called the issuer * and B the provider. * * @param BasePackage $issuer The package declaring the conflict * @param BasePackage $provider The package causing the conflict * @param Rule::RULE_* $reason A RULE_* constant describing the reason for generating this rule * @param mixed $reasonData Any data, e.g. the package name, that goes with the reason * @return ?Rule The generated rule * * @phpstan-param ReasonData $reasonData */ protected function createRule2Literals(BasePackage $issuer, BasePackage $provider, $reason, $reasonData = null): ?Rule { // ignore self conflict if ($issuer === $provider) { return null; } return new Rule2Literals(-$issuer->id, -$provider->id, $reason, $reasonData); } /** * @param BasePackage[] $packages * @param Rule::RULE_* $reason A RULE_* constant * @param mixed $reasonData * @return Rule * * @phpstan-param ReasonData $reasonData */ protected function createMultiConflictRule(array $packages, $reason, $reasonData): Rule { $literals = array(); foreach ($packages as $package) { $literals[] = -$package->id; } if (\count($literals) == 2) { return new Rule2Literals($literals[0], $literals[1], $reason, $reasonData); } return new MultiConflictRule($literals, $reason, $reasonData); } /** * Adds a rule unless it duplicates an existing one of any type * * To be able to directly pass in the result of one of the rule creation * methods null is allowed which will not insert a rule. * * @param RuleSet::TYPE_* $type A TYPE_* constant defining the rule type * @param Rule $newRule The rule about to be added * * @return void */ private function addRule($type, Rule $newRule = null): void { if (!$newRule) { return; } $this->rules->add($newRule, $type); } /** * @return void */ protected function addRulesForPackage(BasePackage $package, PlatformRequirementFilterInterface $platformRequirementFilter): void { /** @var \SplQueue<BasePackage> */ $workQueue = new \SplQueue; $workQueue->enqueue($package); while (!$workQueue->isEmpty()) { $package = $workQueue->dequeue(); if (isset($this->addedMap[$package->id])) { continue; } $this->addedMap[$package->id] = $package; if (!$package instanceof AliasPackage) { foreach ($package->getNames(false) as $name) { $this->addedPackagesByNames[$name][] = $package; } } else { $workQueue->enqueue($package->getAliasOf()); $this->addRule(RuleSet::TYPE_PACKAGE, $this->createRequireRule($package, array($package->getAliasOf()), Rule::RULE_PACKAGE_ALIAS, $package)); // aliases must be installed with their main package, so create a rule the other way around as well $this->addRule(RuleSet::TYPE_PACKAGE, $this->createRequireRule($package->getAliasOf(), array($package), Rule::RULE_PACKAGE_INVERSE_ALIAS, $package->getAliasOf())); // if alias package has no self.version requires, its requirements do not // need to be added as the aliased package processing will take care of it if (!$package->hasSelfVersionRequires()) { continue; } } foreach ($package->getRequires() as $link) { $constraint = $link->getConstraint(); if ($platformRequirementFilter->isIgnored($link->getTarget())) { continue; } elseif ($platformRequirementFilter instanceof IgnoreListPlatformRequirementFilter) { $constraint = $platformRequirementFilter->filterConstraint($link->getTarget(), $constraint); } $possibleRequires = $this->pool->whatProvides($link->getTarget(), $constraint); $this->addRule(RuleSet::TYPE_PACKAGE, $this->createRequireRule($package, $possibleRequires, Rule::RULE_PACKAGE_REQUIRES, $link)); foreach ($possibleRequires as $require) { $workQueue->enqueue($require); } } } } /** * @return void */ protected function addConflictRules(PlatformRequirementFilterInterface $platformRequirementFilter): void { /** @var BasePackage $package */ foreach ($this->addedMap as $package) { foreach ($package->getConflicts() as $link) { // even if conlict ends up being with an alias, there would be at least one actual package by this name if (!isset($this->addedPackagesByNames[$link->getTarget()])) { continue; } $constraint = $link->getConstraint(); if ($platformRequirementFilter->isIgnored($link->getTarget())) { continue; } elseif ($platformRequirementFilter instanceof IgnoreListPlatformRequirementFilter) { $constraint = $platformRequirementFilter->filterConstraint($link->getTarget(), $constraint); } $conflicts = $this->pool->whatProvides($link->getTarget(), $constraint); foreach ($conflicts as $conflict) { // define the conflict rule for regular packages, for alias packages it's only needed if the name // matches the conflict exactly, otherwise the name match is by provide/replace which means the // package which this is an alias of will conflict anyway, so no need to create additional rules if (!$conflict instanceof AliasPackage || $conflict->getName() === $link->getTarget()) { $this->addRule(RuleSet::TYPE_PACKAGE, $this->createRule2Literals($package, $conflict, Rule::RULE_PACKAGE_CONFLICT, $link)); } } } } foreach ($this->addedPackagesByNames as $name => $packages) { if (\count($packages) > 1) { $reason = Rule::RULE_PACKAGE_SAME_NAME; $this->addRule(RuleSet::TYPE_PACKAGE, $this->createMultiConflictRule($packages, $reason, $name)); } } } /** * @return void */ protected function addRulesForRequest(Request $request, PlatformRequirementFilterInterface $platformRequirementFilter): void { foreach ($request->getFixedPackages() as $package) { if ($package->id == -1) { // fixed package was not added to the pool as it did not pass the stability requirements, this is fine if ($this->pool->isUnacceptableFixedOrLockedPackage($package)) { continue; } // otherwise, looks like a bug throw new \LogicException("Fixed package ".$package->getPrettyString()." was not added to solver pool."); } $this->addRulesForPackage($package, $platformRequirementFilter); $rule = $this->createInstallOneOfRule(array($package), Rule::RULE_FIXED, array( 'package' => $package, )); $this->addRule(RuleSet::TYPE_REQUEST, $rule); } foreach ($request->getRequires() as $packageName => $constraint) { if ($platformRequirementFilter->isIgnored($packageName)) { continue; } elseif ($platformRequirementFilter instanceof IgnoreListPlatformRequirementFilter) { $constraint = $platformRequirementFilter->filterConstraint($packageName, $constraint); } $packages = $this->pool->whatProvides($packageName, $constraint); if ($packages) { foreach ($packages as $package) { $this->addRulesForPackage($package, $platformRequirementFilter); } $rule = $this->createInstallOneOfRule($packages, Rule::RULE_ROOT_REQUIRE, array( 'packageName' => $packageName, 'constraint' => $constraint, )); $this->addRule(RuleSet::TYPE_REQUEST, $rule); } } } /** * @return void */ protected function addRulesForRootAliases(PlatformRequirementFilterInterface $platformRequirementFilter): void { foreach ($this->pool->getPackages() as $package) { // ensure that rules for root alias packages and aliases of packages which were loaded are also loaded // even if the alias itself isn't required, otherwise a package could be installed without its alias which // leads to unexpected behavior if (!isset($this->addedMap[$package->id]) && $package instanceof AliasPackage && ($package->isRootPackageAlias() || isset($this->addedMap[$package->getAliasOf()->id])) ) { $this->addRulesForPackage($package, $platformRequirementFilter); } } } /** * @return RuleSet */ public function getRulesFor(Request $request, PlatformRequirementFilterInterface $platformRequirementFilter = null): RuleSet { $platformRequirementFilter = $platformRequirementFilter ?: PlatformRequirementFilterFactory::ignoreNothing(); $this->addRulesForRequest($request, $platformRequirementFilter); $this->addRulesForRootAliases($platformRequirementFilter); $this->addConflictRules($platformRequirementFilter); // Remove references to packages $this->addedMap = $this->addedPackagesByNames = array(); $rules = $this->rules; $this->rules = new RuleSet; return $rules; } }
composer/composer
src/Composer/DependencyResolver/RuleSetGenerator.php
PHP
mit
13,501
/** * @author alteredq / http://alteredqualia.com/ */ THREE.DepthPassPlugin = function () { this.enabled = false; this.renderTarget = null; var _gl, _renderer, _lights, _webglObjects, _webglObjectsImmediate, _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin, _frustum = new THREE.Frustum(), _projScreenMatrix = new THREE.Matrix4(), _renderList = []; this.init = function ( renderer, lights, webglObjects, webglObjectsImmediate ) { _gl = renderer.context; _renderer = renderer; _lights = lights; _webglObjects = webglObjects; _webglObjectsImmediate = webglObjectsImmediate; var depthShader = THREE.ShaderLib[ "depthRGBA" ]; var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms ); _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } ); _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } ); _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } ); _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } ); _depthMaterial._shadowPass = true; _depthMaterialMorph._shadowPass = true; _depthMaterialSkin._shadowPass = true; _depthMaterialMorphSkin._shadowPass = true; }; this.render = function ( scene, camera ) { if ( ! this.enabled ) return; this.update( scene, camera ); }; this.update = function ( scene, camera ) { var i, il, j, jl, n, program, buffer, material, webglObject, object, light, renderList, fog = null; // set GL state for depth map _gl.clearColor( 1, 1, 1, 1 ); _gl.disable( _gl.BLEND ); _renderer.state.setDepthTest( true ); // update scene if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); // update camera matrices and frustum camera.matrixWorldInverse.getInverse( camera.matrixWorld ); _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); _frustum.setFromMatrix( _projScreenMatrix ); // render depth map _renderer.setRenderTarget( this.renderTarget ); _renderer.clear(); // set object matrices & frustum culling _renderList.length = 0; projectObject(scene, scene, camera); // render regular objects var objectMaterial, useMorphing, useSkinning; for ( j = 0, jl = _renderList.length; j < jl; j ++ ) { webglObject = _renderList[ j ]; object = webglObject.object; buffer = webglObject.buffer; // todo: create proper depth material for particles if ( object instanceof THREE.PointCloud && ! object.customDepthMaterial ) continue; objectMaterial = getObjectMaterial( object ); if ( objectMaterial ) _renderer.setMaterialFaces( object.material ); useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets; useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning; if ( object.customDepthMaterial ) { material = object.customDepthMaterial; } else if ( useSkinning ) { material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin; } else if ( useMorphing ) { material = _depthMaterialMorph; } else { material = _depthMaterial; } if ( buffer instanceof THREE.BufferGeometry ) { _renderer.renderBufferDirect( camera, _lights, fog, material, buffer, object ); } else { _renderer.renderBuffer( camera, _lights, fog, material, buffer, object ); } } // set matrices and render immediate objects for ( j = 0, jl = _webglObjectsImmediate.length; j < jl; j ++ ) { webglObject = _webglObjectsImmediate[ j ]; object = webglObject.object; if ( object.visible ) { object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); _renderer.renderImmediateObject( camera, _lights, fog, _depthMaterial, object ); } } // restore GL state var clearColor = _renderer.getClearColor(), clearAlpha = _renderer.getClearAlpha(); _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha ); _gl.enable( _gl.BLEND ); }; function projectObject(scene, object,camera) { if ( object.visible ) { var webglObjects = _webglObjects[object.id]; if (webglObjects && (object.frustumCulled === false || _frustum.intersectsObject( object ) === true) ) { for (var i = 0, l = webglObjects.length; i < l; i ++) { var webglObject = webglObjects[i]; object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); _renderList.push(webglObject); } } for (var i = 0, l = object.children.length; i < l; i ++) { projectObject(scene, object.children[i], camera); } } } // For the moment just ignore objects that have multiple materials with different animation methods // Only the first material will be taken into account for deciding which depth material to use function getObjectMaterial( object ) { return object.material instanceof THREE.MeshFaceMaterial ? object.material.materials[ 0 ] : object.material; } };
BenediktS/three.js
examples/js/renderers/plugins/DepthPassPlugin.js
JavaScript
mit
5,549
import path from 'path' let { context, file, mocha, options } = module.parent.context let { it } = context context.it = function (name, callback) { if (callback) { return it(...arguments); } else { callback = name name = path.basename(file, '.js') } }
Capt-Slow/wdio-mocha-framework
test/fixtures/tests.options.compilers.js
JavaScript
mit
264
/** * @copyright Copyright (C) DocuSign, Inc. All rights reserved. * * This source code is intended only as a supplement to DocuSign SDK * and/or on-line documentation. * * This sample is designed to demonstrate DocuSign features and is not intended * for production use. Code and policy for a production application must be * developed to meet the specific data and security requirements of the * application. * * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. */ package net.docusign.sample; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.GregorianCalendar; import java.util.List; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import net.docusign.api_3_0.APIServiceSoap; import net.docusign.api_3_0.ArrayOfString2; import net.docusign.api_3_0.EnvelopePDF; import net.docusign.api_3_0.EnvelopeStatusFilter; import net.docusign.api_3_0.FilteredEnvelopeStatuses; import net.docusign.api_3_0.RequestRecipientTokenAuthenticationAssertion; import net.docusign.api_3_0.RequestRecipientTokenAuthenticationAssertionAuthenticationMethod; import net.docusign.api_3_0.RequestRecipientTokenClientURLs; /** * Servlet implementation class GetStatusAndDocs */ public class GetStatusAndDocs extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public GetStatusAndDocs() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession().setAttribute(Utils.SESSION_EMBEDTOKEN, ""); HttpSession session = request.getSession(); // Make sure we're logged in if (session.getAttribute(Utils.SESSION_LOGGEDIN) == null || session.getAttribute(Utils.SESSION_LOGGEDIN).equals(false)) { response.sendRedirect(Utils.CONTROLLER_LOGIN); } else { // Do we have envelope IDs in this session? if (session.getAttribute(Utils.SESSION_ENVELOPEIDS) != null) { APIServiceSoap api = Utils.getAPI(request); // Grab all the envelope IDs in this session ArrayOfString2 envIDs = new ArrayOfString2(); envIDs.getEnvelopeId().addAll((List<String>) session.getAttribute(Utils.SESSION_ENVELOPEIDS)); // Create a filter so we only retrieve these envelope statuses EnvelopeStatusFilter filter = new EnvelopeStatusFilter(); filter.setAccountId(session.getAttribute(Utils.SESSION_ACCOUNT_ID).toString()); filter.setEnvelopeIds(envIDs); try { // Call requestStatusesEx on these envelopes FilteredEnvelopeStatuses statuses = api.requestStatusesEx(filter); session.setAttribute(Utils.SESSION_STATUSES, statuses.getEnvelopeStatuses().getEnvelopeStatus()); } catch (Exception e) { } } response.sendRedirect(Utils.PAGE_GETSTATUS); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the parameter names Enumeration paramNames = request.getParameterNames(); // Loop through the parameter names while (paramNames.hasMoreElements()) { String paramName = (String)paramNames.nextElement(); if (paramName.startsWith(Utils.NAME_STARTSIGNING)) { // We want to start this user signing startSigning(paramName, request); response.sendRedirect(Utils.PAGE_GETSTATUS); } else if (paramName.startsWith(Utils.NAME_DOWNLOAD)) { // We want to download the specified envelope downloadEnvelope(paramName, request, response); } } } protected void downloadEnvelope(String param, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String eid = param.split("\\+")[1]; // Request the PDF of the envelope APIServiceSoap api = Utils.getAPI(request); EnvelopePDF pdf = api.requestPDF(eid); // Start download of the resulting PDF byte[] documentBytes = pdf.getPDFBytes(); response.setHeader("Content-Disposition", "attachment;filename=Envelope.pdf"); response.setContentLength(documentBytes.length); response.setContentType("application/pdf"); response.getOutputStream().write(documentBytes); return; } protected void startSigning(String param, HttpServletRequest request) throws ServletException, IOException { // Parse out envelope id, email, username, client user id String[] params = param.split("\\&"); String eid = "", cid = "", uname = "", email = ""; for (int i = 0; i < params.length; i++) { String[] pair = params[i].split("\\+"); if(pair[0].equals("SignDocEnvelope")) { eid = pair[1]; } else if (pair[0].equals("Email")) { email = pair[1]; } else if (pair[0].equals("UserName")) { uname = pair[1]; } else if (pair[0].equals("CID")) { cid = pair[1]; } } // Request the token try { getToken(request, eid, email, uname, cid); } catch (DatatypeConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } protected void getToken(HttpServletRequest request, String eid, String email, String username, String CID) throws DatatypeConfigurationException { String token = null; // Create the assertion RequestRecipientTokenAuthenticationAssertion assertion = new RequestRecipientTokenAuthenticationAssertion(); assertion.setAssertionID(UUID.randomUUID().toString()); // wsdl2java translates this to XMLGregorianCalendar GregorianCalendar gcal = new GregorianCalendar(); gcal.setTime(new Date()); assertion.setAuthenticationInstant(DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal)); assertion.setAuthenticationMethod(RequestRecipientTokenAuthenticationAssertionAuthenticationMethod.PASSWORD); assertion.setSecurityDomain("DocuSign2010Q1Sample"); // Create the URLs that DocuSign will redirect the iframe to after different events RequestRecipientTokenClientURLs urls = new RequestRecipientTokenClientURLs(); String urlbase = Utils.getCallbackURL(request, Utils.PAGE_POP); urls.setOnAccessCodeFailed(urlbase + "?event=AccessCodeFailed&uname=" + username); urls.setOnCancel(urlbase + "?event=Cancel&uname=" + username); urls.setOnDecline(urlbase + "?event=Decline&uname=" + username); urls.setOnException(urlbase + "?event=Exception&uname=" + username); urls.setOnFaxPending(urlbase + "?event=FaxPending&uname=" + username); urls.setOnIdCheckFailed(urlbase + "?event=IdCheckFailed&uname=" + username); urls.setOnSessionTimeout(urlbase + "?event=SessionTimeout&uname=" + username); urls.setOnTTLExpired(urlbase + "?event=TTLExpired&uname=" + username); urls.setOnViewingComplete(urlbase + "?event=ViewingComplete&uname=" + username); urls.setOnSigningComplete(urlbase + "?event=SigningComplete&uname=" + username); // Get the API service and call RequestRecipientToken for this recipient APIServiceSoap api = Utils.getAPI(request); token = api.requestRecipientToken(eid, CID, username, email, assertion, urls); // Set the iframe to the token request.getSession().setAttribute(Utils.SESSION_EMBEDTOKEN, token); } }
docusign/docusign-soap-sdk
Java/DocuSignSample/src/net/docusign/sample/GetStatusAndDocs.java
Java
mit
8,102
# # MIT License # # Copyright (c) 2016 Paul Taylor # # 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. # module PPool class BasicProcessController def initialize @time_started = Time.now.to_i end def running? return true end def num_processes return 1 end def process_started(pid, num_processes) puts "> process started #{pid}; num_processes #{num_processes}" end def run_process info "#{Process.pid} running" exit 0 end def process_ended(pid, status) puts "> process ended - pid #{pid}, status #{status}" end def progress(stats) puts "> active #{stats[:active_processes]} started #{stats[:processes_started]} ended #{stats[:processes_ended]} errors #{stats[:errors]}" end def delay return 0.1 end def info(m) puts "+ #{m}" end def time_running secs = time_running_secs hours = (secs / (60 * 60)) % 24 mins = (secs / 60) % 60 secs = secs % 60 return "%.2d:%.2d:%.2d" % [hours, mins,secs] end def time_running_secs Time.now.to_i - @time_started end end end
ptaylor/ppool
lib/basic_process_controller.rb
Ruby
mit
2,168