text
stringlengths
27
775k
module XA module W3AFAdapter class Tmp attr_accessor :session, :path, :output_path def initialize(session, path) @session = session @path = path @output_path = "#{@path}/output" end def script_file_path "#{@path}/w3af_script_#{@session}.w3af" end def output_file_path "#{@path}/output/w3af_output_#{@session}" end end end end
<?php namespace Drupal\better_social_sharing_buttons\Plugin\Block; use Drupal\Core\Block\BlockBase; use Drupal\Core\Block\BlockPluginInterface; use Drupal\Core\Url; use Symfony\Cmf\Component\Routing\RouteObjectInterface; /** * Provides a social sharing buttons block. * * @Block( * id = "better_social_sharing_buttons_block", * admin_label = @Translation("Better Social Sharing Buttons block"), * ) */ class SocialSharingButtonsBlock extends BlockBase implements BlockPluginInterface { /** * {@inheritdoc} */ public function build() { $items = []; global $base_url; $request = \Drupal::request(); if ($route = $request->attributes->get(RouteObjectInterface::ROUTE_OBJECT)) { $title = \Drupal::service('title_resolver')->getTitle($request, $route); } $items['page_url'] = Url::fromRoute('<current>', [], ['absolute' => TRUE]); $items['description'] = ''; $items['title'] = $title; $items['width'] = \Drupal::state()->get('width') ?: '20px'; $items['height'] = \Drupal::state()->get('height') ?: '20px'; $items['radius'] = \Drupal::state()->get('radius') ?: '3px'; $items['facebook_app_id'] = \Drupal::state()->get('facebook_app_id') ?: ''; $items['iconset'] = \Drupal::state()->get('iconset') ?: 'social-icons--square'; $items['services'] = \Drupal::state()->get('services') ?: [ 'facebook' => 'facebook', 'twitter' => 'twitter', 'linkedin' => 'linkedin', 'googleplus' => 'googleplus', 'email' => 'email', ]; $items['base_url'] = $base_url; return [ '#theme' => 'better_social_sharing_buttons', '#items' => $items, ]; } }
module.exports = [ 'almende/vis', 'anvaka/ngraph', 'anvaka/VivaGraphJS', 'cpettitt/dagre', 'cytoscape/cytoscape.js', 'dhotson/springy', 'fkling/JSNetworkX', 'GraphAlchemist/Alchemy', 'jacomyal/sigma.js', 'mbostock/d3', 'samizdatco/arbor', 'strathausen/dracula' ];
import 'dart:io'; import 'package:academy_app/data/repository/user/i_user_repository.dart'; import 'package:academy_app/model/application_form/application_form.dart'; import 'package:academy_app/model/domain/auth/value_objects.dart'; import 'package:academy_app/model/user_data/user_data.dart'; import 'package:bloc/bloc.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/material.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:image_picker/image_picker.dart'; import 'package:injectable/injectable.dart'; import 'package:intl/intl.dart'; part 'update_user_state.dart'; part 'update_user_cubit.freezed.dart'; @injectable class UpdateUserCubit extends Cubit<UpdateUserState> { final IUserRepo iUserRepo; final picker = ImagePicker(); FirebaseStorage fs = FirebaseStorage.instance; UpdateUserCubit(this.iUserRepo) : super(UpdateUserState.initial()); void userNameChanged(String userName) { emit( state.copyWith( userName: UserName(userName), isChanged: true, ), ); } void parent1PhoneNumberChanged(String value) { emit( state.copyWith( parentOnePhoneNumber: ParentOnePhoneNumber(value), isChanged: true, ), ); } void parent2PhoneNumberChanged(String value) { emit( state.copyWith( parentTwoPhoneNumber: ParentTwoPhoneNumber(value), isChanged: true, ), ); } void homeAddressChanged(String value) { emit( state.copyWith( homeAddress: HomeAddress(value), isChanged: true, ), ); } void preferredEmailChanged(String value) { emit( state.copyWith( preferredEmail: PreferredEmail(value), isChanged: true, ), ); } void emergencyNameChanged(String value) { emit( state.copyWith( emergencyName: EmergencyName(value), isChanged: true, ), ); } void emergencyPhoneNumberChanged(String value) { emit( state.copyWith( emergencyPhoneNumber: EmergencyPhoneNumber(value), isChanged: true, ), ); } Future<void> pickImage() async { final pickedFile = await picker.pickImage(source: ImageSource.gallery); if (pickedFile == null) return; emit( state.copyWith( img: XFile(pickedFile.path), isChanged: true, ), ); } Future<void> uploadImage(UserData userData) async { final format = DateFormat('yyyy-MM-dd hh:mm'); final time = format.format(DateTime.now()); Reference reference = fs.ref().child( 'userImg/${userData.userName!.getOrCrash()}_${time.toString()}.jpg'); UploadTask uploadTask = reference.putFile( File(state.img.path), SettableMetadata(contentType: 'image/jpg')); uploadTask.snapshotEvents.listen( (taskSnapshot) { if (taskSnapshot.state == TaskState.running) { emit(state.copyWith()); } else if (taskSnapshot.state == TaskState.success) { emit(state.copyWith()); } }, ); var imageUrl = await (await uploadTask).ref.getDownloadURL(); emit( state.copyWith( imgUrl: imageUrl, ), ); } Future<void> updateUser( UserData userData, ApplicationForm applicationForm) async { if (state.isChanged == true) { if (state.img.path.isNotEmpty) { emit(state.copyWith(isUpload: true)); if (userData.imgUrl!.isNotEmpty) { fs.refFromURL(userData.imgUrl!).delete(); await uploadImage(userData).whenComplete( () async { emit(state.copyWith(isComplete: true, isUpload: false)); await iUserRepo.updateUserData( userData: userData.copyWith( imgUrl: state.imgUrl ?? userData.imgUrl, userName: state.userName.value .fold((l) => userData.userName, (r) => state.userName), ), ); }, ); } else { await uploadImage(userData).whenComplete( () async { emit(state.copyWith(isComplete: true, isUpload: false)); await iUserRepo.updateUserData( userData: userData.copyWith( imgUrl: state.imgUrl, userName: state.userName.value .fold((l) => userData.userName, (r) => state.userName), ), ); await iUserRepo.updateAplicationForm( applicationForm: applicationForm.copyWith( parentOnePhoneNumber: state.parentOnePhoneNumber.value.fold( (l) => applicationForm.parentOnePhoneNumber, (r) => state.parentOnePhoneNumber, ), parentTwoPhoneNumber: state.parentTwoPhoneNumber.value.fold( (l) => applicationForm.parentTwoPhoneNumber, (r) => state.parentTwoPhoneNumber, ), homeAddress: state.homeAddress.value.fold( (l) => applicationForm.homeAddress, (r) => state.homeAddress, ), preferredEmail: state.preferredEmail.value.fold( (l) => applicationForm.preferredEmail, (r) => state.preferredEmail, ), emergencyName: state.emergencyName.value.fold( (l) => applicationForm.emergencyName, (r) => state.emergencyName, ), emergencyPhoneNumber: state.emergencyPhoneNumber.value.fold( (l) => applicationForm.emergencyPhoneNumber, (r) => state.emergencyPhoneNumber, ), ), ); }, ); } } else { await iUserRepo.updateUserData( userData: userData.copyWith( userName: state.userName.value .fold((l) => userData.userName, (r) => state.userName), ), ); await iUserRepo.updateAplicationForm( applicationForm: applicationForm.copyWith( parentOnePhoneNumber: state.parentOnePhoneNumber.value.fold( (l) => applicationForm.parentOnePhoneNumber, (r) => state.parentOnePhoneNumber, ), parentTwoPhoneNumber: state.parentTwoPhoneNumber.value.fold( (l) => applicationForm.parentTwoPhoneNumber, (r) => state.parentTwoPhoneNumber, ), homeAddress: state.homeAddress.value.fold( (l) => applicationForm.homeAddress, (r) => state.homeAddress, ), preferredEmail: state.preferredEmail.value.fold( (l) => applicationForm.preferredEmail, (r) => state.preferredEmail, ), emergencyName: state.emergencyName.value.fold( (l) => applicationForm.emergencyName, (r) => state.emergencyName, ), emergencyPhoneNumber: state.emergencyPhoneNumber.value.fold( (l) => applicationForm.emergencyPhoneNumber, (r) => state.emergencyPhoneNumber, ), ), ); emit(state.copyWith(isComplete: true)); } } else { return; } emit( state.copyWith( showErrorMessage: AutovalidateMode.always, ), ); } }
package pinata import "time" // PinList - type PinList struct { Count int `json:"count"` Rows []struct { ID string `json:"id"` IpfsPinHash string `json:"ipfs_pin_hash"` Size int `json:"size"` UserID string `json:"user_id"` DatePinned time.Time `json:"date_pinned"` DateUnpinned interface{} `json:"date_unpinned"` Metadata struct { Name interface{} `json:"name"` Keyvalues interface{} `json:"keyvalues"` } `json:"metadata"` Regions []struct { RegionID string `json:"regionId"` CurrentReplicationCount int `json:"currentReplicationCount"` DesiredReplicationCount int `json:"desiredReplicationCount"` } `json:"regions"` } `json:"rows"` } // PinJSONResponse - type PinJSONResponse struct { IpfsHash string `json:"IpfsHash"` PinSize int `json:"PinSize"` Timestamp time.Time `json:"Timestamp"` }
#!/bin/sh set -e git remote | xargs -n1 git push --all
class Brigade < ActiveRecord::Base has_many :deployed_applications has_many :applications, through: :deployed_applications has_and_belongs_to_many :users validates :name, presence: true validates :point_of_contact_address, presence: true def to_s name end end
Rails.application.routes.draw do get 'example' => 'examplegem/example#index' end
// This is a generated file (see the discoveryapis_generator project). // ignore_for_file: unnecessary_cast library googleapis.servicebroker.v1; import 'dart:core' as core; import 'dart:async' as async; import 'dart:convert' as convert; import 'package:_discoveryapis_commons/_discoveryapis_commons.dart' as commons; import 'package:http/http.dart' as http; export 'package:_discoveryapis_commons/_discoveryapis_commons.dart' show ApiRequestError, DetailedApiRequestError; const core.String USER_AGENT = 'dart-api-client servicebroker/v1'; /// The Google Cloud Platform Service Broker API provides Google hosted /// implementation of the Open Service Broker API /// (https://www.openservicebrokerapi.org/). class ServicebrokerApi { /// View and manage your data across Google Cloud Platform services static const CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform"; final commons.ApiRequester _requester; V1ResourceApi get v1 => new V1ResourceApi(_requester); ServicebrokerApi(http.Client client, {core.String rootUrl: "https://servicebroker.googleapis.com/", core.String servicePath: ""}) : _requester = new commons.ApiRequester(client, rootUrl, servicePath, USER_AGENT); } class V1ResourceApi { final commons.ApiRequester _requester; V1ResourceApi(commons.ApiRequester client) : _requester = client; /// Gets the access control policy for a resource. /// Returns an empty policy if the resource exists and does not have a policy /// set. /// /// Request parameters: /// /// [resource] - REQUIRED: The resource for which the policy is being /// requested. /// See the operation documentation for the appropriate value for this field. /// Value must have pattern "^.+$". /// /// [$fields] - Selector specifying which fields to include in a partial /// response. /// /// Completes with a [GoogleIamV1Policy]. /// /// Completes with a [commons.ApiRequestError] if the API endpoint returned an /// error. /// /// If the used [http.Client] completes with an error when making a REST call, /// this method will complete with the same error. async.Future<GoogleIamV1Policy> getIamPolicy(core.String resource, {core.String $fields}) { var _url = null; var _queryParams = new core.Map<core.String, core.List<core.String>>(); var _uploadMedia = null; var _uploadOptions = null; var _downloadOptions = commons.DownloadOptions.Metadata; var _body = null; if (resource == null) { throw new core.ArgumentError("Parameter resource is required."); } if ($fields != null) { _queryParams["fields"] = [$fields]; } _url = 'v1/' + commons.Escaper.ecapeVariableReserved('$resource') + ':getIamPolicy'; var _response = _requester.request(_url, "GET", body: _body, queryParams: _queryParams, uploadOptions: _uploadOptions, uploadMedia: _uploadMedia, downloadOptions: _downloadOptions); return _response.then((data) => new GoogleIamV1Policy.fromJson(data)); } /// Sets the access control policy on the specified resource. Replaces any /// existing policy. /// /// [request] - The metadata request object. /// /// Request parameters: /// /// [resource] - REQUIRED: The resource for which the policy is being /// specified. /// See the operation documentation for the appropriate value for this field. /// Value must have pattern "^.+$". /// /// [$fields] - Selector specifying which fields to include in a partial /// response. /// /// Completes with a [GoogleIamV1Policy]. /// /// Completes with a [commons.ApiRequestError] if the API endpoint returned an /// error. /// /// If the used [http.Client] completes with an error when making a REST call, /// this method will complete with the same error. async.Future<GoogleIamV1Policy> setIamPolicy( GoogleIamV1SetIamPolicyRequest request, core.String resource, {core.String $fields}) { var _url = null; var _queryParams = new core.Map<core.String, core.List<core.String>>(); var _uploadMedia = null; var _uploadOptions = null; var _downloadOptions = commons.DownloadOptions.Metadata; var _body = null; if (request != null) { _body = convert.json.encode((request).toJson()); } if (resource == null) { throw new core.ArgumentError("Parameter resource is required."); } if ($fields != null) { _queryParams["fields"] = [$fields]; } _url = 'v1/' + commons.Escaper.ecapeVariableReserved('$resource') + ':setIamPolicy'; var _response = _requester.request(_url, "POST", body: _body, queryParams: _queryParams, uploadOptions: _uploadOptions, uploadMedia: _uploadMedia, downloadOptions: _downloadOptions); return _response.then((data) => new GoogleIamV1Policy.fromJson(data)); } /// Returns permissions that a caller has on the specified resource. /// If the resource does not exist, this will return an empty set of /// permissions, not a NOT_FOUND error. /// /// Note: This operation is designed to be used for building permission-aware /// UIs and command-line tools, not for authorization checking. This operation /// may "fail open" without warning. /// /// [request] - The metadata request object. /// /// Request parameters: /// /// [resource] - REQUIRED: The resource for which the policy detail is being /// requested. /// See the operation documentation for the appropriate value for this field. /// Value must have pattern "^.+$". /// /// [$fields] - Selector specifying which fields to include in a partial /// response. /// /// Completes with a [GoogleIamV1TestIamPermissionsResponse]. /// /// Completes with a [commons.ApiRequestError] if the API endpoint returned an /// error. /// /// If the used [http.Client] completes with an error when making a REST call, /// this method will complete with the same error. async.Future<GoogleIamV1TestIamPermissionsResponse> testIamPermissions( GoogleIamV1TestIamPermissionsRequest request, core.String resource, {core.String $fields}) { var _url = null; var _queryParams = new core.Map<core.String, core.List<core.String>>(); var _uploadMedia = null; var _uploadOptions = null; var _downloadOptions = commons.DownloadOptions.Metadata; var _body = null; if (request != null) { _body = convert.json.encode((request).toJson()); } if (resource == null) { throw new core.ArgumentError("Parameter resource is required."); } if ($fields != null) { _queryParams["fields"] = [$fields]; } _url = 'v1/' + commons.Escaper.ecapeVariableReserved('$resource') + ':testIamPermissions'; var _response = _requester.request(_url, "POST", body: _body, queryParams: _queryParams, uploadOptions: _uploadOptions, uploadMedia: _uploadMedia, downloadOptions: _downloadOptions); return _response.then( (data) => new GoogleIamV1TestIamPermissionsResponse.fromJson(data)); } } /// Associates `members` with a `role`. class GoogleIamV1Binding { /// Unimplemented. The condition that is associated with this binding. /// NOTE: an unsatisfied condition will not allow user access via current /// binding. Different bindings, including their conditions, are examined /// independently. GoogleTypeExpr condition; /// Specifies the identities requesting access for a Cloud Platform resource. /// `members` can have the following values: /// /// * `allUsers`: A special identifier that represents anyone who is /// on the internet; with or without a Google account. /// /// * `allAuthenticatedUsers`: A special identifier that represents anyone /// who is authenticated with a Google account or a service account. /// /// * `user:{emailid}`: An email address that represents a specific Google /// account. For example, `alice@gmail.com` . /// /// /// * `serviceAccount:{emailid}`: An email address that represents a service /// account. For example, `my-other-app@appspot.gserviceaccount.com`. /// /// * `group:{emailid}`: An email address that represents a Google group. /// For example, `admins@example.com`. /// /// /// * `domain:{domain}`: A Google Apps domain name that represents all the /// users of that domain. For example, `google.com` or `example.com`. core.List<core.String> members; /// Role that is assigned to `members`. /// For example, `roles/viewer`, `roles/editor`, or `roles/owner`. core.String role; GoogleIamV1Binding(); GoogleIamV1Binding.fromJson(core.Map _json) { if (_json.containsKey("condition")) { condition = new GoogleTypeExpr.fromJson(_json["condition"]); } if (_json.containsKey("members")) { members = (_json["members"] as core.List).cast<core.String>(); } if (_json.containsKey("role")) { role = _json["role"]; } } core.Map<core.String, core.Object> toJson() { final core.Map<core.String, core.Object> _json = new core.Map<core.String, core.Object>(); if (condition != null) { _json["condition"] = (condition).toJson(); } if (members != null) { _json["members"] = members; } if (role != null) { _json["role"] = role; } return _json; } } /// Defines an Identity and Access Management (IAM) policy. It is used to /// specify access control policies for Cloud Platform resources. /// /// /// A `Policy` consists of a list of `bindings`. A `binding` binds a list of /// `members` to a `role`, where the members can be user accounts, Google /// groups, /// Google domains, and service accounts. A `role` is a named list of /// permissions /// defined by IAM. /// /// **JSON Example** /// /// { /// "bindings": [ /// { /// "role": "roles/owner", /// "members": [ /// "user:mike@example.com", /// "group:admins@example.com", /// "domain:google.com", /// "serviceAccount:my-other-app@appspot.gserviceaccount.com" /// ] /// }, /// { /// "role": "roles/viewer", /// "members": ["user:sean@example.com"] /// } /// ] /// } /// /// **YAML Example** /// /// bindings: /// - members: /// - user:mike@example.com /// - group:admins@example.com /// - domain:google.com /// - serviceAccount:my-other-app@appspot.gserviceaccount.com /// role: roles/owner /// - members: /// - user:sean@example.com /// role: roles/viewer /// /// /// For a description of IAM and its features, see the /// [IAM developer's guide](https://cloud.google.com/iam/docs). class GoogleIamV1Policy { /// Associates a list of `members` to a `role`. /// `bindings` with no members will result in an error. core.List<GoogleIamV1Binding> bindings; /// `etag` is used for optimistic concurrency control as a way to help /// prevent simultaneous updates of a policy from overwriting each other. /// It is strongly suggested that systems make use of the `etag` in the /// read-modify-write cycle to perform policy updates in order to avoid race /// conditions: An `etag` is returned in the response to `getIamPolicy`, and /// systems are expected to put that etag in the request to `setIamPolicy` to /// ensure that their change will be applied to the same version of the /// policy. /// /// If no `etag` is provided in the call to `setIamPolicy`, then the existing /// policy is overwritten blindly. core.String etag; core.List<core.int> get etagAsBytes { return convert.base64.decode(etag); } void set etagAsBytes(core.List<core.int> _bytes) { etag = convert.base64.encode(_bytes).replaceAll("/", "_").replaceAll("+", "-"); } /// Deprecated. core.int version; GoogleIamV1Policy(); GoogleIamV1Policy.fromJson(core.Map _json) { if (_json.containsKey("bindings")) { bindings = (_json["bindings"] as core.List) .map<GoogleIamV1Binding>( (value) => new GoogleIamV1Binding.fromJson(value)) .toList(); } if (_json.containsKey("etag")) { etag = _json["etag"]; } if (_json.containsKey("version")) { version = _json["version"]; } } core.Map<core.String, core.Object> toJson() { final core.Map<core.String, core.Object> _json = new core.Map<core.String, core.Object>(); if (bindings != null) { _json["bindings"] = bindings.map((value) => (value).toJson()).toList(); } if (etag != null) { _json["etag"] = etag; } if (version != null) { _json["version"] = version; } return _json; } } /// Request message for `SetIamPolicy` method. class GoogleIamV1SetIamPolicyRequest { /// REQUIRED: The complete policy to be applied to the `resource`. The size of /// the policy is limited to a few 10s of KB. An empty policy is a /// valid policy but certain Cloud Platform services (such as Projects) /// might reject them. GoogleIamV1Policy policy; GoogleIamV1SetIamPolicyRequest(); GoogleIamV1SetIamPolicyRequest.fromJson(core.Map _json) { if (_json.containsKey("policy")) { policy = new GoogleIamV1Policy.fromJson(_json["policy"]); } } core.Map<core.String, core.Object> toJson() { final core.Map<core.String, core.Object> _json = new core.Map<core.String, core.Object>(); if (policy != null) { _json["policy"] = (policy).toJson(); } return _json; } } /// Request message for `TestIamPermissions` method. class GoogleIamV1TestIamPermissionsRequest { /// The set of permissions to check for the `resource`. Permissions with /// wildcards (such as '*' or 'storage.*') are not allowed. For more /// information see /// [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). core.List<core.String> permissions; GoogleIamV1TestIamPermissionsRequest(); GoogleIamV1TestIamPermissionsRequest.fromJson(core.Map _json) { if (_json.containsKey("permissions")) { permissions = (_json["permissions"] as core.List).cast<core.String>(); } } core.Map<core.String, core.Object> toJson() { final core.Map<core.String, core.Object> _json = new core.Map<core.String, core.Object>(); if (permissions != null) { _json["permissions"] = permissions; } return _json; } } /// Response message for `TestIamPermissions` method. class GoogleIamV1TestIamPermissionsResponse { /// A subset of `TestPermissionsRequest.permissions` that the caller is /// allowed. core.List<core.String> permissions; GoogleIamV1TestIamPermissionsResponse(); GoogleIamV1TestIamPermissionsResponse.fromJson(core.Map _json) { if (_json.containsKey("permissions")) { permissions = (_json["permissions"] as core.List).cast<core.String>(); } } core.Map<core.String, core.Object> toJson() { final core.Map<core.String, core.Object> _json = new core.Map<core.String, core.Object>(); if (permissions != null) { _json["permissions"] = permissions; } return _json; } } /// Represents an expression text. Example: /// /// title: "User account presence" /// description: "Determines whether the request has a user account" /// expression: "size(request.user) > 0" class GoogleTypeExpr { /// An optional description of the expression. This is a longer text which /// describes the expression, e.g. when hovered over it in a UI. core.String description; /// Textual representation of an expression in /// Common Expression Language syntax. /// /// The application context of the containing message determines which /// well-known feature set of CEL is supported. core.String expression; /// An optional string indicating the location of the expression for error /// reporting, e.g. a file name and a position in the file. core.String location; /// An optional title for the expression, i.e. a short string describing /// its purpose. This can be used e.g. in UIs which allow to enter the /// expression. core.String title; GoogleTypeExpr(); GoogleTypeExpr.fromJson(core.Map _json) { if (_json.containsKey("description")) { description = _json["description"]; } if (_json.containsKey("expression")) { expression = _json["expression"]; } if (_json.containsKey("location")) { location = _json["location"]; } if (_json.containsKey("title")) { title = _json["title"]; } } core.Map<core.String, core.Object> toJson() { final core.Map<core.String, core.Object> _json = new core.Map<core.String, core.Object>(); if (description != null) { _json["description"] = description; } if (expression != null) { _json["expression"] = expression; } if (location != null) { _json["location"] = location; } if (title != null) { _json["title"] = title; } return _json; } }
import os from .cloudfile import CloudFile def save(dir: str): cloudf = CloudFile() if os.path.isfile(dir): cloudf.save_file(dir) return assert os.path.isdir(dir) for item in os.listdir(dir): save(os.path.join(dir, item))
package org.smartx.redis.template; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * <b><code>HashRedisTemplate</code></b> * <p> * Hashes 数据结构的常用方法封装,Hashes不宜存放过大数据,暂不开放支持Object 类型 * </p> * * @author kext */ @Component public class HashRedisTemplate extends BasicRedisTemplate { /** * Set the string value of a hash field */ public Boolean hset(final String key, final String field, final String value) { return hset(key, field, value, 0); } /** * Set the string value of a hash field */ public Boolean hset(final String key, final String field, final String value, final int ttl) { Long reply = jc.hset(key, field, value); if (ttl > 0) { jc.expire(key, ttl); } return reply == 1; } /** * Set the Object value of a hash field */ public Boolean hset(final String key, final String field, final Object value) { return hset(key, field, value, 0); } /** * Set the Object value of a hash field */ public Boolean hset(final String key, final String field, final Object value, final int ttl) { Long reply = jc.hset(key, field, toJsonString(value)); if (ttl > 0) { jc.expire(key, ttl); } return reply == 1; } /** * Get the value of a hash field */ public String hget(final String key, final String field) { return hget(key, field, 0); } /** * Get the value of a hash field */ public String hget(final String key, final String field, int ttl) { String res = jc.hget(key, field); if (ttl > 0) { this.expire(key, ttl); } return res; } /** * Get the value of a hash field */ public <T> T hget(final String key, final String field, final Class<T> clazz) { return hget(key, field, clazz, 0); } /** * Get the value of a hash field */ public <T> T hget(final String key, final String field, final Class<T> clazz, final int ttl) { T res = fromJson(jc.hget(key, field), clazz); if (ttl > 0) { this.expire(key, ttl); } return res; } /** * Delete one or more hash fields */ public Boolean hdel(final String key, final String... fields) { return jc.hdel(key, fields) == 1; } /** * Check if a hash field exists */ public Boolean hexists(final String key, final String field) { return jc.hexists(key, field); } /** * Get all the fields and values in a hash * 当Hash较大时候,慎用! */ public Map<String, String> hgetAll(final String key) { return jc.hgetAll(key); } /** * Get all the fields and values in a hash * 当Hash较大时候,慎用! */ public <T> Map<String, T> hgetAllObject(final String key, Class<T> clazz) { Map<String, String> byteMap = jc.hgetAll(key); if (byteMap != null && byteMap.size() > 0) { Map<String, T> map = new HashMap<>(); for (Entry<String, String> e : byteMap.entrySet()) { map.put(e.getKey(), fromJson(e.getValue(), clazz)); } return map; } return null; } /** * Get the values of all the given hash fields. */ public List<String> hmget(final String key, final String... fields) { return jc.hmget(key, fields); } /** * Get the value of a mulit fields */ public Map<String, Object> hmgetObject(final String key, final int ttl, final String... fields) { if (null == fields) { return null; } List<String> res = jc.hmget(key, fields); Map<String, Object> resMap = null; if (null != res) { resMap = new HashMap<>(); for (int i = 0; i < res.size(); i++) { resMap.put(fields[i], fromJson(res.get(i), Object.class)); } } if (ttl > 0) { this.expire(key, ttl); } return resMap; } /** * Get the value of a mulit fields */ public Map<String, Object> hmgetObject(final String key, final String... fields) { return hmgetObject(key, 0, fields); } /** * Set multiple hash fields to multiple values. */ public String hmset(final String key, final Map<String, String> hash) { return jc.hmset(key, hash); } /** * Increment the integer value of a hash field by the given number. */ public Long hincrBy(final String key, final String field, final long value) { return jc.hincrBy(key, field, value); } /** * Get all the fields in a hash. */ public Set<String> hkeys(final String key) { return jc.hkeys(key); } /** * Get all the fields in a hash. */ public <T> Set<T> hkeys(final String key, final Class<T> clazz) { Set<String> set = jc.hkeys(key); Set<T> objectSet = new HashSet<>(); if (set != null && set.size() != 0) { for (String b : set) { objectSet.add(fromJson(b, clazz)); } } return objectSet; } /** * Get the number of fields in a hash. */ public Long hlen(final String key) { return jc.hlen(key); } }
import { mkdirSync, promises as fs } from 'fs'; const GHOST_TMP = '.ghost/tmp'; export const writeJson = async ( subFolderName: string, data: { slug: string } ) => { try { mkdirSync(`${GHOST_TMP}/${subFolderName}`, { recursive: true }); } catch (error) {} try { await fs.writeFile( `${GHOST_TMP}/${subFolderName}/${data.slug}.json`, JSON.stringify(data) ); } catch (error) { console.log(error); } }; export const writeToMarkdown = async ( subFolderName: string, slug: string, rawText: string ) => { try { mkdirSync(`${GHOST_TMP}/${subFolderName}`, { recursive: true }); } catch (error) {} try { const outputFileName = `${slug}.md`; await fs.writeFile( `${GHOST_TMP}/${subFolderName}/${outputFileName}`, rawText ); } catch (error) { console.log(error); } };
-module(spts_live_SUITE). -author('elbrujohalcon@inaka.net'). -include_lib("mixer/include/mixer.hrl"). -mixin([ {spts_test_utils, [ init_per_suite/1 , end_per_suite/1 ]} ]). -export([ all/0 , init_per_testcase/2 , end_per_testcase/2 ]). -export([ serpent_movement/1 , collision_detection_left_wall/1 , collision_detection_right_wall/1 , collision_detection_up_wall/1 , collision_detection_down_wall/1 , collision_with_serpent_body/1 , collision_with_serpent_head/1 , collision_with_serpent_self/1 , always_a_fruit/1 , fruit_reapears/1 , fruit_feeds/1 , countdown/1 , no_countdown/1 , rounds/1 , initial_food/1 , increasing_food/1 , random_food/1 , random_increasing_food/1 , max_serpents/1 ]). -spec all() -> [atom()]. all() -> spts_test_utils:all(?MODULE). -spec init_per_testcase(atom(), spts_test_utils:config()) -> spts_test_utils:config(). init_per_testcase(random_food, Config) -> Game = spts_games_repo:create( #{cols => 5, rows => 5, flags => [random_food]}), [{game, Game} | Config]; init_per_testcase(random_increasing_food, Config) -> Game = spts_games_repo:create( #{cols => 5, rows => 5, flags => [random_food, increasing_food]}), [{game, Game} | Config]; init_per_testcase(increasing_food, Config) -> Game = spts_games_repo:create( #{cols => 5, rows => 5, flags => [increasing_food]}), [{game, Game} | Config]; init_per_testcase(initial_food, Config) -> GameId = spts_games:id( spts_core:create_game( #{ cols => 50 , rows => 50 , ticktime => 600000 , countdown => 0 , initial_food => 2 })), Serpent = spts_core:add_serpent(GameId, <<"if1">>), Direction = case spts_serpents:body(Serpent) of [{Row, _Col}] when Row < 25 -> down; [{Row, _Col}] when Row >= 25 -> up end, ok = spts_core:turn(GameId, <<"if1">>, Direction), [{game, GameId} | Config]; init_per_testcase(rounds, Config) -> GameId = spts_games:id( spts_core:create_game( #{ cols => 500 , rows => 500 , ticktime => 1000 , countdown => 2 , rounds => 100 })), Serpent = spts_core:add_serpent(GameId, <<"rounds1">>), Direction = case spts_serpents:body(Serpent) of [{Row, _Col}] when Row < 250 -> down; [{Row, _Col}] when Row >= 250 -> up end, ok = spts_core:turn(GameId, <<"rounds1">>, Direction), [{game, GameId} | Config]; init_per_testcase(max_serpents, Config) -> GameId = spts_games:id( spts_core:create_game( #{cols => 5, rows => 5, max_serpents => 2})), [{game, GameId} | Config]; init_per_testcase(serpent_movement, Config) -> GameId = spts_games:id( spts_core:create_game( #{cols => 5, rows => 5, ticktime => 600000, countdown => 0})), _ = spts_core:add_serpent(GameId, <<"sm1">>), _ = spts_core:add_serpent(GameId, <<"sm2">>), _ = spts_core:add_serpent(GameId, <<"sm3">>), [{game, GameId} | Config]; init_per_testcase(Test, Config) when Test == collision_with_serpent_body; Test == collision_with_serpent_head; Test == collision_with_serpent_self; Test == fruit_reapears; Test == fruit_feeds -> Game = spts_games_repo:create(#{cols => 5, rows => 5, initial_food => 0}), [{game, Game} | Config]; init_per_testcase(countdown, Config) -> GameId = spts_games:id( spts_core:create_game( #{cols => 5, rows => 5, ticktime => 600000, countdown => 5})), _ = spts_core:add_serpent(GameId, <<"cd1">>), [{game, GameId} | Config]; init_per_testcase(_Test, Config) -> GameId = spts_games:id( spts_core:create_game( #{cols => 5, rows => 5, ticktime => 600000, countdown => 0})), _ = spts_core:add_serpent(GameId, <<"serp1">>), [{game, GameId} | Config]. -spec end_per_testcase(atom(), spts_test_utils:config()) -> spts_test_utils:config(). end_per_testcase(_Test, Config) -> case lists:keyfind(game, 1, Config) of {game, GameId} when is_binary(GameId) -> ok = spts_core:stop_game(GameId); _ -> ok end, lists:keydelete(game, 1, Config). -spec serpent_movement(spts_test_utils:config()) -> {comment, []}. serpent_movement(Config) -> {game, GameId} = lists:keyfind(game, 1, Config), ct:comment("Check the game board and start the game"), Game = spts_core:fetch_game(GameId), Serpents = spts_games:serpents(Game), ok = spts_core:start_game(GameId), ct:comment("After a tick, all serpents should've moved in their directions"), spts_games:process_name(GameId) ! tick, NewGame = spts_core:fetch_game(GameId), FoundSerpents = lists:map( fun(Serpent) -> NewSerpent = spts_games:serpent(NewGame, spts_serpents:name(Serpent)), ExpectedDirection = spts_serpents:direction(Serpent), ExpectedDirection = spts_serpents:direction(NewSerpent), [Head|_] = spts_serpents:body(Serpent), ExpectedPosition = spts_test_utils:move(Head, spts_serpents:direction(Serpent)), [ExpectedPosition|_] = spts_serpents:body(NewSerpent), NewSerpent end, Serpents), [] = FoundSerpents -- spts_games:serpents(NewGame), [] = spts_games:serpents(NewGame) -- FoundSerpents, {comment, ""}. -spec collision_detection_left_wall(spts_test_utils:config()) -> {comment, []}. collision_detection_left_wall(Config) -> [{_, 0} | _] = collision_detection_wall(left, Config), {comment, ""}. -spec collision_detection_right_wall(spts_test_utils:config()) -> {comment, []}. collision_detection_right_wall(Config) -> [{_, 6} | _] = collision_detection_wall(right, Config), {comment, ""}. -spec collision_detection_up_wall(spts_test_utils:config()) -> {comment, []}. collision_detection_up_wall(Config) -> [{0, _} | _] = collision_detection_wall(up, Config), {comment, ""}. -spec collision_detection_down_wall(spts_test_utils:config()) -> {comment, []}. collision_detection_down_wall(Config) -> [{6, _} | _] = collision_detection_wall(down, Config), {comment, ""}. collision_detection_wall(Direction, Config) -> {game, GameId} = lists:keyfind(game, 1, Config), ct:comment("Pick the first serpent and get it to move ~p", [Direction]), ok = spts_core:turn(GameId, <<"serp1">>, Direction), spts_core:start_game(GameId), ct:comment( "After moving the serpent 5 times ~p, it should've died", [Direction]), lists:foreach( fun(_) -> spts_games:process_name(GameId) ! tick end, lists:seq(1, 5)), NewGame = spts_core:fetch_game(GameId), finished = spts_games:state(NewGame), Serpent = spts_games:serpent(NewGame, <<"serp1">>), dead = spts_serpents:status(Serpent), spts_serpents:body(Serpent). -spec collision_with_serpent_body(spts_test_utils:config()) -> {comment, []}. collision_with_serpent_body(Config) -> {game, Game} = lists:keyfind(game, 1, Config), GameNumericId = spts_games:numeric_id(Game), ct:comment("Serpents are placed in proper positions"), Serpent1 = spts_serpents:new(<<"cwsb1">>, GameNumericId, 1, {2, 2}, down, 1), Serpent2 = spts_serpents:new(<<"cwsb2">>, GameNumericId, 2, {2, 3}, left, 0), GameWithSerpents = spts_games:add_serpent(spts_games:add_serpent(Game, Serpent1), Serpent2), ct:comment("When serpent 2 moves to the left it should collide with S1"), NewGame = spts_games_repo:advance(GameWithSerpents), ct:comment("S1 should be alive and its body should be 2 cells long"), alive = spts_serpents:status(spts_games:serpent(NewGame, <<"cwsb1">>)), ct:comment("S2 should've died in ~p", [NewGame]), dead = spts_serpents:status(spts_games:serpent(NewGame, <<"cwsb2">>)), {comment, ""}. -spec collision_with_serpent_self(spts_test_utils:config()) -> {comment, []}. collision_with_serpent_self(Config) -> {game, Game} = lists:keyfind(game, 1, Config), GameNumericId = spts_games:numeric_id(Game), ct:comment("Serpents are placed in proper positions"), Serpent1 = spts_serpents:new(<<"cwss1">>, GameNumericId, 1, {2, 2}, right, 2), GameWithSerpent = spts_games:add_serpent(Game, Serpent1), ct:comment("When serpent move it grows"), NewGame = spts_games_repo:advance(spts_games_repo:advance(GameWithSerpent)), ct:comment("If it now turns back, it dies"), NewerGame = spts_games_repo:advance( spts_games_repo:turn(NewGame, <<"cwss1">>, left)), ct:comment("The serpent is dead"), dead = spts_serpents:status(spts_games:serpent(NewerGame, <<"cwss1">>)), ct:comment("The game finished"), finished = spts_games:state(NewerGame), {comment, ""}. -spec collision_with_serpent_head(spts_test_utils:config()) -> {comment, []}. collision_with_serpent_head(Config) -> {game, Game} = lists:keyfind(game, 1, Config), GameNumericId = spts_games:numeric_id(Game), ct:comment("Serpents are placed in proper positions"), Serpent1 = spts_serpents:new(<<"cwsh1">>, GameNumericId, 1, {2, 2}, right, 1), Serpent2 = spts_serpents:new(<<"cwsh2">>, GameNumericId, 2, {2, 4}, left, 1), GameWithSerpents = spts_games:add_serpent( spts_games:add_serpent(Game, Serpent1), Serpent2), ct:comment("When serpents move they simultaenously collide"), NewGame = spts_games_repo:advance(GameWithSerpents), ct:comment("Both serpents are dead"), dead = spts_serpents:status(spts_games:serpent(NewGame, <<"cwsh1">>)), dead = spts_serpents:status(spts_games:serpent(NewGame, <<"cwsh2">>)), ct:comment("The game finished"), finished = spts_games:state(NewGame), {comment, ""}. -spec always_a_fruit(spts_test_utils:config()) -> {comment, []}. always_a_fruit(Config) -> {game, GameId} = lists:keyfind(game, 1, Config), Cycle = case spts_serpents:body( spts_games:serpent( spts_core:fetch_game(GameId), <<"serp1">>)) of [{1, 1} | _] -> [right, down, left, up]; [{1, _} | _] -> [down, left, up, right]; [{5, 5} | _] -> [left, up, right, down]; [{5, _} | _] -> [up, right, down, left]; [_|_] -> [up, right, down, left] end, spts_core:start_game(GameId), Advance = fun(Direction) -> ct:comment("Pick the serpent and get it to move ~p", [Direction]), ok = spts_core:turn(GameId, <<"aaf1">>, Direction), spts_games:process_name(GameId) ! tick, NewGame = spts_core:fetch_game(GameId), ct:comment("Fruit is still there: ~p / ~p", [NewGame, Cycle]), {_, _} = spts_games:fruit(NewGame) end, lists:foreach(Advance, Cycle), {comment, ""}. -spec fruit_reapears(spts_test_utils:config()) -> {comment, []}. fruit_reapears(Config) -> {game, Game} = lists:keyfind(game, 1, Config), GameNumericId = spts_games:numeric_id(Game), ct:comment("Serpent and fruit are placed in proper positions"), Serpent1 = spts_serpents:new(<<"fr1">>, GameNumericId, 1, {2, 2}, right, 0), GameWithSerpentAndFruit = add_serpent_and_fruit(Game, 1, Serpent1), ct:comment("When serpent moves it feeds"), NewGame = spts_games_repo:advance(GameWithSerpentAndFruit), ct:comment("Serpent is alive and its head is where the fruit was"), NewSerpent1 = spts_games:serpent(NewGame, <<"fr1">>), alive = spts_serpents:status(NewSerpent1), [{2, 3}] = spts_serpents:body(NewSerpent1), ct:comment("Fruit is somewhere else"), case spts_games:fruit(NewGame) of notfound -> ct:fail("There is no fruit"); {{2, 3}, _} -> ct:fail("Fruit did not move"); _NewFruit -> ok end, {comment, ""}. -spec fruit_feeds(spts_test_utils:config()) -> {comment, []}. fruit_feeds(Config) -> {game, Game} = lists:keyfind(game, 1, Config), GameNumericId = spts_games:numeric_id(Game), ct:comment("Serpent and fruit are placed in proper positions"), Serpent1 = spts_serpents:new(<<"ff1">>, GameNumericId, 1, {2, 2}, right, 0), [{2, 2}] = spts_serpents:body(Serpent1), GameWithSerpentAndFruit = add_serpent_and_fruit(Game, 1, Serpent1), ct:comment("When serpent moves it feeds"), NewGame = spts_games_repo:advance(GameWithSerpentAndFruit), ct:comment("Serpent is alive and its head is where the fruit was"), NewSerpent1 = spts_games:serpent(NewGame, <<"ff1">>), alive = spts_serpents:status(NewSerpent1), [{2, 3}] = spts_serpents:body(NewSerpent1), ct:comment("Serpent advances again, it's body is extended"), {Direction, NewerHead, FinalHead} = case spts_games:fruit(NewGame) of notfound -> ct:fail("There is no fruit"); {{2, 4}, _} -> {down, {3, 3}, {4, 3}}; _NewFruit -> {right, {2, 4}, {2, 5}} end, NewerGame = spts_games_repo:advance( spts_games_repo:turn(NewGame, <<"ff1">>, Direction)), NewerSerpent1 = spts_games:serpent(NewerGame, <<"ff1">>), alive = spts_serpents:status(NewerSerpent1), [NewerHead, {2, 3}] = spts_serpents:body(NewerSerpent1), ct:comment("Serpent advances yet again, it's body is not extended"), FinalGame = spts_games_repo:advance(NewerGame), FinalSerpent1 = spts_games:serpent(FinalGame, <<"ff1">>), alive = spts_serpents:status(FinalSerpent1), [FinalHead, NewerHead] = spts_serpents:body(FinalSerpent1), {comment, ""}. -spec countdown(spts_test_utils:config()) -> {comment, []}. countdown(Config) -> {game, GameId} = lists:keyfind(game, 1, Config), ct:comment("Before start, there are 5 rounds of countdown to go"), Game = spts_core:fetch_game(GameId), 5 = spts_games:countdown(Game), created = spts_games:state(Game), ct:comment("Before really starting the game, we spend 5 rounds of countdown"), ok = spts_core:start_game(GameId), lists:foreach( fun(Round) -> G = spts_core:fetch_game(GameId), Round = spts_games:countdown(G), countdown = spts_games:state(G), spts_games:process_name(GameId) ! tick end, lists:seq(4, 1, -1)), ct:comment("After the countdown the game should start"), spts_games:process_name(GameId) ! tick, FinalGame = spts_core:fetch_game(GameId), 0 = spts_games:countdown(FinalGame), started = spts_games:state(FinalGame), {comment, ""}. -spec no_countdown(spts_test_utils:config()) -> {comment, []}. no_countdown(Config) -> {game, GameId} = lists:keyfind(game, 1, Config), ct:comment("Before start, there are 0 rounds of countdown to go"), Game = spts_core:fetch_game(GameId), 0 = spts_games:countdown(Game), created = spts_games:state(Game), ct:comment("After start, the game jumped straight to started"), ok = spts_core:start_game(GameId), FinalGame = spts_core:fetch_game(GameId), 0 = spts_games:countdown(FinalGame), started = spts_games:state(FinalGame), {comment, ""}. -spec rounds(spts_test_utils:config()) -> {comment, []}. rounds(Config) -> {game, GameId} = lists:keyfind(game, 1, Config), ok = spts_core:start_game(GameId), Tick = fun(_) -> spts_games:process_name(GameId) ! tick end, ct:comment("2 rounds of countdown"), lists:foreach(Tick, [1, 2]), ct:comment("after 9 game rounds, the game should still be started"), lists:foreach(Tick, lists:seq(1, 99)), started = spts_games:state(spts_core:fetch_game(GameId)), ct:comment("after the 10th round, the game should finish due to rounds"), spts_games:process_name(GameId) ! tick, FinalGame = spts_core:fetch_game(GameId), ct:comment("~p", [FinalGame]), finished = spts_games:state(FinalGame), alive = spts_serpents:status(spts_games:serpent(FinalGame, <<"rounds1">>)), {comment, ""}. -spec initial_food(spts_test_utils:config()) -> {comment, []}. initial_food(Config) -> {game, GameId} = lists:keyfind(game, 1, Config), ok = spts_core:start_game(GameId), ct:comment("When the game starts the serpent body length is 1"), [_] = spts_serpents:body( spts_games:serpent( spts_core:fetch_game(GameId), <<"if1">>)), Tick = fun() -> spts_games:process_name(GameId) ! tick, spts_serpents:body( spts_games:serpent( spts_core:fetch_game(GameId), <<"if1">>)) end, ct:comment("After the first tick, the length should be 2"), [_, _] = Tick(), ct:comment("After the second tick, the length should be 3"), [_, _, _] = Tick(), {comment, ""}. -spec increasing_food(spts_test_utils:config()) -> {comment, []}. increasing_food(Config) -> {game, Game} = lists:keyfind(game, 1, Config), GameNumericId = spts_games:numeric_id(Game), ct:comment("Serpent and fruit are placed in proper positions"), Serpent1 = spts_serpents:new(<<"+f1">>, GameNumericId, 1, {2, 2}, right, 1), GameWithSerpentAndFruit = add_serpent_and_fruit(Game, 10, Serpent1), ct:comment("When serpent moves it feeds"), NewGame = spts_games_repo:advance(GameWithSerpentAndFruit), ct:comment("Fruit has a higher value"), case spts_games:fruit(NewGame) of notfound -> ct:fail("There is no fruit"); {_, NewValue} when NewValue =< 10 -> ct:fail("Fruit value didn't increase"); {_, _} -> ok end, {comment, ""}. -spec random_increasing_food(spts_test_utils:config()) -> {comment, []}. random_increasing_food(Config) -> {game, Game} = lists:keyfind(game, 1, Config), GameNumericId = spts_games:numeric_id(Game), ct:comment("Serpent and fruit are placed in proper positions"), Serpent1 = spts_serpents:new(<<"r+f1">>, GameNumericId, 1, {2, 2}, right, 1), GameWithSerpentAndFruit = spts_games:add_serpent( spts_games:content(Game, {2, 3}, {fruit, 1}), Serpent1), ct:comment("When serpent moves it feeds"), NewGame = spts_games_repo:advance(GameWithSerpentAndFruit), ct:comment("Fruit has a different value"), case spts_games:fruit(NewGame) of notfound -> ct:fail("There is no fruit"); {_, 1} -> ct:fail("Fruit value didn't change"); {_, _} -> ok end, {comment, ""}. -spec random_food(spts_test_utils:config()) -> {comment, []}. random_food(Config) -> {game, Game} = lists:keyfind(game, 1, Config), GameNumericId = spts_games:numeric_id(Game), ct:comment("Serpent and fruit are placed in proper positions"), Serpent1 = spts_serpents:new(<<"rf1">>, GameNumericId, 1, {2, 2}, right, 1), GameWithSerpentAndFruit = spts_games:add_serpent( spts_games:content(Game, {2, 3}, {fruit, 10}), Serpent1), ct:comment("When serpent moves it feeds"), NewGame = spts_games_repo:advance(GameWithSerpentAndFruit), ct:comment("Fruit has a =< 10 value"), case spts_games:fruit(NewGame) of notfound -> ct:fail("There is no fruit"); {_, F} when F > 10 -> ct:fail("Fruit value too high"); {_, _} -> ok end, {comment, ""}. -spec max_serpents(spts_test_utils:config()) -> {comment, []}. max_serpents(Config) -> {game, GameId} = lists:keyfind(game, 1, Config), ct:comment("2 serpents can be added"), _ = spts_core:add_serpent(GameId, <<"ms1">>), _ = spts_core:add_serpent(GameId, <<"ms2">>), ct:comment("the 3rd one can not"), try spts_core:add_serpent(GameId, <<"ms3">>) of S -> ct:fail("Unexpected serpent addition: ~p", [S]) catch throw:invalid_state -> ok end, [_, _] = spts_games:serpents(spts_core:fetch_game(GameId)), {comment, ""}. add_serpent_and_fruit(Game, Food, Serpent) -> spts_games:add_serpent( spts_games:content(Game, {2, 3}, {fruit, Food}), Serpent).
{-# LANGUAGE DataKinds #-} import Data.Proxy (Proxy) import GHC.Base (Type) import GHC.TypeLits (KnownNat) foo :: (KnownNat n) => Proxy n -> [Type] -> Type foo = undefined
namespace Sequin.Integration.Configuration { using System; using System.Collections.Generic; using System.Threading.Tasks; using Discovery; using FluentAssertions; using Infrastructure; using Pipeline; using Sequin.Configuration; using Xunit; public class OptionsTests { private readonly OptionsBuilder defaultOptions; public OptionsTests() { defaultOptions = Options.Configure() .WithHandlerFactory(x => new TestHandlerFactory()) .WithCommandRegistry(x => new TestCommandRegistry()); } [Fact] public void SetsCommandRegistry() { var commandRegistry = new TestCommandRegistry(); var options = defaultOptions.WithCommandRegistry(x => commandRegistry) .Build(); options.CommandRegistry.Should().Be(commandRegistry); } [Fact] public void ThrowsExceptionIfCommandRegistryIsNull() { Action action = () => defaultOptions.WithCommandRegistry(x => null); action.ShouldThrow<ArgumentNullException>(); } [Fact] public void ThrowsExceptionIfCommandRegistryResolverIsNull() { Action action = () => defaultOptions.WithCommandRegistry(null); action.ShouldThrow<ArgumentNullException>(); } [Fact] public void SetsHandlerFactory() { var handlerFactory = new TestHandlerFactory(); var options = defaultOptions.WithHandlerFactory(x => handlerFactory) .Build(); options.HandlerFactory.Should().Be(handlerFactory); } [Fact] public void ThrowsExceptionIfHandlerFactoryIsNull() { Action action = () => defaultOptions.WithHandlerFactory(x => null); action.ShouldThrow<ArgumentNullException>(); } [Fact] public void ThrowsExceptionIfHandlerFactoryResolverIsNull() { Action action = () => defaultOptions.WithHandlerFactory(null); action.ShouldThrow<ArgumentNullException>(); } [Fact] public void ConfiguresPipeline() { var options = defaultOptions.WithPipeline(x => new TestCommandPipelineStage { Next = x.IssueCommand }).Build(); options.CommandPipeline.Root.Should().BeOfType<TestCommandPipelineStage>(); } [Fact] public void ThrowsExceptionIfIssueCommandIsNotInPipeline() { Action action = () => defaultOptions.WithPipeline(x => new TestCommandPipelineStage()).Build(); action.ShouldThrow<MissingIssueCommandStageException>(); } [Fact] public void SetsPostProcessorPipeline() { var options = defaultOptions.WithPostProcessPipeline(new TestCommandPipelineStage()) .Build(); options.CommandPipeline.Root.Next.Should().BeOfType<TestCommandPipelineStage>(); } private class TestCommandRegistry : ICommandRegistry { public Type GetCommandType(string name) { throw new NotImplementedException(); } } private class TestHandlerFactory : IHandlerFactory { ICollection<IHandler<T>> IHandlerFactory.GetForCommand<T>() { throw new NotImplementedException(); } } private class TestCommandPipelineStage : CommandPipelineStage { protected override Task Process<TCommand>(TCommand command) { throw new NotImplementedException(); } } } }
import * as React from "react"; import { time } from '../timer'; export const Timer = (props: TimerProps) => ( <h3>{time.secondsToString(props.elapsedSeconds)}</h3> ); export interface TimerProps { elapsedSeconds: number; }
package cli import ( "errors" "fmt" "os" "regexp" "strconv" "strings" "time" "github.com/aws/amazon-ecs-cli-v2/cmd/ecs-preview/template" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/archer" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/cli/group" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/store" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/term/color" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/term/log" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/workspace" "github.com/spf13/cobra" "github.com/spf13/viper" ) // logOpts contains the fields to collect to delete a secret. type logOpts struct { appName string envName string start string tail bool logManager archer.LogManager projectService projectService storeReader storeReader ws archer.Workspace *GlobalOpts } // Validate returns an error if the values provided by the user are invalid. func (o *logOpts) Validate() error { if o.ProjectName() != "" { _, err := o.storeReader.GetProject(o.ProjectName()) if err != nil { return err } } if o.appName != "" { _, err := o.storeReader.GetApplication(o.ProjectName(), o.appName) if err != nil { return err } } if o.envName != "" { if err := o.validateEnvName(); err != nil { return err } } return nil } func (o *logOpts) validateEnvName() error { if _, err := o.targetEnv(); err != nil { return err } return nil } func (o *logOpts) targetEnv() (*archer.Environment, error) { env, err := o.projectService.GetEnvironment(o.ProjectName(), o.envName) if err != nil { return nil, fmt.Errorf("get environment %s from metadata store: %w", o.envName, err) } return env, nil } // Ask asks for fields that are required but not passed in. func (o *logOpts) Ask() error { if err := o.askProject(); err != nil { return err } if err := o.askAppName(); err != nil { return err } return o.askEnvName() } // Execute displays the logs. func (o *logOpts) Execute() error { var startTime int64 logID := fmt.Sprintf("%s-%s-%s", o.projectName, o.envName, o.appName) if o.start == "" { startTime = time.Now().Add(-24 * time.Hour).UnixNano() / 1e6 // msec } else { re := regexp.MustCompile(`^([0-9]*)([A-Za-z])$`) results := re.FindStringSubmatch(o.start) if len(results) != 3 { return errors.New("'start' must be in the format: 24h") } startNum, _ := strconv.Atoi(results[1]) startType := results[2] var then time.Time now := time.Now() switch strings.ToLower(startType) { case "m": then = now.Add(time.Duration(-startNum) * time.Minute) case "h": then = now.Add(time.Duration(-startNum) * time.Hour) case "d": then = now.AddDate(0, 0, -startNum) case "w": then = now.AddDate(0, 0, -startNum * 7) default: return errors.New("'start' type must be: m, h, d, w") } startTime = then.UnixNano() / 1e6 // msec } startTime, err := o.showEntries(logID, startTime) if err != nil { return err } if o.tail { // listen for Enter key to exit go func() { fmt.Scanln() os.Exit(0) }() for { time.Sleep(10 * time.Second) startTime, err = o.showEntries(logID, startTime) if err != nil { return err } } } return nil } // returns the endTime to serve as the startTime for the next iteration func (o *logOpts) showEntries(logID string, startTime int64) (int64, error) { entries, endTime, err := o.logManager.GetLog(logID, startTime) if err != nil { return 0, err } o.print(entries) return endTime, nil } func (o *logOpts) print(entries *[]archer.LogEntry) { for _, e := range *entries { sec := e.Timestamp / 1000 localTime := time.Unix(sec, 0).Local().Format(time.RFC3339) fmt.Printf("%s %s %s\n", color.HighlightLogTimestamp(localTime), color.HighlightLogStreamName(e.StreamName), e.Message) } } func (o *logOpts) askProject() error { if o.ProjectName() != "" { return nil } projNames, err := o.retrieveProjects() if err != nil { return err } if len(projNames) == 0 { log.Infoln("There are no projects to select.") } proj, err := o.prompt.SelectOne( "Which project:", applicationShowProjectNameHelpPrompt, projNames, ) if err != nil { return fmt.Errorf("selecting projects: %w", err) } o.projectName = proj return nil } func (o *logOpts) askEnvName() error { if o.envName != "" { return nil } envs, err := o.projectService.ListEnvironments(o.ProjectName()) if err != nil { return fmt.Errorf("get environments for project %s from metadata store: %w", o.ProjectName(), err) } if len(envs) == 0 { log.Infof("Couldn't find any environments associated with project %s, try initializing one: %s\n", color.HighlightUserInput(o.ProjectName()), color.HighlightCode("dw_run.sh env init")) return fmt.Errorf("no environments found in project %s", o.ProjectName()) } if len(envs) == 1 { o.envName = envs[0].Name log.Infof("Only found one environment, defaulting to: %s\n", color.HighlightUserInput(o.envName)) return nil } var names []string for _, env := range envs { names = append(names, env.Name) } selectedEnvName, err := o.prompt.SelectOne("Select an environment", "", names) if err != nil { return fmt.Errorf("select env name: %w", err) } o.envName = selectedEnvName return nil } func (o *logOpts) askAppName() error { if o.appName != "" { return nil } appNames, err := o.retrieveApplications() if err != nil { return err } if len(appNames) == 0 { log.Infof("No applications found in project '%s'\n.", o.ProjectName()) return nil } appName, err := o.prompt.SelectOne( fmt.Sprintf("Which app:"), "The app this secret belongs to.", appNames, ) if err != nil { return fmt.Errorf("selecting applications for project %s: %w", o.ProjectName(), err) } o.appName = appName return nil } func (o *logOpts) retrieveProjects() ([]string, error) { projs, err := o.storeReader.ListProjects() if err != nil { return nil, fmt.Errorf("listing projects: %w", err) } projNames := make([]string, len(projs)) for ind, proj := range projs { projNames[ind] = proj.Name } return projNames, nil } func (o *logOpts) retrieveApplications() ([]string, error) { apps, err := o.storeReader.ListApplications(o.ProjectName()) if err != nil { return nil, fmt.Errorf("listing applications for project %s: %w", o.ProjectName(), err) } appNames := make([]string, len(apps)) for ind, app := range apps { appNames[ind] = app.Name } return appNames, nil } // BuildLogCmd displays the log entries for an app. func BuildLogCmd() *cobra.Command { opts := logOpts{ GlobalOpts: NewGlobalOpts(), } cmd := &cobra.Command{ Use: "log", Short: "Log commands.", Example: ` Displays the log entries for the last 24 hours (default value). /code $ dw_run.sh log Displays the log entries for the last 14 days. /code $ dw_run.sh log --start 14d The 'start' parameter accepts a number and a range type. Range types: m -> minutes, h -> hours, d -> days, w -> weeks Displays the log entries for the last 24 hours and will show any new entries as they come in. /code $ dw_run.sh log --tail Displays the log entries for the last 20 minutes and will show any new entries as they come in. /code $ dw_run.sh log --start 20m --tail `, PreRunE: runCmdE(func(cmd *cobra.Command, args []string) error { store, err := store.New() if err != nil { return fmt.Errorf("connect to environment datastore: %w", err) } ws, err := workspace.New() if err != nil { return fmt.Errorf("new workspace: %w", err) } opts.ws = ws opts.logManager = store opts.projectService = store opts.storeReader = store return nil }), RunE: runCmdE(func(cmd *cobra.Command, args []string) error { if err := opts.Validate(); err != nil { return err } if err := opts.Ask(); err != nil { return err } return opts.Execute() }), } cmd.Flags().StringVarP(&opts.appName, appFlag, appFlagShort, "", appFlagDescription) cmd.Flags().StringVarP(&opts.start, "start", "s", "", "How far back to look, e.g. `20m`.") cmd.Flags().BoolVar(&opts.tail, "tail", false,"Continuously show new entries.") cmd.Flags().StringVarP(&opts.envName, envFlag, envFlagShort, "", envFlagDescription) cmd.Flags().StringP(projectFlag, projectFlagShort, "dw-run" /* default */, projectFlagDescription) viper.BindPFlag(projectFlag, cmd.Flags().Lookup(projectFlag)) cmd.SetUsageTemplate(template.Usage) cmd.Annotations = map[string]string{ "group": group.Develop, } return cmd }
import * as React from 'react' import * as TestRenderer from 'react-test-renderer' import { LinearProgress } from './LinearProgress' describe('Circular Progress components', () => { describe('rendering variants', () => { test('should match to snapshot - empty LinearProgress', () => { const component = TestRenderer.create(<LinearProgress />) expect(component).toMatchSnapshot('LinearProgress empty snapshot') }) test('should match snapshot - with variant indeterminate', () => { const component = TestRenderer .create(<LinearProgress variant="indeterminate" />) expect(component).toMatchSnapshot('With variant indeterminate snapshot') }) test('should match snapshot - with variant determinate', () => { const component = TestRenderer .create(<LinearProgress variant="determinate" value={70} />) expect(component).toMatchSnapshot('With variant determinate snapshot') }) test('should match snapshot - with variant Buffer', () => { const component = TestRenderer .create(<LinearProgress variant="buffer" value={50} valueBuffer={70} />) expect(component).toMatchSnapshot('With variant buffer snapshot') }) test('should match snapshot - with variant query', () => { const component = TestRenderer .create(<LinearProgress variant="query" />) expect(component).toMatchSnapshot('With variant query snapshot') }) }) })
package com.kafka.demo.controller; import com.kafka.demo.entity.JsonDTO; import com.kafka.demo.producer.JsonProducer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class JsonController { @Autowired private JsonProducer jsonProducer; @PostMapping("/json") public String producerJsonMessage(@RequestBody JsonDTO json){ jsonProducer.sendJson(json); return "JSON sended to Kafka"; } }
import {IComponentConfiguration} from "../../Component"; export interface IRouteInfoKey { key: string; description: string; } export interface IRoutePath { sequenceKey: string; startKey: string; stopKey: string; infoKeys: IRouteInfoKey[]; } export interface IRouteConfiguration extends IComponentConfiguration { paths?: IRoutePath[]; playing?: boolean; } export default IRouteConfiguration;
import withinRange from './within-range'; export default function exponentialRatio(value) { const ratio = (Math.exp(value) - 1) / (Math.E - 1); return withinRange(ratio, 0, 1); }
package com.detmir.kkppt3.views import android.content.Context import android.util.AttributeSet import android.util.Log import android.view.LayoutInflater import android.widget.FrameLayout import android.widget.TextView import com.detmir.kkppt3.R import com.detmir.recycli.annotations.RecyclerItemStateBinder import com.detmir.recycli.annotations.RecyclerItemView import toPx @RecyclerItemView class HeaderItemView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { private val title: TextView init { Log.d("a","init Header sdasd") LayoutInflater.from(context).inflate(R.layout.header_view, this) setPadding(24.toPx, 32.toPx, 24.toPx, 8.toPx) title = findViewById(R.id.header_view_title) } @RecyclerItemStateBinder fun bindState(headerItem: HeaderItem) { title.text = headerItem.title tag = headerItem.id } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Question; class QuestionController extends Controller { public function list() { $questions = Question::withCount('answers')->orderBy('created_at', 'desc')->get(); return view('questions.list', [ 'questions' => $questions, 'placeholder' => PLACEHOLDERS[array_rand(PLACEHOLDERS)], ]); } public function create(Request $req) { $req->validate([ 'body' => ['required', 'min:5', 'ends_with:?'], ]); $question = new Question; $question->body = $req->body; $question->save(); return redirect("/questions/{$question->id}"); } public function show(Question $question) { return view('questions.show', [ 'question' => $question, 'answers' => $question->answers(), ]); } } const PLACEHOLDERS = [ "What's your favorite vegetable?", "How long have you been vegan?", "Why did you go vegan?", "Are you still vegan when you travel?", "How do they milk the almonds?", "How do you really feel about milk powder?", "Bacon tho?", "\"'/><b mouseover=alert(/xss/)>Are my beliefs about cross-site scripting in PHP outdated?", "\"';drop table questions;--Are my beliefs about SQL injection in PHP outdated?", ];
Introduction ------------ This script contains fundamental image manipulation actions. It is based on Pillow for Python. ## Installation Install via pip: pip install os-image-handler ## Usage Example ```python from os_image_handler import image_handler as ih # create a background canvas with a background gradient color background = ih.create_new_image(1024, 500, None, '#FFC1B', '#FF881B') # add text ih.draw_text_on_img(background, 'Ball Game!', 20, 20, '#FFFFFF', '/Users/home/Library/Fonts/Consolas.ttf', 150) # add the ball image ball = ih.load_img('/Users/home/Desktop/icons/ball.png') ball = ih.resize_img_by_width(ball, 250) ih.paste_image(background, ball, 150, 200) # add the happy lady image happy_lady = ih.load_img('/Users/home/Desktop/icons/happy.png') happy_lady = ih.resize_img_by_width(happy_lady, 250) happy_lady = ih.tilt_image(happy_lady, 45) ih.paste_image(background, happy_lady, background.width-happy_lady.width*0.7, background.height/2) # save ih.save_img(background, '/Users/home/Desktop/ball_game_img.png') ``` ![output](/images/ball_game_img.png) ## Licence MIT
# frozen_string_literal: true class Analysis::CodeHistory < Analysis::QueryBase arel_tables :activity_fact, :all_month def execute AllMonth.select([month, select_columns]).joins(joins_clause).where(within_date).group(month).order(month) end private def start_date truncate_date(@start_date) end def end_date truncate_date(@end_date) end end
<?php namespace Syspons\Sheetable\Exceptions; use Exception; use Illuminate\Http\JsonResponse; use Maatwebsite\Excel\Validators\ValidationException; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class ExcelImportValidationException extends Exception { /** * The recommended response to send to the client. */ private ValidationException|PhpSpreadsheetException $validationException; /** * Create a new exception instance. */ public function __construct(ValidationException|PhpSpreadsheetException|null $validationException = null) { parent::__construct('Validation Error.'); $this->validationException = $validationException; } /** * Render the exception into an HTTP response. */ public function render(/* Request $request */): JsonResponse { if ($this->validationException instanceof ValidationException) { $errors = $this->validationException->errors(); } else { $errors = [$this->validationException->getMessage()]; } return response()->json(['errors' => $errors], 422); } }
## 在线 IJulia 笔记本 - [JuliaBox](https://www.juliabox.com) - [Jupyter](https://try.jupyter.org) ## 文本编辑器 - [Juno](http://junolab.org) - [Emacs](https://www.gnu.org/software/emacs) \ [Julia 模式](https://www.emacswiki.org/emacs/Julia) - [vim](https://www.vim.org) \ [Julia 模式](https://github.com/JuliaLang/julia-vim) - [VS Code 插件](https://marketplace.visualstudio.com/items?itemName=julialang.language-julia)
<?php if (@$_GET['halaman']== 'tampilpengguna') { include '../Pengguna/pengguna.php'; } elseif (@$_GET['halaman']== 'inputpengguna') { include '../Pengguna/inputpengguna.php'; } elseif (@$_GET['halaman']== 'editpengguna') { include '../Pengguna/editpengguna.php'; } elseif (@$_GET['halaman']== 'hapuspengguna') { include '../Pengguna/hapuspengguna.php'; } elseif (@$_GET['halaman']== 'tampilpelanggan') { include '../Pelanggan/pelanggan.php'; } elseif (@$_GET['halaman']== 'tambahpelanggan') { include '../Pelanggan/tambah_pelanggan.php'; } elseif (@$_GET['halaman']== 'hapuspelanggan') { include '../Pelanggan/hapus_pelanggan.php'; } elseif (@$_GET['halaman']== 'editpelanggan') { include '../Pelanggan/editpelanggan.php'; } elseif (@$_GET['halaman']== 'tampilproduk') { include '../Daftar_Harga/daftar_harga.php'; } elseif (@$_GET['halaman']== 'editharga') { include '../Daftar_Harga/edit_harga.php'; } elseif (@$_GET['halaman']== 'hapusharga') { include '../Daftar_Harga/hapus_harga.php'; } elseif (@$_GET['halaman']== 'tambahharga') { include '../Daftar_Harga/tambah_harga.php'; } elseif (@$_GET['halaman']== 'tampiljenispengeluaran') { include '../Jenis_Pengeluaran/jenis_pengeluaran.php'; } elseif (@$_GET['halaman']== 'tambahjenis') { include '../Jenis_Pengeluaran/tambah_jenis.php'; } elseif (@$_GET['halaman']== 'hapusjenis') { include '../Jenis_Pengeluaran/hapus_jenis.php'; } elseif (@$_GET['halaman']== 'editjenis') { include '../Jenis_Pengeluaran/edit_jenis.php'; } elseif (@$_GET['halaman']== 'tampilpengeluaran') { include '../Pengeluaran/list_pengeluaran.php'; } elseif (@$_GET['halaman']== 'tambahpengeluaran') { include '../Pengeluaran/tambah_pengeluaran.php'; } elseif (@$_GET['halaman']== 'editpengeluaran') { include '../Pengeluaran/edit_pengeluaran.php'; } elseif (@$_GET['halaman']== 'hapuspengeluaran') { include '../Pengeluaran/hapus_pengeluaran.php'; } elseif(@$_GET['halaman']== 'homepage') { include '../../selamatdatang.php'; } elseif(@$_GET['halaman']== 'tampiltransaksi') { include '../Transaksi/transaksi.php'; } elseif(@$_GET['halaman']== 'edittransaksi') { include '../Transaksi/edittransaksi.php'; } elseif(@$_GET['halaman']== 'hapustransaksi') { include '../Transaksi/hapus_transaksi.php'; } elseif(@$_GET['halaman']== 'hapustransaksisem') { include '../Transaksi/hapus_transaksi_sem.php'; } elseif(@$_GET['halaman']== 'tambahtransaksi') { include '../Transaksi/tambahtransaksi.php'; } else { include '../../selamatdatang.php'; } ?>
num = rand(10) puts "Guess a number from 0 to 9" while true guess = gets.to_i if guess == num puts "Correct" break elsif guess < num puts "Too low" elsif guess > num puts "Too high" end end
using System.Collections.Generic; using Monik.Common; using Monik.Service; using Moq; using Moq.Language.Flow; using NUnit.Framework; namespace Monik.Test { [TestFixture] public class CacheLogTests : CacheBaseTests<CacheLog, Log_> { public override CacheLog CreateCache(IRepository repository, ICacheSourceInstance cache, IMonik monik) { return new CacheLog(repository, cache, monik); } public override ISetup<IRepository, long> SetupRepoMaxId(Mock<IRepository> repo) { return repo.Setup(r => r.GetMaxLogId()); } public override ISetup<IRepository, List<Log_>> SetupRepoLast(Mock<IRepository> repo) { return repo.Setup(r => r.GetLastLogs(It.IsAny<int>())); } public override ISetup<IRepository> SetupRepoWriteEntities(Mock<IRepository> repo) { return repo.Setup(r => r.WriteLogs(It.IsAny<IEnumerable<Log_>>())); } } }
export const FETCH_USER_INIT_ACTION = "FETCH_USER_INIT_ACTION" export function fetchusers() { return { type: FETCH_USER_INIT_ACTION } }
package eu.caraus.appsflastfm.ui.search.artists import eu.caraus.appsflastfm.common.extensions.failed import eu.caraus.appsflastfm.common.extensions.loading import eu.caraus.appsflastfm.common.extensions.subOnIoObsOnUi import eu.caraus.appsflastfm.common.extensions.success import eu.caraus.appsflastfm.common.retrofit.Outcome import eu.caraus.appsflastfm.common.schedulers.SchedulerProvider import eu.caraus.appsflastfm.data.domain.lastFm.artists.ArtistItem import eu.caraus.appsflastfm.data.remote.lastFm.LastFmApi import io.reactivex.subjects.PublishSubject class ArtistsInteractor( private val service : LastFmApi , private val scheduler : SchedulerProvider ) : ArtistsContract.Interactor { private val artistsFetchResult = PublishSubject.create<Outcome<List<ArtistItem?>>>() override fun getArtists( artistName : String ) { artistsFetchResult.loading(true ) service.searchArtists( artistName ).subOnIoObsOnUi( scheduler) .subscribe({ it.results?.artistmatches?.artist?.let { artistsFetchResult.success( it ) } ?: run { artistsFetchResult.success( mutableListOf() ) } },{ artistsFetchResult.failed( it ) }) } override fun getArtistsOutcome() : PublishSubject<Outcome<List<ArtistItem?>>> { return artistsFetchResult } }
# Example Attack **Note:** Keep in mind that each command outlined below can be supplied via YAML file, making it significantly easier to manage complex lockout configurations. ## 1. Install BFG ```bash pip3 install bl-bfg ``` ## 2. Select an attack module View them by running this command. A section titled "Brute Force Modules" will be displayed. I'll use `testing.fake` as an example, which allows us to sample BFG/BruteLoops functionality without attacking a live service. ```bash bfg cli brute-force --help ``` ## 3. Create a database of attack values (usernames/passwords) Use the `manage-db` subcommand to insert values into an SQLite database. There are quite a few import methods here, but I'll demonstrate use of `import-spray-values` for simplicity: ```bash bfg cli manage-db import-spray-values -db /tmp/test.db \ --usernames username1 username2 \ --passwords password1 password2 ``` ## 4. Run the attack Use the `brute-force` subcommand to start the attack. ```bash bfg cli brute-force -db /tmp/test.db \ --parallel-guess-count 4 \ --threshold-jitter-min 15s --threshold-jitter-max 30s \ testing.fake \ --username username1 --password password2 ``` This should result in an attack being executed where a 15-30 second wait occurs between guess attempts for each user.
module.exports = { sessionSecret: "sessionSecret", pwdSecret: "pwdSecret", };
package com.example import org.http4k.security.AccessToken object TokenChecker { fun check(accessToken: AccessToken) = accessToken.value.startsWith("ACCESS_TOKEN") }
require 'minitest/autorun' require 'crg_scoreboard_extractor' class TestBout < Minitest::Test include CrgScoreboardExtractor def setup @bout = Bout.new(File.open('test/fixtures/scoreboard-0-now.xml')) end def test_jam jam = Clock.new(82300, '1', true) assert_equal @bout.jam, jam end def test_period period = Clock.new(1762300, '2', true) assert_equal @bout.period, period end def test_team1 jammer = Position.new("Jammer", "Moshzilla", "42") positions = [ Position.new("Blocker2", "", ""), jammer, Position.new("Blocker1", "", ""), Position.new("Pivot", "", ""), Position.new("Blocker3", "", "") ] team1 = Team.new("Sugar Loathe", "/images/teamlogo/sugar-loathe.jpg", "2", true, positions) assert_equal @bout.team1, team1 assert_equal @bout.team1.jammer, jammer end def test_team2 positions = [ Position.new("Blocker2", "", ""), Position.new("Jammer", "", ""), Position.new("Blocker1", "", ""), Position.new("Pivot", "", ""), Position.new("Blocker3", "", "") ] team2 = Team.new("Ladies of HellTown", "/images/teamlogo/loht.png", "1", false, positions) assert_equal @bout.team2, team2 end end
--- company-name: "Viewable Media" domain: viewablemedia.com home: http://viewablemedia.com/ privacy-policy: http://www.visiblemeasures.com/privacy-policy/ owned-by: "Visible Measures" ---
#!/usr/bin/env ruby # -*- coding: utf-8 -*- # # This sample code is a port of # gstreamer/tests/examples/stepping/framestep1.c. It is licensed # under the terms of the GNU Library General Public License, version # 2 or (at your option) later. # # Copyright (C) 2013 Ruby-GNOME2 Project Team # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA require "gst" def event_loop(pipe) running = true bus = pipe.bus while running message = bus.timed_pop_filtered(Gst::CLOCK_TIME_NONE, Gst::MessageType::ANY) raise "message nil" if message.nil? case message.type when Gst::MessageType::EOS puts "got EOS" running = false when Gst::MessageType::WARNING warning, debug = message.parse_warning puts "Debugging info: #{debug || 'none'}" puts "Warning: #{warning.message}" when Gst::MessageType::ERROR error, debug = message.parse_error puts "Debugging info: #{debug || 'none'}" puts "Error: #{error.message}" running = false when Gst::MessageType::STEP_DONE format, amount, rate, flush, intermediate, duration, eos = message.parse_step_done if format == Gst::Format::DEFAULT puts "step done: #{gst_time(duration)} skipped in #{gst_time(amount)} frames" else puts "step done: #{gst_time(duration)} skipped" end running = false end end end def gst_time(time) Time.at(time / 1000000000.0).utc.strftime("%H:%M:%S.%N") end # create a new bin to hold the elements bin = Gst::Pipeline.new("pipeline") raise "'pipeline' gstreamer plugin missing" if bin.nil? # create a fake source videotestsrc = Gst::ElementFactory.make("videotestsrc", "videotestsrc") raise "'videotestsrc' gstreamer plugin missing" if videotestsrc.nil? videotestsrc.num_buffers = 10 # and a fake sink appsink = Gst::ElementFactory.make("appsink", "appsink") raise "'appsink' gstreamer plugin missing" if appsink.nil? appsink.emit_signals = true appsink.sync = true appsink.signal_connect("new-preroll") do |appsink| # signalled when a new preroll buffer is available sample = appsink.pull_preroll puts "have new-preroll sample #{sample}, timestamp #{gst_time(sample.buffer.pts)}" Gst::FlowReturn::OK end # add objects to the main pipeline bin << videotestsrc << appsink # link the elements videotestsrc >> appsink # go to the PAUSED state and wait for preroll puts "prerolling first frame" bin.pause bin.get_state(Gst::CLOCK_TIME_NONE) # step two frames, flush so that new preroll is queued puts "stepping three frames" unless bin.send_event(Gst::Event.new(Gst::Format::BUFFERS, 2, 1.0, true, false)) raise "Failed to send STEP event!" end # blocks and returns when we received the step done message event_loop(bin) # wait for step to really complete bin.get_state(Gst::CLOCK_TIME_NONE) result, pos = bin.query_position(Gst::Format::TIME) puts "stepped two frames, now at #{gst_time(pos)}" # step 3 frames, flush so that new preroll is queued puts "stepping 120 milliseconds" unless bin.send_event(Gst::Event.new(Gst::Format::TIME, 120 * Gst::MSECOND, 1.0, true, false)) raise "Failed to send STEP event!" end # blocks and returns when we received the step done message event_loop(bin) # wait for step to really complete bin.get_state(Gst::CLOCK_TIME_NONE) result, pos = bin.query_position(Gst::Format::TIME) puts "stepped 120ms frames, now at #{gst_time(pos)}" puts "playing until EOS" bin.play # Run event loop listening for bus messages until EOS or ERROR event_loop(bin) puts "finished" # stop the bin bin.stop
export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" cd $(dirname $(realpath $0)) nvm run --silent index.js
require('../../spec_helper') const cp = require('child_process') const os = require('os') const info = require(`${lib}/tasks/info`) const xvfb = require(`${lib}/exec/xvfb`) const spawn = require(`${lib}/exec/spawn`) describe('exec spawn', function () { beforeEach(function () { this.sandbox.stub(process, 'exit') this.spawnedProcess = this.sandbox.stub({ on: () => {}, unref: () => {}, stdout: { pipe: () => {}, }, stderr: { pipe: () => {}, }, }) this.sandbox.stub(cp, 'spawn').returns(this.spawnedProcess) this.sandbox.stub(xvfb, 'start').resolves() this.sandbox.stub(xvfb, 'stop').resolves() this.sandbox.stub(xvfb, 'isNeeded').returns(true) this.sandbox.stub(info, 'getPathToExecutable').returns('/path/to/cypress') }) context('.start', function () { it('passes args + options to spawn', function () { this.spawnedProcess.on.withArgs('close').yieldsAsync(0) return spawn.start('--foo', { foo: 'bar' }) .then(() => { expect(cp.spawn).to.be.calledWithMatch('/path/to/cypress', ['--foo'], { foo: 'bar' }) }) }) it('starts xvfb when needed', function () { this.spawnedProcess.on.withArgs('close').yieldsAsync(0) return spawn.start('--foo') .then(() => { expect(xvfb.start).to.be.calledOnce }) }) it('does not start xvfb when its not needed', function () { xvfb.isNeeded.returns(false) this.spawnedProcess.on.withArgs('close').yieldsAsync(0) return spawn.start('--foo') .then(() => { expect(xvfb.start).not.to.be.called }) }) it('stops xvfb when spawn closes', function () { this.spawnedProcess.on.withArgs('close').yieldsAsync(0) this.spawnedProcess.on.withArgs('close').yields() return spawn.start('--foo') .then(() => { expect(xvfb.stop).to.be.calledOnce }) }) it('resolves with spawned close code in the message', function () { this.spawnedProcess.on.withArgs('close').yieldsAsync(10) return spawn.start('--foo') .then((code) => { expect(code).to.equal(10) }) }) it('rejects with error from spawn', function () { const msg = 'the error message' this.spawnedProcess.on.withArgs('error').yieldsAsync(new Error(msg)) return spawn.start('--foo') .then(() => { throw new Error('should have hit error handler but did not') }, (e) => { expect(e.message).to.include(msg) }) }) it('unrefs if options.detached is true', function () { this.spawnedProcess.on.withArgs('close').yieldsAsync(0) return spawn.start(null, { detached: true }) .then(() => { expect(this.spawnedProcess.unref).to.be.calledOnce }) }) it('does not unref by default', function () { this.spawnedProcess.on.withArgs('close').yieldsAsync(0) return spawn.start() .then(() => { expect(this.spawnedProcess.unref).not.to.be.called }) }) it('uses inherit/inherit/ignore when not windows', function () { this.sandbox.stub(os, 'platform').returns('darwin') this.spawnedProcess.on.withArgs('close').yieldsAsync(0) return spawn.start() .then(() => { expect(cp.spawn.firstCall.args[2]).to.deep.eq({ detached: false, stdio: ['inherit', 'inherit', 'ignore'], }) }) }) it('uses inherit/pipe/pipe when windows', function () { this.sandbox.stub(os, 'platform').returns('win32') this.spawnedProcess.on.withArgs('close').yieldsAsync(0) return spawn.start() .then(() => { expect(cp.spawn.firstCall.args[2]).to.deep.eq({ detached: false, stdio: ['inherit', 'pipe', 'pipe'], }) }) }) }) })
#ifndef CHIOP_INTERFACE_HPP #define CHIOP_INTERFACE_HPP #include "hiop_defs.hpp" #include "hiopInterface.hpp" #include "hiopNlpFormulation.hpp" #include "hiopAlgFilterIPM.hpp" /** Light C interface that wraps around the mixed-dense nlp class in HiOp. Its initial motivation * was to serve as an interface to Julia */ using namespace hiop; class cppUserProblem; extern "C" { // C struct with HiOp function callbacks typedef struct cHiopProblem { hiopNlpMDS *refcppHiop; cppUserProblem *hiopinterface; // user_data similar to the Ipopt interface. In case of Julia pointer to the Julia problem object. void *user_data; // Used by hiop_solveProblem() to store the final state. The duals should be added here. double *solution; double obj_value; // HiOp callback function wrappers int (*get_starting_point)(size_type n_, double* x0, void* user_data); int (*get_prob_sizes)(size_type* n_, size_type* m_, void* user_data); int (*get_vars_info)(size_type n, double *xlow_, double* xupp_, void* user_data); int (*get_cons_info)(size_type m, double *clow_, double* cupp_, void* user_data); int (*eval_f)(size_type n, double* x, int new_x, double* obj, void* user_data); int (*eval_grad_f)(size_type n, double* x, int new_x, double* gradf, void* user_data); int (*eval_cons)(size_type n, size_type m, double* x, int new_x, double* cons, void* user_data); int (*get_sparse_dense_blocks_info)(hiop_size_type* nx_sparse, hiop_size_type* nx_dense, hiop_size_type* nnz_sparse_Jaceq, hiop_size_type* nnz_sparse_Jacineq, hiop_size_type* nnz_sparse_Hess_Lagr_SS, hiop_size_type* nnz_sparse_Hess_Lagr_SD, void* user_data); int (*eval_Jac_cons)(size_type n, size_type m, double* x, int new_x, size_type nsparse, size_type ndense, int nnzJacS, hiop_index_type* iJacS, hiop_index_type* jJacS, double* MJacS, double* JacD, void *user_data); int (*eval_Hess_Lagr)(size_type n, size_type m, double* x, int new_x, double obj_factor, double* lambda, int new_lambda, size_type nsparse, size_type ndense, hiop_size_type nnzHSS, hiop_index_type* iHSS, hiop_index_type* jHSS, double* MHSS, double* HDD, hiop_size_type nnzHSD, hiop_index_type* iHSD, hiop_index_type* jHSD, double* MHSD, void* user_data); } cHiopProblem; } // The cpp object used in the C interface class cppUserProblem : public hiopInterfaceMDS { public: cppUserProblem(cHiopProblem *cprob_) : cprob(cprob_) { } virtual ~cppUserProblem() { } // HiOp callbacks calling the C wrappers bool get_prob_sizes(size_type& n_, size_type& m_) { cprob->get_prob_sizes(&n_, &m_, cprob->user_data); return true; }; bool get_starting_point(const size_type& n, double *x0) { cprob->get_starting_point(n, x0, cprob->user_data); return true; }; bool get_vars_info(const size_type& n, double *xlow_, double* xupp_, NonlinearityType* type) { for(size_type i=0; i<n; ++i) type[i]=hiopNonlinear; cprob->get_vars_info(n, xlow_, xupp_, cprob->user_data); return true; }; bool get_cons_info(const size_type& m, double* clow, double* cupp, NonlinearityType* type) { for(size_type i=0; i<m; ++i) type[i]=hiopNonlinear; cprob->get_cons_info(m, clow, cupp, cprob->user_data); return true; }; bool eval_f(const size_type& n, const double* x, bool new_x, double& obj_value) { cprob->eval_f(n, (double *) x, 0, &obj_value, cprob->user_data); return true; }; bool eval_grad_f(const size_type& n, const double* x, bool new_x, double* gradf) { cprob->eval_grad_f(n, (double *) x, 0, gradf, cprob->user_data); return true; }; bool eval_cons(const size_type& n, const size_type& m, const size_type& num_cons, const hiop_index_type* idx_cons, const double* x, bool new_x, double* cons) { return false; }; bool eval_cons(const size_type& n, const size_type& m, const double* x, bool new_x, double* cons) { cprob->eval_cons(n, m, (double *) x, new_x, cons, cprob->user_data); return true; }; bool get_sparse_dense_blocks_info(hiop_size_type& nx_sparse, hiop_size_type& nx_dense, hiop_size_type& nnz_sparse_Jaceq, hiop_size_type& nnz_sparse_Jacineq, hiop_size_type& nnz_sparse_Hess_Lagr_SS, hiop_size_type& nnz_sparse_Hess_Lagr_SD) { cprob->get_sparse_dense_blocks_info(&nx_sparse, &nx_dense, &nnz_sparse_Jaceq, &nnz_sparse_Jacineq, &nnz_sparse_Hess_Lagr_SS, &nnz_sparse_Hess_Lagr_SD, cprob->user_data); return true; }; bool eval_Jac_cons(const size_type& n, const size_type& m, const size_type& num_cons, const hiop_index_type* idx_cons, const double* x, bool new_x, const size_type& nsparse, const size_type& ndense, const hiop_size_type& nnzJacS, hiop_index_type* iJacS, hiop_index_type* jJacS, double* MJacS, double* JacD) { return false; }; bool eval_Jac_cons(const size_type& n, const size_type& m, const double* x, bool new_x, const size_type& nsparse, const size_type& ndense, const hiop_size_type& nnzJacS, hiop_index_type* iJacS, hiop_index_type* jJacS, double* MJacS, double* JacD) { cprob->eval_Jac_cons(n, m, (double *) x, new_x, nsparse, ndense, nnzJacS, iJacS, jJacS, MJacS, JacD, cprob->user_data); return true; }; bool eval_Hess_Lagr(const size_type& n, const size_type& m, const double* x, bool new_x, const double& obj_factor, const double* lambda, bool new_lambda, const size_type& nsparse, const size_type& ndense, const hiop_size_type& nnzHSS, hiop_index_type* iHSS, hiop_index_type* jHSS, double* MHSS, double* HDD, hiop_size_type& nnzHSD, hiop_index_type* iHSD, hiop_index_type* jHSD, double* MHSD) { //Note: lambda is not used since all the constraints are linear and, therefore, do //not contribute to the Hessian of the Lagrangian cprob->eval_Hess_Lagr(n, m, (double *) x, new_x, obj_factor, (double *) lambda, new_lambda, nsparse, ndense, nnzHSS, iHSS, jHSS, MHSS, HDD, nnzHSD, iHSD, jHSD, MHSD, cprob->user_data); return true; }; private: // Storing the C struct in the CPP object cHiopProblem *cprob; }; /** The 3 essential function calls to create and destroy a problem object in addition to solve a problem. * Some option setters will be added in the future. */ extern "C" int hiop_createProblem(cHiopProblem *problem); extern "C" int hiop_solveProblem(cHiopProblem *problem); extern "C" int hiop_destroyProblem(cHiopProblem *problem); #endif
A brainfuck interpreter written in brainfuck, compiled using the `brainfuck` macro. See the parent directory.
# Scripts for creating a private cluster across datacenters on Azure This folder has a set of scripts to create a cluster of identical virtual machines (VMs) in different datacenters on Microsoft Azure and to connect these VMs through Azure's vitual network (VNets) peering. ./sbin: scripts to use Azure CLI ./utils: utility scripts ./exp: settings for Domino experiments ## Prerequisites Install Azure CLI NOTE: Azure has limitations on VMs and the access to datacenters for different types of subscriptions or users. Make sure that your Azure subscription has access to target datacenters and quotas to create the expected VMs in these datacenters. One way to check the availability (without generating bills) is to use the web UI trhough Azure Portal to reserve a VM but not finalize the reservation. There could also be limitations on the total number of CPUs and other resources. Quotas can be increased by contacting Azure support. ## Quick start ### Azure CLI login $ az login ### Configuration $ cp sbin/settings-default.sh ./settings.sh Edits settings.sh to configure a cluster, like VM locations and sizes. NOTE: Make sure to correctly specifiy the "vm_public_key" which should be the public key file for the private key that has been configured on Azure for VM logins. ### Cluster creation $ ./sbin/cluster.sh settings.sh The immediate output of cluster.sh may not be able to list all of the required VMs because it will take some time to have all the VMs start running. It would be better to check the VM status via Azure Portal to make sure that all VMs are successfully created and running before using them. After all VMs are running, use ./sbin/vm-ip.sh settings.sh to list all of the VMs and their IPs. NOTE: Once the cluster is not needed, currently you have to stop VMs and delete resources via Azure Portal to avoid unnecessary bills. Make sure that needed data are copied out before removing storage resources. ## Experimental settings for Domino experiments The exp folder contains the cluster settings and scripts for the experiments for the Domino paper. For example, the following commands will create a cluster with 9 datacenters and 3 replicas in North America. cd exp ./azure-cluster-setup.sh settings-Azure-NA-3r.sh ## Script usage samples sbin/settings-default.sh specifies the settings of a cluster to create sbin/cluster.sh creates a cluster of VMs sbin/groups.sh creates a resource group sbin/vnet.sh establishs and peers VNets sbin/vm.sh creates VMs sbin/vm-ip.sh obtains the public and private IPs of the created VMs sbin/location.sh lists the locations of available datacenters in Azure sbin/vnet-del.sh deletes VNets sbin/sample.sh consists of several commonly used Azure CLI commands for information fetching utils/ip.py splits the output of sbin/vm-ip.sh (as a file) into .public and .private files for public and private IPs, respecitively. The .private file will associate a port for each VM as a configuration property for any future use. For example: sbin/vm-ip.sh settings.sh > vm.ip utils/ip.py -f vm.ip -p 10001 ## TODO Add scripts for releasing cluster resources on Azure.
import * as React from "react" import { createMuiTheme, CssBaseline } from "@material-ui/core" import { MuiThemeProvider } from "@material-ui/core/styles" import * as colors from "@material-ui/core/colors" import { ThemeOptionsProvider, WithThemeOptions } from "./ThemeOptionsProvider" interface Props { children: React.ReactNode } export const Providers = (props: Props) => ( <ThemeOptionsProvider> <WithThemeOptions> {({ primaryColor, secondaryColor, rightToLeft, darkMode }) => ( <MuiThemeProvider theme={createMuiTheme({ typography: { useNextVariants: true }, palette: { primary: colors[primaryColor], secondary: colors[secondaryColor], type: darkMode ? "dark" : "light" }, direction: rightToLeft ? "rtl" : "ltr" })} > <CssBaseline /> {props.children} </MuiThemeProvider> )} </WithThemeOptions> </ThemeOptionsProvider> )
package io.byzaneo.initializer.event; import io.byzaneo.initializer.bean.Project; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = true) public class ProjectIntegrationEvent extends ProjectEvent { private static final long serialVersionUID = 1478305394105817966L; public ProjectIntegrationEvent(Project project) { super(project); } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Group; use App\User; use App\Permission; use App\Role; use App\Http\Requests\User\SaveGroup as SaveGroupRequest; use App\Http\Requests\User\SaveUser as SaveUserRequest; use App\Http\Requests\User\SaveRole as SaveRoleRequest; class UserController extends Controller { public function listGroups() { $this->authorize('manage', Group::class); $tree = auth()->user()->getTreeAllGroups(['users', 'roles', 'descendants.users']); return view('user.listGroups', compact('tree')); } public function addGroup() { $this->authorize('manage', Group::class); $user = auth()->user(); $tree = $user->getTreeAllGroups(); $permissions = $user->group->permissions; $lifetimes = config('smart.users.groups.lifetimes'); return view('user.formGroup', compact('tree', 'permissions', 'lifetimes')); } public function editGroup(Group $group) { $this->authorize('edit', $group); $item = $group->load('permissions', 'users', 'ancestors'); $user = auth()->user(); $tree = $user->getTreeAllGroups(); $permissions = $user->group->permissions; $lifetimes = config('smart.users.groups.lifetimes'); return view('user.formGroup', compact('item', 'tree', 'permissions', 'lifetimes')); } public function saveGroup(SaveGroupRequest $request, Group $group) { $this->authorize('manage', Group::class); $data = $request->validated(); $attributes = array_only($data, ['name', 'active', 'lifetime']); if ( ! $group->exists ) { $parent = Group::find($data['parent_id']); $group = $parent->children()->create($attributes); } else { $group->update($attributes); } if (auth()->user()->can('groups', Permission::class)) { $perms = array_key_exists('perms', $data) ? array_keys($data['perms']) : []; $group->permissions()->sync($perms); } return redirect()->route('user.listGroups')->pnotify('Дані збережено', '','success'); } public function deleteGroup(Group $group) { $this->authorize('delete', $group); $group->delete(); return redirect()->route('user.listGroups')->pnotify('Групу видалено.', '','success'); } public function listUsers(Request $request) { $this->authorize('manage', User::class); $search = $request->get('search'); $filter_group = $request->get('filter_group'); $userGroups = auth()->user()->getAllGroups(); $userGroupsIds = $userGroups->pluck('id'); $query = User::query(); $query->with('group.ancestors', 'roles')->whereIn('group_id', $userGroupsIds); if( ! empty($search)) { $query->where(function($q) use($search){ $q->where('name', 'like', "%".$search."%"); $q->orWhere('email', 'like', "%".$search."%"); $q->orWhere('pib', 'like', "%".$search."%"); }); } ! empty($filter_group) ? $query->where('group_id', $filter_group) : false; $users = $query->paginate(User::PAGINATE_PER_PAGE); $userGroups->load('ancestors'); return view('user.listUsers', compact('users', 'userGroups', 'search', 'filter_group')); } public function addUser() { $this->authorize('manage', User::class); $groupsTree = auth()->user()->getTreeAllGroups(); return view('user.formUser', compact('groupsTree')); } public function editUser(User $user) { $this->authorize('edit', $user); $item = $user->load('roles', 'group.roles'); $groupsTree = auth()->user()->getTreeAllGroups(); return view('user.formUser', compact('item', 'groupsTree')); } public function saveUser(SaveUserRequest $request, User $user) { $this->authorize('manage', User::class); $data = $request->validated(); $user->fill($data); $user->save(); $roles = array_key_exists('roles', $data) ? $data['roles'] : []; $user->roles()->sync($roles); return redirect()->route('user.listUsers')->pnotify('Дані збережено', '','success'); } public function deleteUser(User $user) { $this->authorize('delete', $user); $user->delete(); return redirect()->route('user.listUsers')->pnotify('Користувача видалено.', '','success'); } public function listRoles(Request $request) { $this->authorize('manage', Role::class); $search = $request->get('search'); $filter_group = $request->get('filter_group'); $userGroups = auth()->user()->getAllGroups(); $userGroupsIds = $userGroups->pluck('id'); $query = Role::query(); $query->with('group.ancestors','users')->whereIn('group_id', $userGroupsIds); ! empty($search) ? $query->where('name', 'like', "%".$search."%") : false; ! empty($filter_group) ? $query->where('group_id', $filter_group) : false; $roles = $query->paginate(Role::PAGINATE_PER_PAGE); ! empty($search) ? $roles->appends(compact('search')) : false; ! empty($filter_group) ? $roles->appends(compact('filter_group')) : false; $userGroups->load('ancestors'); return view('user.listRoles', compact('roles', 'userGroups', 'search', 'filter_group')); } public function addRole() { $this->authorize('manage', Role::class); $groupsTree = auth()->user()->getTreeAllGroups(); return view('user.formRole', compact('groupsTree')); } public function saveRole(SaveRoleRequest $request, Role $role) { $this->authorize('manage', Role::class); $data = $request->validated(); $role->fill($data); $role->save(); $perms = array_key_exists('perms', $data) ? array_keys($data['perms']) : []; $role->permissions()->sync($perms); return redirect()->route('user.listRoles')->pnotify('Успіх', 'Дані збережено', 'success'); } public function editRole(Role $role) { $this->authorize('edit', $role); $item = $role->load('group.permissions'); $groupsTree = auth()->user()->getTreeAllGroups(); return view('user.formRole', compact('item', 'groupsTree')); } public function deleteRole(Role $role) { $this->authorize('delete', $role); $role->delete(); return redirect()->route('user.listRoles')->pnotify('Успіх', 'Роль видалено.','success'); } public function getPerms(Group $group, Role $role) { $group->load('permissions'); $permissions = $group->permissions; $item = $role->load('permissions'); return view('user.checkboxesPermissions', compact('permissions', 'item')); } public function getRoles(Group $group) { $group->load('roles'); $roles = $group->roles; return view('user.selectRoles', compact('roles')); } }
package org.wuuijkl.wrpc.server; import junit.framework.TestCase; import org.wuuijkl.wrpc.Request; import org.wuuijkl.wrpc.ServiceDescriptor; import org.wuuijkl.wrpc.utils.ReflectionUtils; import java.lang.reflect.Method; public class ServiceManagerTest extends TestCase { ServiceManager sm = new ServiceManager(); public void testRegister() { TestInterface bean = new Test1Class(); sm.register(TestInterface.class, bean); } public void testLookup() { TestInterface bean = new Test1Class(); sm.register(TestInterface.class, bean); Method method = ReflectionUtils.getPublicMethods(TestInterface.class).get(0); ServiceDescriptor sdp = ServiceDescriptor.from(TestInterface.class, method); Request request = new Request(); request.setService(sdp); ServiceInstance sis = sm.lookup(request); assertNotNull(sis); } }
import 'package:gbuagenda/utils/colours.dart'; import 'package:gbuagenda/utils/theme_data.dart'; import 'package:flutter/material.dart'; class ClassChip extends StatelessWidget { final String text; const ClassChip({this.text}); @override Widget build(BuildContext context) { if (text == "G-0") { return Container(); } else { return Padding( padding: const EdgeInsets.symmetric(horizontal: 6.0), child: ClipRRect( borderRadius: BorderRadius.circular(8.0), child: Container( color: Colours.chips, child: Padding( padding: const EdgeInsets.all(6.0), child: Text( text, style: theme.textTheme.headline6.copyWith( color: Colours.accent, fontWeight: FontWeight.w900, ), ), ), ), ), ); } } }
#!/bin/ash # # If we have key's then import them # export GNUPGHOME=/opt/fileserver/gpg KEYRING=$GNUPGHOME/secring.gpg KEYS=/opt/fileserver/keys SECRET=$KEYS/secret.gpg PUBLIC=$KEYS/public.gpg if [ -d "$KEYS" -a -f "$SECRET" -a -f "$PUBLIC" ] then mkdir -p $GNUPGHOME chmod 700 $GNUPGHOME if [ ! -f "$KEYRING" ] then echo "Importing keys" gpg --import --yes "$SECRET" gpg --import --yes "$PUBLIC" gpg --list-keys # Notify dpkg filesystem extensions to enable signature support export SIGNING_ENABLED=true fi fi
CREATE SCHEMA pov; CREATE LANGUAGE plperl; CREATE LANGUAGE plpgsql; \i sql/schema/pov/functions/_format_type.sql \i sql/schema/pov/functions/tsort.pl \i sql/schema/pov/views/pg_all_objects_unique_columns.sql \i sql/schema/pov/views/pg_depend_remapped.sql \i sql/schema/pov/views/pg_depend_oid_concat.sql \i sql/schema/pov/views/pg_depend_dot.sql \i sql/schema/pov/views/pg_depend_tsort.sql \i sql/schema/pov/views/pg_depend_definitions.sql -- Dependency level 1 (directly under public schema:) CREATE TABLE t1 ( id integer, PRIMARY KEY (id) ); CREATE FUNCTION f1 ( integer ) RETURNS boolean AS $$ SELECT $1 > 1; $$ LANGUAGE sql; CREATE SEQUENCE s1; -- Dependency level 2: CREATE TABLE t2 ( id integer, PRIMARY KEY (id), FOREIGN KEY (id) REFERENCES t1(id) ); CREATE TABLE t3 ( id integer not null default nextval('s1'), PRIMARY KEY (id), CHECK(f1(id)) ); -- Dependency level 3: CREATE VIEW v1 AS SELECT * FROM t1; CREATE VIEW v2 AS SELECT * FROM t2; -- Dependency level 4: CREATE VIEW v3 AS SELECT v1.id AS id1, v2.id AS id2 FROM v1, v2; -- Dependency level 5: CREATE VIEW v4 AS SELECT *, f1(id1) FROM v3;
namespace RD.CanMusicMakeYouRunFaster.FakeResponseServer.UnitTests.ControllerTests { using NUnit.Framework; using FakeResponseServer.Controllers; using FluentAssertions; using System.Collections.Generic; using System; using DbContext; using Microsoft.EntityFrameworkCore; using System.Linq; using RD.CanMusicMakeYouRunFaster.FakeResponseServer.DTO.Request; public class LastFMMusicControllerTests { private LastFMMusicController sut; private readonly List<DTO.LastTrack> listeningHistory = new List<DTO.LastTrack>(); private readonly Models.LastFM.LastTrack item1 = new Models.LastFM.LastTrack { AlbumName = "Some Album Name", ArtistImages = new Models.LastFM.LastImageSet() { Small = new Uri("http://localhost/Small"), Medium = new Uri("http://localhost/Medium"), Large = new Uri("http://localhost/Large"), ExtraLarge = new Uri("http://localhost/XL"), Mega = new Uri("http://localhost/Mega"), }, ArtistMbid = "123456789", ArtistName = "Some Artist", ArtistUrl = new Uri("http://localhost/ArtistURI"), Duration = new TimeSpan(0, 2, 30), Id = "23456789", Images = new Models.LastFM.LastImageSet { Small = new Uri("http://localhost/Small1"), Medium = new Uri("http://localhost/Medium1"), Large = new Uri("http://localhost/Large1"), ExtraLarge = new Uri("http://localhost/XL1"), Mega = new Uri("http://localhost/Mega1"), }, IsLoved = true, IsNowPlaying = false, ListenerCount = 1500, Mbid = "3456789", Name = "Some Track", PlayCount = 300, Rank = 1, TimePlayed = DateTime.UtcNow, TopTags = new List<Models.LastFM.LastTag>(), Url = new Uri("http://localhost/TrackURI"), UserPlayCount = 20 }; private readonly Models.LastFM.LastTrack item2 = new Models.LastFM.LastTrack { AlbumName = "Some Album Name 2", ArtistImages = new Models.LastFM.LastImageSet() { Small = new Uri("http://localhost/Small2"), Medium = new Uri("http://localhost/Medium2"), Large = new Uri("http://localhost/Large2"), ExtraLarge = new Uri("http://localhost/XL2"), Mega = new Uri("http://localhost/Mega2"), }, ArtistMbid = "abcdefghi", ArtistName = "Some Artist 2", ArtistUrl = new Uri("http://localhost/ArtistURI2"), Duration = new TimeSpan(0, 3,0), Id = "bcdefghij", Images = new Models.LastFM.LastImageSet { Small = new Uri("http://localhost/Small3"), Medium = new Uri("http://localhost/Medium3"), Large = new Uri("http://localhost/Large3"), ExtraLarge = new Uri("http://localhost/XL3"), Mega = new Uri("http://localhost/Mega3"), }, IsLoved = false, IsNowPlaying = true, ListenerCount = 53478763, Mbid = "cdefghijk", Name = "Some Track 2", PlayCount = 573847389, Rank = 2, TimePlayed = DateTime.UtcNow, TopTags = new List<Models.LastFM.LastTag>(), Url = new Uri("http://localhost/TrackURI2"), UserPlayCount = 30, }; private readonly Models.LastFM.LastTrack item3 = new Models.LastFM.LastTrack { AlbumName = "Some Album Name 3", ArtistImages = new Models.LastFM.LastImageSet() { Small = new Uri("http://localhost/Small4"), Medium = new Uri("http://localhost/Medium4"), Large = new Uri("http://localhost/Large4"), ExtraLarge = new Uri("http://localhost/XL4"), Mega = new Uri("http://localhost/Mega4"), }, ArtistMbid = "1a2b3c4d5e", ArtistName = "Some Artist 3", ArtistUrl = new Uri("http://localhost/ArtistURI3"), Duration = new TimeSpan(0, 6, 0), Id = "cdefghijkl", Images = new Models.LastFM.LastImageSet { Small = new Uri("http://localhost/Small5"), Medium = new Uri("http://localhost/Medium5"), Large = new Uri("http://localhost/Large5"), ExtraLarge = new Uri("http://localhost/XL5"), Mega = new Uri("http://localhost/Mega5"), }, IsLoved = false, IsNowPlaying = true, ListenerCount = 53478763, Mbid = "cdefghijk", Name = "Some Track 3", PlayCount = 573847389, Rank = 2, TimePlayed = DateTime.UtcNow, TopTags = new List<Models.LastFM.LastTag>(), Url = new Uri("http://localhost/TrackURI3"), UserPlayCount = 30, }; private readonly DTO.LastTrack DTOItem1 = new DTO.LastTrack { AlbumName = "Some Album Name", ArtistImages = new DTO.LastImageSet() { Small = new Uri("http://localhost/Small"), Medium = new Uri("http://localhost/Medium"), Large = new Uri("http://localhost/Large"), ExtraLarge = new Uri("http://localhost/XL"), Mega = new Uri("http://localhost/Mega"), }, ArtistMbid = "123456789", ArtistName = "Some Artist", ArtistUrl = new Uri("http://localhost/ArtistURI"), Duration = new TimeSpan(0, 2, 30).Ticks, Id = "23456789", Images = new DTO.LastImageSet { Small = new Uri("http://localhost/Small1"), Medium = new Uri("http://localhost/Medium1"), Large = new Uri("http://localhost/Large1"), ExtraLarge = new Uri("http://localhost/XL1"), Mega = new Uri("http://localhost/Mega1"), }, IsLoved = true, IsNowPlaying = false, ListenerCount = 1500, Mbid = "3456789", Name = "Some Track", PlayCount = 300, Rank = 1, TimePlayed = DateTime.UtcNow, TopTags = null, Url = new Uri("http://localhost/TrackURI"), UserPlayCount = 20 }; private readonly DTO.LastTrack DTOItem2 = new DTO.LastTrack { AlbumName = "Some Album Name 2", ArtistImages = new DTO.LastImageSet() { Small = new Uri("http://localhost/Small2"), Medium = new Uri("http://localhost/Medium2"), Large = new Uri("http://localhost/Large2"), ExtraLarge = new Uri("http://localhost/XL2"), Mega = new Uri("http://localhost/Mega2"), }, ArtistMbid = "abcdefghi", ArtistName = "Some Artist 2", ArtistUrl = new Uri("http://localhost/ArtistURI2"), Duration = new TimeSpan(0, 3, 0).Ticks, Id = "bcdefghij", Images = new DTO.LastImageSet { Small = new Uri("http://localhost/Small3"), Medium = new Uri("http://localhost/Medium3"), Large = new Uri("http://localhost/Large3"), ExtraLarge = new Uri("http://localhost/XL3"), Mega = new Uri("http://localhost/Mega3"), }, IsLoved = false, IsNowPlaying = true, ListenerCount = 53478763, Mbid = "cdefghijk", Name = "Some Track 2", PlayCount = 573847389, Rank = 2, TimePlayed = DateTime.UtcNow, TopTags = null, Url = new Uri("http://localhost/TrackURI2"), UserPlayCount = 30, }; private readonly DTO.LastTrack DTOItem3 = new DTO.LastTrack { AlbumName = "Some Album Name 3", ArtistImages = new DTO.LastImageSet() { Small = new Uri("http://localhost/Small4"), Medium = new Uri("http://localhost/Medium4"), Large = new Uri("http://localhost/Large4"), ExtraLarge = new Uri("http://localhost/XL4"), Mega = new Uri("http://localhost/Mega4"), }, ArtistMbid = "1a2b3c4d5e", ArtistName = "Some Artist 3", ArtistUrl = new Uri("http://localhost/ArtistURI3"), Duration = new TimeSpan(0, 6, 0).Ticks, Id = "cdefghijkl", Images = new DTO.LastImageSet { Small = new Uri("http://localhost/Small5"), Medium = new Uri("http://localhost/Medium5"), Large = new Uri("http://localhost/Large5"), ExtraLarge = new Uri("http://localhost/XL5"), Mega = new Uri("http://localhost/Mega5"), }, IsLoved = false, IsNowPlaying = true, ListenerCount = 53478763, Mbid = "cdefghijk", Name = "Some Track 3", PlayCount = 573847389, Rank = 2, TimePlayed = DateTime.UtcNow, TopTags = null, Url = new Uri("http://localhost/TrackURI3"), UserPlayCount = 30, }; private DbContextOptions<DataRetrievalContext> contextOptions; [OneTimeSetUp] public void SetUp() { contextOptions = new DbContextOptionsBuilder<DataRetrievalContext>() .UseInMemoryDatabase("LastFMMusicControllerTestDatabase") .Options; using var context = new DataRetrievalContext(contextOptions); var now = DateTime.UtcNow; item1.TimePlayed = now.AddDays(-2); item2.TimePlayed = now.AddDays(-3); item3.TimePlayed = now; DTOItem1.TimePlayed = now.AddDays(-2); DTOItem2.TimePlayed = now.AddDays(-3); DTOItem3.TimePlayed = now; listeningHistory.Add(DTOItem1); listeningHistory.Add(DTOItem2); listeningHistory.Add(DTOItem3); context.LastTracks.Add(item1); context.LastTracks.Add(item2); context.LastTracks.Add(item3); context.SaveChanges(); } [Test] public void GetRecentTracks_MusicHistoryReturned() { sut = new LastFMMusicController(new DataRetrievalContext(contextOptions)); var request = new LastFMGetRecentTracksRequest { ApiKey = "some API key", User = "RD" }; var getResult = sut.GetRecentTracks(request); var retrievedTracks = getResult.Result.Content.ToList(); retrievedTracks.Should().HaveCount(3); retrievedTracks.Should().BeEquivalentTo(listeningHistory); } [Test] public void GetRecentTracksWithAfterParam_MusicHistoryReturned() { var after = DateTime.UtcNow.AddDays(-1); var afterAsUnix = ((DateTimeOffset)after).ToUnixTimeMilliseconds(); var request = new LastFMGetRecentTracksRequest { ApiKey = "some API key", User = "RD", From = afterAsUnix }; sut = new LastFMMusicController(new DataRetrievalContext(contextOptions)); var getResult = sut.GetRecentTracks(request); var retrievedTracks = getResult.Result.Content.ToList(); retrievedTracks.Should().HaveCount(1); retrievedTracks.Should().NotBeEquivalentTo(listeningHistory); retrievedTracks[0].Should().BeEquivalentTo(DTOItem3); } [Test] public void GetRecentTracksWithNullParams_EmptyResponseReturned() { var request = new LastFMGetRecentTracksRequest { ApiKey = null, User = null, From = null }; sut = new LastFMMusicController(new DataRetrievalContext(contextOptions)); var getResult = sut.GetRecentTracks(request); getResult.Result.Content.Should().BeNull(); } [Test] public void GetRecentTracksWithEmptyParams_EmptyResponseReturned() { var request = new LastFMGetRecentTracksRequest { ApiKey = string.Empty, User = string.Empty, From = null }; sut = new LastFMMusicController(new DataRetrievalContext(contextOptions)); var getResult = sut.GetRecentTracks(request); getResult.Result.Content.Should().BeNull(); } } }
public class ClaseBoolean{ public static void main(String[] args) { // Valores de true y false Boolean positivo = Boolean.TRUE; Boolean negativo = Boolean.FALSE; // COMPUERTAS LOGICAS System.out.println("true and false = "+ Boolean.logicalAnd(positivo, negativo)); System.out.println("true and true = "+ Boolean.logicalAnd(positivo, positivo)); System.out.println("true and false = "+Boolean.logicalOr(positivo, negativo)); System.out.println("true and true = "+Boolean.logicalOr(positivo, positivo)); System.out.println("true and false = "+Boolean.logicalXor(positivo, negativo)); System.out.println("true and true = "+Boolean.logicalXor(positivo, positivo)); } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.OData.Query; using school_management_system_API.Models; using school_management_system_API.Services; using System; namespace school_management_system_API.Controllers { [EnableCors("AllowAll")] public class AddressController : BaseController { private readonly AddressService _addressService; public AddressController(AddressService studentService) { this._addressService = studentService; } [HttpGet] [EnableQuery] public ActionResult Get() { return Ok(_addressService.GetAll()); } [HttpGet] [Route("[controller]/{key}")] [Route("[controller]({key})")] public ActionResult GetById(int key) { var result = _addressService.GetById(key); if (result.Failure) return BadRequest(result.Error); return Ok(result.Value); } [HttpPost] public ActionResult Post([FromBody]AddressBase address) { if(!ModelState.IsValid) return BadRequest(); var result = _addressService.Create(address); if (result.Failure) return BadRequest(result.Error); return Created(new Uri($"{Request.Path}/{result.Value.Id}", UriKind.Relative), result.Value); } [HttpPut] [Authorize] public ActionResult Put([FromBody] AddressBase address, int key) { if (!ModelState.IsValid) return BadRequest(); address.Id = key; var result = _addressService.Update(address, SchoolId); if (result.Failure) return BadRequest(result.Error); return Ok(); } [HttpDelete] [Authorize] public ActionResult Delete( int key) { if (!ModelState.IsValid) return BadRequest(); var result = _addressService.RemoveById(key, SchoolId); if (result.Failure) return BadRequest(result.Error); return NoContent(); } } }
require_relative '../../../automated_init' context "Equality" do context "Attribute List" do context "Map" do context "Equal" do control = Schema::Controls::Schema.example compare = Schema::Controls::Schema::Equivalent.example control_name = :some_other_attribute compare_name = :yet_another_attribute map = [ { control_name => compare_name } ] fixture = Equality.build(control, compare, map, ignore_class: true) fixture.() context "Classes are the same" do tested = fixture.test_session.test?('Classes are the same') test "Not tested" do refute(tested) end end context "some_other_attribute => yet_another_attribute" do passed = fixture.test_session.test_passed?('some_other_attribute => yet_another_attribute') test "Passed" do assert(passed) end end context "some_attribute" do tested = fixture.test_session.test?('some_attribute') test "Not tested" do refute(tested) end end end end end end
#!/bin/bash # (C) Copyright NuoDB, Inc. 2017-2018 # # This source code is licensed under the MIT license found in the LICENSE # file in the root directory of this source tree. export NUOCA_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" export LOGSTASH_HOME=${NUOCA_HOME}/extern/logstash export NUODB_AGENTPORT=48004 export NUODB_DOMAIN_PASSWORD=bird if [ -d ${NUOCA_HOME}/python ]; then export PATH=${NUOCA_HOME}/python/bin:${PATH} export PYTHONHOME=${NUOCA_HOME}/python:${NUOCA_HOME}/python/x86_64-linux fi export PATH=${PATH}:${NUOCA_HOME}/extern/zabbix/bin export PYTHONPATH=${NUOCA_HOME}/pynuoca:${NUOCA_HOME}:${NUOCA_HOME}/lib:${NUODB_ROOT}/drivers/pynuoadmin export NUOADMINAGENTLOGCONFIG=${NUOCA_HOME}/etc/logstash/nuoadminagentlog.conf
import * as React from 'react'; import { Button } from '../../../common/button/button'; import { generateKeyPair, KeyPairData } from '../../../../lib/keygen'; import { P } from '../../../common/typography/typography'; import styles from './keypair-generator.module.scss'; interface KeyPairGeneratorState { generated: boolean; keypairData?: KeyPairData; } function getFormattedData(keypairData: KeyPairData): string { const { phrase, publicKey, testnetAddress, mainnetAddress } = keypairData; return `Mnemonic phrase: ${phrase} Public key (hex): ${publicKey} Testnet address (SS58): ${testnetAddress} Mainnet address (SS58): ${mainnetAddress} `; } export const KeyPairGenerator: React.FC = () => { const [results, setResults] = React.useState<KeyPairGeneratorState>({ generated: false, }); const handleClick = () => { const keypairData = generateKeyPair(); setResults({ generated: true, keypairData, }); }; const handleReset = () => { setResults({ generated: false, keypairData: undefined, }); }; if (results.generated) { return ( <> <div className={styles.infoBox}> <pre>{getFormattedData(results.keypairData)}</pre> </div> <P> <strong> You've generated a public key and mnemonic. Save the mnemonic to a secure offline location! <br /> If you don't remember your mnemonic, you won't be able to claim your EDG. </strong> </P> <Button onClick={handleReset} style="secondary"> Start over </Button> </> ); } return ( <div> <Button onClick={handleClick}>Generate key pair</Button> </div> ); };
import { Dimensions } from "react-native"; const Dim = { WindowWidth : Dimensions.get('window').width, WindowHeight : Dimensions.get('window').height, ScreenWidth : Dimensions.get('screen').width, ScreenHeight : Dimensions.get('screen').height } export default Dim;
import { PlatformConfig } from "homebridge"; type RuleSet = { path: string; value: string; }; type Filter = RuleSet[]; export interface JellyfinSensor { name: string; filters: Filter[]; // Added by extend config uuid: string; sn: string; } export interface JellyfinServer { port: number; address: string; api_key: string; checkInterval: number; } export interface JellyfinConfig extends PlatformConfig { server: JellyfinServer; sensors: JellyfinSensor[]; } type RemoteTrailer = { Url: string; Name: string; }; type ExternalUrl = { Url: string; Name: string; }; type NowPlayingItem = { Name: string; ServerId: string; Id: string; DateCreated: string; HasSubtitles: boolean; Container: string; PremiereDate: string; ExternalUrls: ExternalUrl[]; Path: string; EnableMediaSourceDisplay: boolean; Overview: string; Taglines: unknown[]; Genres: unknown[]; CommunityRating: number; RunTimeTicks: number; ProductionYear: number; IndexNumber: number; ParentIndexNumber: number; ProviderIds: { Tvdb: string; Imdb: string; }; IsHD: boolean; IsFolder: boolean; ParentId: string; Type: "Episode" | string; Studios: unknown[]; GenreItems: unknown[]; ParentBackdropItemId: string; ParentBackdropImageTags: string[]; LocalTrailerCount: number; SeriesName: string; SeriesId: string; SeasonId: string; SpecialFeatureCount: number; PrimaryImageAspectRatio: number; SeriesPrimaryImageTag: string; SeasonName: string; VideoType: "VideoFile" | string; ImageTags: { Primary: string; }; BackdropImageTags: []; ScreenshotImageTags: []; ImageBlurHashes: { [key: string]: { [key: string]: string }; }; SeriesStudio: string; Chapters?: { StartPositionTicks: number; Name: string; ImageDateModified: string; }[]; LocationType: "FileSystem" | string; MediaType: "Video" | string; Width: number; Height: number; }; type FullNowPlayingItem = { SpecialFeatureIds: unknown[]; LocalTrailerIds: unknown[]; RemoteTrailerIds: unknown[]; TmdbCollectionName?: string; AdditionalParts: unknown[]; LocalAlternateVersions: unknown[]; LinkedAlternateVersions: unknown[]; SubtitleFiles: string[]; HasSubtitles: boolean; IsPlaceHolder: boolean; DefaultVideoStreamIndex: 0 | number; VideoType: "VideoFile" | string; Size: number; Container: string; DateLastSaved: string; RemoteTrailers: RemoteTrailer[]; IsHD: boolean; IsShortcut: boolean; Width: number; Height: number; ExtraIds: unknown[]; SupportsExternalTransfer: boolean; }; export type JellyfinSession = { PlayState: { CanSeek: boolean; IsPaused: boolean; IsMuted: boolean; RepeatMode: "RepeatNone" | string; }; AdditionalUsers: unknown[]; Capabilities: { PlayableMediaTypes: unknown[]; SupportedCommands: unknown[]; SupportsMediaControl: boolean; SupportsContentUploading: boolean; SupportsPersistentIdentifier: boolean; SupportsSync: boolean; }; RemoteEndPoint: string; PlayableMediaTypes: unknown[]; Id: string; Client: string; LastActivityDate: string; LastPlaybackCheckIn: string; DeviceName: string; DeviceId: string; ApplicationVersion: string; IsActive: boolean; SupportsMediaControl: boolean; SupportsRemoteControl: boolean; HasCustomDeviceName: boolean; ServerId: string; SupportedCommands: unknown[]; FullNowPlayingItem?: FullNowPlayingItem; NowPlayingItem?: NowPlayingItem; };
% vim: ft=prolog % typing relies on occurs check :- set_prolog_flag(occurs_check, true). % name(x) is variable reference % proc(x, b) is λx.b (i.e., function with parameter x and body b) % func(t1, t2) is the function type t1 → t2 % invoke(f, a) is f of a (i.e., f applied to a) % % for cleaner syntax, use % :- op(700, xfy, ->). % t1 -> t2 replaces func(t1, t2) % :- op(900, xfx, :). % x : t replaces type/2, type(x, t) % :- op(910, xfx, =>). % Env => x : t replaces type/3, type(Env, x, t). % :- op(920, xfx, in_env). % x in_env Env replaces in_env(x, Env). % :- op(300, yfx, $). % f $ x replaces invoke(f, a). in_env(X, [X|_]) :- !. % only keep the first occurrence, no backtracking in_env(X, [_|L]) :- in_env(X, L). type(Env, name(X), T) :- in_env(type(X, T), Env). % !. % see cut in in_env: only first occurrence, no backtracking type(Env, proc(X, B), func(T1, T2)) :- type([type(X, T1) | Env], B, T2). type(Env, invoke(F, A), Tresult) :- type(Env, F, func(Targ, Tresult)), type(Env, A, Targ). type(Env, pair(A, B), tuple(Ta, Tb)) :- type(Env, A, Ta), type(Env, B, Tb). type(Env, first(X), T) :- type(Env, X, tuple(T, _)). type(Env, second(X), T) :- type(Env, X, tuple(_, T)). % base rules % unit value type(_, (/), unit). % explicit type markers type(Env, as(X, T), T) :- type(Env, X, T). type(Env, zerop(X), bool) :- type(Env, X, int). type(Env, if(Test, Consequent, Alternate), T) :- type(Env, Test, bool), type(Env, Consequent, T), type(Env, Alternate, T). % type(_, X, int) :- X in inf..sup. type(_, 0, int). % shorthands type(_, 1, int). type(_, 2, int). type(_, 3, int). type(_, 4, int). type(_, 5, int). type(_, 6, int). type(_, 7, int). type(_, 8, int). type(_, 9, int). type(_, 10, int). type(Env, add1(X), int) :- type(Env, X, int). type(Env, -(X, Y), int) :- type(Env, X, int), type(Env, Y, int). type(_, nil, list(_)). type(Env, cons(Head, Tail), list(T)) :- type(Env, Head, T), type(Env, Tail, list(T)). type(Env, nilp(L), bool) :- type(Env, L, list(_)). type(Env, head(L), T) :- type(Env, L, list(T)). type(Env, tail(L), list(T)) :- type(Env, L, list(T)).
<# Upload user interested file as additional log information to the current timeline record. The file shall be available for download along with task logs. ##vso[task.uploadfile]local file path Example: ##vso[task.uploadfile]c:\additionalfile.log #>
// Copyright 2013 Traceur Authors. // // 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. import { ARGUMENTS, THIS } from '../syntax/PredefinedName.js'; import {AlphaRenamer} from './AlphaRenamer.js'; import {FindInFunctionScope} from './FindInFunctionScope.js'; /** * This is used to find whether a function contains a reference to 'this' or * 'arguments'. */ class FindThisOrArguments extends FindInFunctionScope { constructor() { super(); this.foundThis = false; this.foundArguments = false; } visitThisExpression(tree) { this.foundThis = true; this.found = this.foundArguments; } visitIdentifierExpression(tree) { if (tree.identifierToken.value === ARGUMENTS) { this.foundArguments = true; this.found = this.foundThis; } } } export default function alphaRenameThisAndArguments(tempVarTransformer, tree) { var finder = new FindThisOrArguments(); finder.visitAny(tree); if (finder.foundArguments) { var argumentsTempName = tempVarTransformer.addTempVarForArguments(); tree = AlphaRenamer.rename(tree, ARGUMENTS, argumentsTempName); } if (finder.foundThis) { var thisTempName = tempVarTransformer.addTempVarForThis(); tree = AlphaRenamer.rename(tree, THIS, thisTempName); } return tree; }
require 'spec_helper' RSpec.describe NewspaperWorks::TitleInfoPresenter do let(:solr_document) { SolrDocument.new(attributes) } let(:attributes) do { 'publication_id_ssi' => 'foo', 'publication_title_ssi' => 'bar' } end subject { Hyrax::NewspaperPagePresenter.new(solr_document, nil) } describe '#publication_id' do it 'returns the correct value' do expect(subject.publication_id).to eq 'foo' end end describe '#publication_title' do it 'returns the correct value' do expect(subject.publication_title).to eq 'bar' end end end
version=0.1.0 rm ./sender echo "🟩 Downloading agent" wget https://github.com/senderchan/go-sender/releases/download/v${version}/sender_${version}_Linux_x86_64.tar.gz tar -zxvf sender_${version}_Linux_x86_64.tar.gz rm -f sender_${version}_Linux_x86_64.tar.gz chmod +x ./sender mv -f ./sender /usr/bin echo "\n\n\n\n" echo "🟩 Agent version" sender-agent version echo "=====================================" echo "Sender agent cli install finish" echo 'run "sender" will create a config file in current dir' echo 'run "sender service" will create systemctl config file "sender.service" in "/etc/systemd/system/"' echo 'run "systemctl start sender" for start' echo "====================================="
module FrontendRescue class Error < StandardError def initialize(name, user_agent, message, trace, params) @trace = trace.split("\n") rescue [] @user_agent = user_agent @params = params || {} super "Uncaught #{name} Error: #{message}" end def backtrace ["User Agent: #{user_agent}"] + @params.map{|k, v| "#{k}: #{v}"} + @trace end def user_agent @user_agent end end end
<?php namespace TrackerBundle\Repository; use BlogBundle\Entity\Post; use Doctrine\ORM\EntityRepository; use TrackerBundle\Entity\Record; use TrackerBundle\Entity\RecordRepository; class DoctrineRecordRepository extends EntityRepository implements RecordRepository { /** * {@inheritdoc} */ public function save(Record $record) { $entityManager = $this->getEntityManager(); $entityManager->persist($record); $entityManager->flush($record); } /** * {@inheritdoc} */ public function list(): array { return $this->findAll(); } /** * {@inheritdoc} */ public function findById(int $id) { return $this->find($id); } /** * {@inheritdoc} */ public function findByPost(Post $post): array { return $this->findBy([ 'post' => $post ]); } }
// Created by Tommy Bazar. No rights reserved :) // Special credits go to : Temaran (compute shader tutorial), TheHugeManatee (original concept, supervision) // and Ryan Brucks (original raymarching code). #include "Rendering/RaymarchTypes.h" FString GetDirectionName(FCubeFace Face) { switch (Face) { case FCubeFace::XPositive: return FString("+X"); case FCubeFace::XNegative: return FString("-X"); case FCubeFace::YPositive: return FString("+Y"); case FCubeFace::YNegative: return FString("-Y"); case FCubeFace::ZPositive: return FString("+Z"); case FCubeFace::ZNegative: return FString("-Z"); default: return FString("Something went wrong here!"); } } FMajorAxes FMajorAxes::GetMajorAxes(FVector LightPos) { FMajorAxes RetVal; TArray<TTuple<FCubeFace, float>> FaceVector; for (int i = 0; i < 6; i++) { // Dot of position and face normal yields cos(angle) float Weight = FVector::DotProduct(FCubeFaceNormals[i], LightPos); // Need to make sure we go along the axis with a positive weight, not negative. Weight = (Weight > 0 ? Weight * Weight : 0); RetVal.FaceWeights.Add(MakeTuple(FCubeFace(i), Weight)); } // Sort so that the 3 major axes are the first. RetVal.FaceWeights.Sort([](const auto& A, const auto& B) { return A.Value > B.Value; }); return RetVal; }
node.default['rbenv']['rubies'] = [ '2.0.0-p247' ] node.default['rbenv']['gems'] = { '2.0.0-p247' => [ { 'name' => 'bundler' } ] }
<?php namespace App\Account\Services; use App\Account\Contracts\AccountCreatorable; use Illuminate\Support\Facades\Hash; class AccountCreator implements AccountCreatorable { /** * @param string $userName * @param string $userEmail * @param string $password * @param string $accountName * @return mixed * @throws \Exception */ public function createAccount(string $userName, string $userEmail, string $password, string $accountName) { try { $user = \App\User::create([ 'name' => $userName, 'email' => $userEmail, 'password' => Hash::make($password) ]); $account = \App\Account::create([ 'name' => $accountName ]); $user->accounts()->attach($account->id, ['is_owner' => true]); return $user; } catch (\Exception $e) { throw $e; } } }
import * as React from 'react'; import { SidebarStyle } from '../utils/styles'; type SidebarProps = { guilds: any[]; } export const Sidebar = (props: SidebarProps) => { return <SidebarStyle></SidebarStyle> }
# iView-project This project is build for Vue.js 2 + vue-router + webpack2 + iView 3, just install and run. ## Install ```bush // install dependencies npm install ``` ## Run ### Development ```bush // For the first time, run init to create index.html npm run init npm run dev ``` ### Production(Build) ```bush npm run build ``` ### 问题解决 ```bush mac电脑上运行前准备阶段会出现两个问题(简单记录,不排除个人原因): 1.npm ERR! iview-project@3.0.0 init: `webpack --progress --config webpack.dev.config.js 解决方法: fs.write(fd, buf, 0, buf.length, 0, function (err, written, buffer){}); 修改成 fs.write(fd, buf, 0, 'utf-8', function (err, written, buffer) {}) 2.gyp ERR! cwd /Users/bobo/j2ee/gitcodes/renren-fast-vue/node_modules/node-sass 解决方法: 先在package.json文件中的 dependencies 下配置: ... "node-sass":"^4.13.0" ... 然后: // 1、清除npm缓存(由于是在Mac系统下,执行npm cache clean --force命令时前面需要加sudo获取权限) sudo npm cache clean --force // 2、删除node_modules文件(也可手动删除node_modules文件夹) rm -rf node_modules // 3、重新执行安装 npm install ```
# Circuit - Repeat 3x 30sec Forearm Plank 30sec Hand Plank 30sec Mountain Climbers 30sec Bicycle Crunches 30sec Raised Toe Touches 30sec Russian Twists 30sec Crunches
<?php namespace GeneralServicer\View\Helper; use Zend\View\Helper\AbstractHelper; /** * $this calss displays a thumbnail for the uploaded documents * @author otaba * */ class GeneralUploadedDocThumbnailHelper extends AbstractHelper { public function __invoke($mimeType){ switch ($mimeType){ } } }
--- title: _unlock ms.date: 11/04/2016 api_name: - _unlock api_location: - msvcrt.dll - msvcr100.dll - msvcr110_clr0400.dll - msvcr110.dll - msvcr80.dll - msvcr120.dll - msvcr90.dll - msvcr120_clr0400.dll api_type: - DLLExport topic_type: - apiref f1_keywords: - unlock - _unlock helpviewer_keywords: - unlock function - _unlock function ms.assetid: 2eda2507-a134-4997-aa12-f2f8cb319e14 ms.openlocfilehash: 73eec2b05b1d321bfc8ac61e743459bf2323fb8e ms.sourcegitcommit: 7a6116e48c3c11b97371b8ae4ecc23adce1f092d ms.translationtype: MT ms.contentlocale: cs-CZ ms.lasthandoff: 04/22/2020 ms.locfileid: "81745106" --- # <a name="_unlock"></a>_unlock Uvolní zámek s více vlákny. > [!IMPORTANT] > Tato funkce je zastaralá. Počínaje Visual Studio 2015, není k dispozici v CRT. ## <a name="syntax"></a>Syntaxe ```cpp void __cdecl _unlock( int locknum ); ``` #### <a name="parameters"></a>Parametry *locknum*<br/> [v] Identifikátor zámku uvolnit. ## <a name="requirements"></a>Požadavky **Zdroj:** mlock.c ## <a name="see-also"></a>Viz také [Abecední seznam odkazů na funkce](../c-runtime-library/reference/crt-alphabetical-function-reference.md)<br/> [_lock](../c-runtime-library/lock.md)
// 2017-12-01 // Copyright (c) 2017 Nimzozo /** * Syntax highlighting for web languages. */ window.webCode = window.webCode || (function () { "use strict"; var codes = {}; /** * CSS class names and ids. */ var css = { attribute: "webCode-html-attribute", string: "webCode-html-string", tag: "webCode-html-tag", webCode: "webCode" }; /** * Regular expressions. */ var regExp = { htmlCloser: />/, htmlOpener: /</, html: /^<[^<>]>$/, htmlAttribute: /(&lt;\S+?\s)(\S+?)(=)/gm, htmlString: /(\s\S+?=)('.+?'|".+?")(\s|&gt;)/gm, htmlTag: /(<\/?)(\S+?)(\s|>)/ }; var replacement = { htmlAttribute: "$1<pre class=\"" + css.attribute + "\">$2</pre>$3", htmlString: "$1<pre class=\"" + css.string + "\">$2</pre>$3", htmlTag: "$1<pre class=\"" + css.tag + "\">$2</pre>$3" }; function parseFragment(str) { var fragment = ""; var fragments = []; var startIndex = 0; var strArray = str.split(""); if (regExp.html.test(str)) { var tags = regExp.htmlTag.exec(str); } else { return str; } } /** * Separate a string. * @param {string} str The string to separate. */ function separate(str) { var fragment = ""; var fragments = []; var startIndex = 0; var strArray = str.split(""); strArray.forEach(function (char, charIndex) { if (regExp.htmlOpener.test(char)) { fragment = str.substring(startIndex, charIndex); fragments.push(fragment); startIndex = charIndex; } else if (regExp.htmlCloser.test(char)) { fragment = str.substring(startIndex, charIndex + 1); fragments.push(fragment); startIndex = charIndex + 1; } else if (charIndex === str.length - 1) { fragment = str.substring(startIndex, charIndex + 1); fragments.push(fragment); } }); return fragments; } codes = document.getElementsByClassName(css.webCode); Object.keys(codes).forEach(function (key) { var code = codes[key]; var text = ""; var arr = separate(code.innerText); arr.forEach(function (str) { text += "[" + str + "]"; }); code.innerText = text; }); }());
#!/bin/bash # Security Test case # TC_CR2.1_1: Authorization enforcement # set -e . ../../lib/common-lib . ../../lib/common-variables TEST_CASE_NAME="TC_CR2.1_1: Authorization enforcement" preTest() { check_root check_pkgs_installed "sudo" # Create the users for the test case create_test_user $USER1_NAME $USER1_PSWD } runTest() { if ! echo "$USER1_PSWD" | su - $USER1_NAME -c "sudo -vknS"; then info_msg "User '$USER1_NAME' has no supervisor prvilieges" else error_msg "FAIL: Have already supervisor prvilieges" fi # provide supervisor prvilieges to the user if echo "$USER1_NAME ALL=(ALL:ALL) ALL" | sudo EDITOR='tee -a' visudo ; then info_msg "Provided supervisor prvilieges to the user '$USER1_NAME'" else error_msg "FAIL: cannot give supervisor prvilieges to the user '$USER1_NAME'" fi # access the file to check whether supervisor prvilieges gives if echo "$USER1_PSWD" | su - $USER1_NAME -c "echo '$USER1_PSWD' | sudo -vkS"; then info_msg "User $USER1_NAME has supervisor prvilieges" else error_msg "FAIL: Doesn't have supervisor prvilieges" fi info_msg "PASS" } postTest() { sed -i '/^'$USER1_NAME'/d' /etc/sudoers # delete the user created in the test del_user $USER1_NAME } # Main cmd="$1" case "$1" in "init") echo "" echo "preTest: $TEST_CASE_NAME" preTest ;; "run") echo "" echo "runTest: $TEST_CASE_NAME" runTest ;; "clean") echo "" echo "postTest: $TEST_CASE_NAME" postTest ;; esac
class XmcEndSystem { [string]$Policy [string]$FilterId [int]$LoginLatPort [string]$RegistrationType [string]$AuthenticationType [string]$HostName [string]$LastAssessmentHashCodeChangeTime [string]$StartAssessmentWarningTime [string]$AllAuthenticationTypes [string]$LastScanTime [IpAddress]$IpAddress [string]$Zone [string]$Class [string]$SwitchPort [string]$LastSeenTime [string]$Reason [string]$StateDescription [string]$ExtendedState [string]$Source [string]$TlsClientCertificateFingerprint [string]$MacAddress [string]$TlsClientCertificateIssuer [string]$LastQuarantineTime [string]$SwitchPortId [string]$OperatingSystem [string]$FirstSeenTime [string]$Username [string]$SiteId [IpAddress]$SwitchIp [int]$Id [string]$NacApplianceGroupName [IpAddress]$RadiusServerIp [string]$EsType [string]$LastAuthEventTime [string]$LocationInfo [string]$RequestAttributes [IpAddress]$NacApplianceIp [string]$TlsClientCertificateExpiration [string]$AssessmentHashCode [string]$NacProfileName [string]$LastScanResultState [string]$State # Ap Location Info [string]$ApMac [string]$ApName [string]$ApSerial [string]$InterfaceName [string]$InterfaceDescription [string]$InterfaceAlias [string]$Ssid #region initiators ################################################################################### # blank initiator XmcEndSystem() { } ################################################################################### #endregion initiators }
--- firstName: "diana" lastName: "kim" position: "guildmaster" order: 3 ---
'use strict'; (function(){ class RiskTableComponent { constructor($scope, Entry, Coverage, $filter, $timeout, $state) { $scope.entry = Entry; $scope.isDisabled = $scope.entry.isDisabled(); $scope.businessProcesses = []; $scope.risks = []; $scope.subRisks = []; $scope.selectedRisks = []; $scope._und = _; // Pagination $scope.pageSize = 20; $scope.currentPage = 1; $scope.setCurrentPage = function(currentPage) { $scope.currentPage = currentPage; }; Coverage.getRisks() .then(function(data){ $scope.risks = data; $scope.businessProcesses = _.map(_.groupBy(data, 'BUSINESS_PROCESS_ID'), function(g) { return { BUSINESS_PROCESS: _.reduce(g, function(m,x) { return x.BUSINESS_PROCESS; }, 0), BUSINESS_PROCESS_ID: _.reduce(g, function(m,x) { return x.BUSINESS_PROCESS_ID; }, 0), }; }); }); Coverage.getAllSubRisks() .then(function(data){ $scope.subRisks = data; }); $scope.removeAllFilters = function () { $scope.entry.searchRiskCatalogue = {}; }; $scope.removeFilter = function (element) { delete $scope.entry.searchRiskCatalogue[element]; if (_.size($scope.entry.searchRiskCatalogue) === 0) { $scope.entry.searchRiskCatalogue = {}; } }; $scope.setFilterBusinessProcess = function (businessProcesses) { if (businessProcesses) { $scope.entry.searchRiskCatalogue.BUSINESS_PROCESS = businessProcesses; } else { delete $scope.entry.searchRiskCatalogue.BUSINESS_PROCESS; } }; $scope.printSelected = function() { $scope.selectedRisks = _.filter($scope.risks, function(elem) { return elem.SELECTED == 'Y';}); }; $scope.removeSelected = function() { $scope.selectedRisks = _.filter($scope.risks, function(elem) { return elem.SELECTED == 'Y';}); $scope.selectedRisks.forEach(function(r) {r.SELECTED = 'N';}); $scope.selectedRisks = []; }; $scope.riskInfo = function(riskId, subProcessId) { $scope.removeSelected(); if (riskId) { $state.go('riskInfo', {riskId: riskId}, {reload: true}); } else { $state.go('riskInfo', {subProcessId: subProcessId}, {reload: true}); } }; $scope.getSubRisks = function(riskId) { return _.filter($scope.subRisks, function(e) {return e.RISK_ID == riskId;}); }; // Watch filter change var timer = false; var timeoutFilterChange = function(newValue, oldValue){ if(timer){ $timeout.cancel(timer); } timer = $timeout(function(){ $scope.loadFinished = false; // remove filters with blank values $scope.entry.searchRiskCatalogue = _.pick($scope.entry.searchRiskCatalogue, function(value, key, object) { return value !== '' && value !== null; }); if (_.size($scope.entry.searchRiskCatalogue) === 0) { //delete $scope.entry.searchRiskCatalogue; $scope.entry.searchRiskCatalogue = {}; } $scope.filteredRisks = $filter('filter') ($scope.risks, $scope.entry.searchRiskCatalogue); $scope.loadFinished = true; $scope.currentPage = 1; }, 400); }; $scope.$watch('entry.searchRiskCatalogue', timeoutFilterChange, true); } } angular.module('amxApp') .component('riskTable', { templateUrl: 'app/coverage/routes/riskTable/riskTable.html', controller: RiskTableComponent, controllerAs: 'riskTableCtrl' }); })();
namespace SoftJail.DataProcessor.ImportDto { using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; public class ImportDepartmentsCellsDTO { [Required] [JsonProperty("Name")] [MinLength(GlobalConstants.DepartmentNameMinLength)] [MaxLength(GlobalConstants.DepartmentNameMaxLength)] public string DepartmentName { get; set; } [JsonProperty("Cells")] public ImportCellDTO[] Cells { get; set; } } }
## German-Vocab app Backend (in Go) This German-Vocab app contains a list of words for my reference and learning. Made with GORM, JWT, PostgreSQL
# View helper for dashboard module DashboardsHelper # Renders the font icon depending on the project privacy state # @param [Project] project def project_icon(project) klass = ["icon"] klass << if project.privacy "icon-lock" else ["mini-icon", "mini-icon-public"] end content_tag :span, "", :class => klass.join(' ') end # Renders a badge with the number of open issues # @param [Project] project def issue_number(project) content_tag :span, project.issues.not_completed.count, :class => "issue-count badge" end end
require 'test_helper' class BackstackTest < ActionDispatch::IntegrationTest # My hackpologies, this is just dizzying. Hard to see patterns to # spot errors. def test_backstack_meandering # DRYer lambdas aback = lambda {|x| ['a#back[href=?]', x.to_s] } # testing backstack_link nolink = lambda {|x| ['#no_link_trail', x.to_s] } # testing backstack_trail get '/' assert_select 'a#back', :count => 0 # means no back link assert_select *nolink['Alpha'] get '/c2/c' assert_select *aback['/'] assert_select *nolink['Alpha / Charlie'] # testing clicky trail assert_select '#link_trail' do assert_select "a[href='/']", 'Alpha' end get '/c2/b' assert_select *aback['/'] assert_select *nolink['Alpha / Bravo'] get '/' assert_select 'a#back', :count => 0 assert_select *nolink['Alpha'] get '/c2/c' assert_select *aback['/'] assert_select *nolink['Alpha / Charlie'] get '/c3/f' assert_select *aback['/c2/c'] assert_select *nolink['Alpha / Charlie / Foxtrot'] # # testing backstack_ignore - shouldnt change above # backstack_ignore('ic1#ignore1') is set in application_controller.rb get '/ic1/ignore1' # assert_select *aback['/c2/c'] # back link disappears, is that ok? assert_select *nolink['Alpha / Charlie / Foxtrot'] # # testing backstack_ignore - *should* change above # backstack_ignore('ic2#ignore2') is not set in application_controller.rb get '/ic2/ignore2' # assert_select *aback['/c2/c'] # back link disappears, is that ok? assert_select *nolink['Alpha / Charlie / Ignore2'] # fix mess we made above get '/c3/f' assert_select *aback['/c2/c'] assert_select *nolink['Alpha / Charlie / Foxtrot'] # testing clicky trail assert_select '#link_trail' do assert_select "a[href='/']", 'Alpha' assert_select "a[href='/c2/c']", 'Charlie' end get '/c4/j' assert_select *aback['/c3/f'] assert_select *nolink['Alpha / Charlie / Foxtrot / Juliet'] get '/c4/i' assert_select *aback['/c3/f'] assert_select *nolink['Alpha / Charlie / Foxtrot / India'] get '/c4/h' assert_select *aback['/c3/f'] assert_select *nolink['Alpha / Charlie / Foxtrot / Hotel'] get '/c4/g' assert_select *aback['/c3/f'] assert_select *nolink['Alpha / Charlie / Foxtrot / Golf'] # testing clicky trail assert_select '#link_trail' do assert_select "a[href='/']", 'Alpha' assert_select "a[href='/c2/c']", 'Charlie' assert_select "a[href='/c3/f']", 'Foxtrot' end get '/c3/f' assert_select *aback['/c2/c'] assert_select *nolink['Alpha / Charlie / Foxtrot'] get '/c3/d' assert_select *aback['/c2/c'] assert_select *nolink['Alpha / Charlie / Delta'] get '/c3/e' assert_select *aback['/c2/c'] assert_select *nolink['Alpha / Charlie / Echo'] # testing clicky trail assert_select '#link_trail' do assert_select "a[href='/']", 'Alpha' assert_select "a[href='/c2/c']", 'Charlie' end get '/c2/c' assert_select *aback['/'] get '/' assert_select 'a#back', :count => 0 # means no back link assert_select *nolink['Alpha'] end end
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} -- There are edge cases that we don't need to consider module Day22 where import Control.Applicative (liftA2) import Control.DeepSeq (NFData (..), rwhnf) import Data.Bits (shiftL) import Data.Foldable (foldl', toList) import Data.Sequence (Seq (..), (|>)) import qualified Data.Sequence as Seq import qualified Data.Set as Set import Text.Megaparsec (endBy, many) import Text.Megaparsec.Char (digitChar, space) import qualified Text.Megaparsec.Char.Lexer as L import Advent.AoC data Game = Game !(Seq Int) !(Seq Int) deriving (Eq, Show) instance NFData Game where rnf = rwhnf data Player = Player1 | Player2 deriving (Show, Eq) parsePlayer :: Parser (Seq Int) parsePlayer = Seq.fromList <$> (("Player " *> digitChar <* ":\n") *> (L.decimal `endBy` "\n")) parseInput :: Parser Game parseInput = liftA2 Game (parsePlayer <* "\n") parsePlayer getInput :: FilePath -> IO Game getInput = parseFile parseInput -- For the "many" input where we're testing multiple games. getInputs :: FilePath -> IO [Game] getInputs = parseFile (many (L.lexeme space parseInput)) type KeyFun a = Game -> a play :: Ord a => KeyFun a -> Bool -> Game -> (Player, Seq Int) play kf recurse = go mempty where go _ (Game p1 Empty) = (Player1, p1) go _ (Game Empty p2) = (Player2, p2) go s game@(Game (p1 :<| p1s) (p2 :<| p2s)) | Set.member sk s = (Player1, Empty) | recurse && length p1s >= p1 && length p2s >= p2 = let p1deck' = Seq.take p1 p1s p2deck' = Seq.take p2 p2s maxp1 = maximum p1deck' maxp2 = maximum p2deck' in go s' $ case () of _ -- supercard, followed by recursion | maxp1 > maxp2 && maxp1 > (p1 + p2) -> awin | p1won $ go mempty (Game p1deck' p2deck') -> awin | otherwise -> bwin | p1 > p2 = go s' awin -- part1 awin | p2 > p1 = go s' bwin -- part1 bwin | otherwise = error "tie" where awin = Game (p1s |> p1 |> p2) p2s bwin = Game p1s (p2s |> p2 |> p1) p1won (Player1,_) = True p1won _ = False s' = Set.insert sk s -- Seems to work for many to just consider the first deck sk = kf game -- sk = foldl' (\o -> (+ ((shiftL o 5) + o))) 5381 p1deck score :: Seq Int -> Int score = sum . zipWith (*) [1..] . reverse . toList optfirst :: KeyFun Int optfirst (Game p1 _) = foldl' (\o -> (+ ((shiftL o 5) + o))) 5381 p1 {-# INLINE optfirst #-} optboth :: KeyFun Int optboth (Game p1 p2) = foldl' (\o -> (+ ((shiftL o 5) + o))) 5381 ((p1 :|> 0) <> p2) {-# INLINE optboth #-} optboth' :: KeyFun Int optboth' (Game p1 p2) = (`shiftL` 5) (foldl' (\o -> (+ ((shiftL o 5) + o))) 5381 p1) + foldl' (\o -> (+ ((shiftL o 5) + o))) 5381 p2 {-# INLINE optboth' #-} part1 :: Game -> Int part1 = score . snd . play optfirst False part2 :: Game -> Int part2 = score . snd . play optfirst True
import 'package:flutter/cupertino.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:schoolexam_correction_ui/blocs/language/language.dart'; typedef TranslationCallback = String Function(AppLocalizations dictionary); class LanguageCubit extends Cubit<LanguageState> { LanguageCubit() : super(LanguageState.initial()); /// Detects a possible language switch within the [context] and updates its state accordingly. Future<void> loadContext({required BuildContext context}) async { final localization = AppLocalizations.of(context); if (localization != null) { emit(state.copyWith(dictionary: localization)); } } String translate({required TranslationCallback callback}) => callback(state.dictionary); }
--- title: Bragg Edge post: "<i class='fa fa-battery-full'></i> " pre: "- " --- **Notebook name**: bragg_edge.ipynb ## Description ## Start the notebook If you need help accessing this notebook, check the [How To > Start the python notebooks](/en/tutorial/how_to_start_notebooks) tutorial. ## How to Use It? ### Select your IPTS Check the full tutorial [here]({{%relref "/tutorial/notebooks/select_ipts/_index.md#activate-search" %}})</i> ### loading the Normalized Images Select the **working folder**. All the
# Licenses ## Common Javascript MIT or Apache 2.0 ## Android version MIT or Apache 2.0 ## iOS/macOS version MIT only based on Phonegap-SQLitePlugin by @davibe (Davide Bertola <dade@dadeb.it>) and @joenoon (Joe Noon <joenoon@gmail.com>) ## Windows version MIT or Apache 2.0 ### SQLite3-WinRT by @doo (doo GmbH) MIT License ## SQLite3 Public domain
use prelude::*; /// MetaItem builder. pub struct MetaItemBuilder { node: Option<MetaItem>, } impl MetaItemBuilder { /// Create a metaitem builder. pub fn new() -> MetaItemBuilder { MetaItemBuilder { node: None } } /// Get meta words. pub fn get_words(&self) -> Vec<String> { let mut values = Vec::new(); if let MetaItemKind::List(ref inners) = self.node.as_ref().unwrap().node { for inner in inners { if let NestedMetaItemKind::MetaItem(ref inner) = inner.node { if let MetaItemKind::Word = inner.node { values.push(inner.name.to_string()); } } } } values } /// Get `NameValue`'s value. pub fn get_name_value(&self) -> Option<String> { if let MetaItemKind::NameValue(ref spanned) = self.node.as_ref().unwrap().node { if let LitKind::Str(ref value, _) = spanned.node { return Some(value.to_string()); } } None } /// Get meta name. pub fn get_name(&self) -> String { self.node.as_ref().unwrap().name.to_string() } } impl<'a> From<&'a MetaItem> for MetaItemBuilder { fn from(meta: &MetaItem) -> MetaItemBuilder { MetaItemBuilder { node: Some(meta.clone()) } } }
import * as React from "react"; import AdditionalAnswer from "./additional-answer"; import AnswerOptionText from "./answer-option-text"; import AnswerOptionSelect from "./answer-option-select"; import AnswerOptionMultiSelect from "./answer-option-multi-select"; import { QuestionType } from "./../utils/constants"; const Question = ({ question }: any) => { return ( <div className="question"> <div className="question-content"> <span>{question.order}. </span> {question.required && <span className="required-question"> * </span>} <span>{question.name}</span> </div> {question.questionType === QuestionType.Text && ( <AnswerOptionText question={question} /> )} {question.questionType === QuestionType.Select && ( <AnswerOptionSelect question={question} answerOptions={question.answerOptions} /> )} {question.questionType === QuestionType.MultiSelect && ( <AnswerOptionMultiSelect question={question} answerOptions={question.answerOptions} /> )} {question.additionalAnswer && <AdditionalAnswer question={question} />} </div> ); }; export default Question;
(ns Algorithms.PriorityQueue (:use [Algorithms.heap])) (defprotocol PriorityQueue (insert [Q val]) (peek [Q]) (pop [Q]) (set-val [Q idx val])) (defrecord MaxPriorityQueue [heap]) (extend-type MaxPriorityQueue PriorityQueue (insert [Q val] (MaxPriorityQueue. (max-heap-insert (:heap Q val)))) (peek [Q] (heap-max (:heap Q))) (pop [Q] (MaxPriorityQueue. (heap-extract-max (:heap Q)))) (set-val [Q idx val] (MaxPriorityQueue. (heap-increase-key (:heap Q) idx val)))) (defrecord MinPriorityQueue [heap]) (extend-type MinPriorityQueue PriorityQueue (insert [Q val] (MinPriorityQueue. (min-heap-insert (:heap Q val)))) (peek [Q] (heap-min (:heap Q))) (pop [Q] (MinPriorityQueue. (heap-extract-min (:heap Q)))) (set-val [Q idx val] (MinPriorityQueue. (heap-decrease-key (:heap Q) idx val))))
;;(ql:quickload :cl-telegram-bot) ;;(ql:quickload :utility) ;;;Architecture of the cl-telegram bot ;;;start a spin loop in a subthread which requests updates from Telegram, ;;;and dispatches on those updates. (defpackage #:the-bot (:use :cl :cl-telegram-util)) (in-package #:the-bot) ;;blindly coding ;;planned features: ;;persistence ;;multiple users ;;two-way communication. the bot can alert the person, the person can alert the bot ;;Initialize the lparallel library (setf lparallel:*kernel* (lparallel:make-kernel 2)) ;;The lparallel channel for asynchronously getting updates (defparameter *async-updates-channel* nil) ;;Initialize the device which runs functions at a constant rate in real-time (defparameter *ticker* nil) (defparameter *current-time* 0) (defun what-time (&optional (time (local-time:now))) (local-time:timestamp-to-unix time)) (defun start2 (&optional (token cl-telegram-bot::*token*)) (subthread (lambda () (start token)))) (defparameter *stop* t "Set this to t to stop the program.") (defun stop () (setf *stop* t)) (defparameter *update-queue* nil) (defun get-pending-updates () "Return the updates in the update queue as a list. The oldest updates come first in the queue, and also first in the list." (let ((update-objects nil)) (loop :named out :do (multiple-value-bind (value existsp) (lparallel.queue:try-pop-queue *update-queue*) (if existsp (push value update-objects) (return-from out)))) (values (nreverse update-objects)))) (defparameter *bot* nil) (defun start (&optional (token cl-telegram-bot::*token*)) (setf *stop* nil) (let ((*bot* (cl-telegram-bot::make-bot :token token)) (*async-updates-channel* (lparallel:make-channel)) (*ticker* ;;A ticker that ticks every 1 second. the second number does not correspond to seconds? (fps-independent-timestep:make-ticker 1 most-positive-fixnum 10)) (*update-queue* (lparallel.queue:make-queue))) ;;FIXME::this is here to empty lost time. Bug? (fps-independent-timestep::tick *ticker* ((what-time))) ;;Dummy task to start polling (lparallel:submit-task *async-updates-channel* (lambda () (make-task-return-type :initialize-dummy))) (loop (designate-polling-and-handle-updates *bot* *async-updates-channel* *ticker*) (when *stop* (return))))) (defun designate-polling-and-handle-updates (&optional (bot *bot*) (channel *async-updates-channel*) (ticker *ticker*)) (setf *current-time* (what-time)) ;;Run 'one-process-iteration' at a fixed rate. (fps-independent-timestep::tick ticker (*current-time*) (tick bot (get-pending-updates))) (multiple-value-bind (value existsp) (lparallel:try-receive-result channel) (when (and existsp value) (with-task-return-type (type value) value (ecase type ;;A get-updates task finished. Handle the recieved tasks, and ;;start polling for the next round (:get-updates (dolist (update-object value) (lparallel.queue:push-queue update-object *update-queue*)) (submit-get-updates-task)) ;;A dummy task is used to initialize the system. (:initialize-dummy (submit-get-updates-task))))))) (defun submit-get-updates-task (&optional (bot *bot*) (channel *async-updates-channel*)) "Create a task to asynchronously wait for updates from telegram, apart from the main bot thread." (lparallel:submit-task channel (lambda () (make-task-return-type :get-updates (mapcar 'create-update (cl-telegram-bot::get-updates bot :timeout 10)))))) (struct-to-clos:struct->class (defstruct update update_id type thing raw-data user)) (defmethod print-object ((update update) stream) (format stream "~%User:~a ~%Update ID:~a ~%Type:~a ~%Thing:~a" (update-user update) (update-update_id update) (update-type update) (update-thing update))) (defun create-update (update-data) (let ((type nil) (thing nil)) (block out ;;A telegram update has one of these types. (dolist (item '("message" "edited_message" "channel_post" "edited_channel_post" "inline_query" "chosen_inline_result" "callback_query" "shipping_query" "pre_checkout_query")) (multiple-value-bind (value existsp) (get-json-object-member update-data item) (when existsp (setf type item thing value) (return-from out))))) (let ((user (get-json-object-members* thing '("from" "id"))) (update_id (get-json-object-member update-data "update_id"))) (make-update :update_id update_id :type type :thing thing :raw-data update-data :user user)))) ;;;Above is general code, below is test code (defparameter *testcase* #+nil (:OBJ ("inline_keyboard" ((:OBJ ("text" . "A") ("callback_data" . "A1")) (:OBJ ("text" . "B") ("callback_data" . "C1")) (:OBJ ("text" . "B") ("callback_data" . "C1")) (:OBJ ("text" . "B") ("callback_data" . "C1")) (:OBJ ("text" . "B") ("callback_data" . "C1")) (:OBJ ("text" . "B") ("callback_data" . "C1")) (:OBJ ("text" . "B") ("callback_data" . "C1")) (:OBJ ("text" . "B") ("callback_data" . "C1")) (:OBJ ("text" . "B") ("callback_data" . "C1")) (:OBJ ("text" . "B") ("callback_data" . "C1")) (:OBJ ("text" . "B") ("callback_data" . "C1"))) ((:OBJ ("text" . "Annnjlkjlkjlkjj;;;;;;;;;;;;;k") ("callback_data" . "A1"))))) (jonathan:parse (alexandria:read-file-into-string (merge-pathnames "test/json.json" (asdf:system-source-directory :cl-telegram))) :as :jsown)) (defparameter *user-id-whitelist* ()) (progn (defun whitelist-user (user) (pushnew user *user-id-whitelist* :test 'eql)) (defun ban-user (user) (setf *user-id-whitelist* (remove user *user-id-whitelist*))) (defun user-whitelisted-p (user) (member user *user-id-whitelist* :test 'eql ))) (defun throw-out-bad-updates (updates) (remove-if-not (lambda (update) (user-whitelisted-p (update-user update))) updates)) (struct-to-clos:struct->class (defstruct )) (defparameter *live-chats* (make-hash-table)) (defparameter *chat-id* nil) (defparameter *ticks* 0) (defun tick (bot update-objects) (incf *ticks*) (format t ".") ;;Remove updates that are not from a whitelisted user (let ((whitelisted-updates (throw-out-bad-updates update-objects))) (let ((whitelisted-updates-count (length whitelisted-updates)) (update-objects-count (length update-objects))) (unless (zerop update-objects-count) (format t "~%----Handling Updates----") (format t "~%Valid :~a ~%Recieved:~a" whitelisted-updates-count update-objects-count))) (setf update-objects whitelisted-updates)) (dolist (update-obj update-objects) (print update-obj) (print (get-json-object-member (update-thing update-obj) "text")) (let ((update (update-raw-data update-obj))) (multiple-value-bind (chatid existsp) (get-json-object-members* update '("message" "chat")) ;;chatid is the id of the chat the update is from ;;FIXME::doees this belong here? only adding to live chats once the ;;user texts the bot first? (when existsp ;;add it to the live chats (setf (gethash chatid *live-chats*) t) ;;FIXME::chat deletion code... move somewhere else? #+nil (cl-telegram-bot/bindings::delete-message bot (get-json-object-members* update '("message" "chat" "id")) (get-json-object-members* update '("message" "message_id")) ))))) (cl-telegram-bot::with-locked-bot (bot) (while ((let ((thing (next-thing-to-do-time))) (and (not (eq thing :end)) (>= *current-time* thing)))) (destructuring-bind (id todo) (todo-item-value (pop *todo-timeline*)) (print id) (typecase todo (string (send-message todo :chat-id id))))) (when (< 1 (length *live-chats*)) (error "what the hell? why are there more than one chat?")) (dolist (chat *live-chats*) (let ((*chat-id* (get-json-object-member chat "id"))) #+nil (send-message *ticks*) #+nil (when (zerop (mod *ticks* 8)) (send-message "https://gamepedia.cursecdn.com/minecraft_gamepedia/c/c8/Wolf.png")) #+nil (when (zerop (mod *ticks* 4)) (send-message (with-output-to-string (stream) (print (utility::etouq (random 234)) stream)) :reply-markup *testcase*)) #+nil (add-task (list *chat-id* "google.com") (what-time (local-time:timestamp+ (local-time:now) (random 100) :sec))))))) (defun send-message (thing &rest rest &key &allow-other-keys) (apply 'cl-telegram-bot/bindings::send-message (or (getf rest :bot) *bot*) (or (getf rest :chat-id) *chat-id*) (format nil "~a" thing) rest)) ;;;whitelisted users ;;;- input whitelist and bot key ;;;throw out updates not on the whitelist ;;;repl ;;;inline keyboard system ;;;remember chat history, also sort by time ;;;persistent? ;;;separation of polling and sending ;;FIXME::O(N) because it uses a list, gets really slow, quadratically? ;;This is an implementation of a simple scheduler. Tasks are scheduled at ;;some point in the future. The variable which holds these tasks is the ;;variable *todo-timeline*. (progn (defparameter *todo-timeline* (list (cons "end" :end))) (defun add-task (task time) (let ((tail (member-if (lambda (a-time) (if (eq a-time :end) t (> a-time time))) *todo-timeline* :key 'cdr))) (destructive-insert-first-in-list (cons task time) tail)) *todo-timeline*) (defun destructive-insert-first-in-list (item list) (if (consp list) (let ((old-car (car list))) (setf (car list) item (cdr list) (cons old-car (cdr list))) list) (error "not a list ~a" list)))) (defun next-thing-to-do-time () (cdr (first *todo-timeline*))) (defun todo-item-value (todo-item) (car todo-item))
package io.ftauth.ftauth_storage_android import android.content.Context import android.content.SharedPreferences import androidx.security.crypto.EncryptedSharedPreferences import androidx.security.crypto.MasterKeys enum class KeyStoreExceptionCode(val code: String) { ACCESS("KEYSTORE_ACCESS"), KEY_NOT_FOUND("KEY_NOT_FOUND"), UNKNOWN("KEYSTORE_UNKNOWN") } data class KeyStoreException( val code: KeyStoreExceptionCode, val details: String? ) : Exception("$code: $details") { companion object { fun access(details: String? = null) = KeyStoreException(KeyStoreExceptionCode.ACCESS, details) fun keyNotFound(key: String? = null) = KeyStoreException(KeyStoreExceptionCode.KEY_NOT_FOUND, key) fun unknown(details: String? = null) = KeyStoreException(KeyStoreExceptionCode.UNKNOWN, details) } } class KeyStore(context: Context) { private val sharedPreferences: SharedPreferences init { val mainKey = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC) sharedPreferences = EncryptedSharedPreferences.create( "ftauth", mainKey, context, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) } fun get(key: String?): String { if (key == null) { throw KeyStoreException.keyNotFound() } return sharedPreferences.getString(key, null) ?: throw KeyStoreException.keyNotFound(key) } fun save(key: String?, value: String?) { if (key == null) { throw KeyStoreException.keyNotFound() } with(sharedPreferences.edit()) { putString(key, value) apply() } } fun clear() { with(sharedPreferences.edit()) { clear() apply() } } fun delete(key: String?) { if (key == null) { throw KeyStoreException.keyNotFound() } with(sharedPreferences.edit()) { remove(key) apply() } } }
//! The P2P public interface. use ic_types::{artifact::Artifact, messages::SignedIngress}; use crate::artifact_manager::OnArtifactError; /// This is an event handler that can be used to submit an /// ingress message to P2P event channels for processing. It encapsulates the /// given ingress message in a *Gossip* artifact and sends it to the P2P /// `GossipArtifact` channel. It is mainly to be used by the HTTP handler to /// submit ingress messages. pub trait IngressEventHandler: Send + Sync { /// The method is called when an ingress message is received. fn on_ingress_message(&self, message: SignedIngress) -> Result<(), OnArtifactError<Artifact>>; } /// P2P exposes channels that are used to hold artifacts sent by /// the *Transport* layer or the HTTP handler. These channels also hold any /// errors and notifications sent by the *Transport* layer (such as /// connection/disconnection events). `P2PRunner` provides the run interface /// used by the replica to start reading from these channels. The artifacts or /// notifications received from these channels are sent to *Gossip* for /// processing. pub trait P2PRunner: Send { /// The method starts the execution of the `P2PRunner`. fn run(&mut self); }
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "OpSelector.h" #include <foder/FileLoader.h> #include <luci/Importer.h> #include <luci/CircleExporter.h> #include <luci/CircleFileExpContract.h> #include <luci/Import/CircleReader.h> #include <luci/Profile/CircleNodeID.h> #include <arser/arser.h> #include <vconone/vconone.h> #include <iostream> #include <string> #include <vector> void print_version(void) { std::cout << "circle-opselector version " << vconone::get_string() << std::endl; std::cout << vconone::get_copyright() << std::endl; } bool check_input(const std::string &str) { bool has_hyphen = false; if (str.empty()) return false; if (str.at(0) == '-' || str[str.size() - 1] == '-') { std::cerr << "ERROR: Invalid input. Please make sure - is between the numbers" << std::endl; return false; } for (char c : str) { if (isdigit(c)) continue; else if (has_hyphen && c == '-') // when user enter '-' more than 2. { std::cerr << "ERROR: Too many '-' in str." << std::endl; return false; } else if (c == '-') has_hyphen = true; else // when user enter not allowed character, print alert msg. { std::cerr << "ERROR: To select operator by id, please use these args: [0-9], '-', ','" << std::endl; return false; } } return true; } void split_id_input(const std::string &str, std::vector<int> &by_id) { std::istringstream ss; ss.str(str); std::string str_buf; while (getline(ss, str_buf, ',')) { if (check_input(str_buf)) // input validation { try { if (str_buf.find('-') == std::string::npos) // if token has no '-' by_id.push_back(stoi(str_buf)); else // tokenize again by '-' { std::istringstream ss2(str_buf); std::string token; int from_to[2], top = 0; while (getline(ss2, token, '-')) from_to[top++] = stoi(token); for (int number = from_to[0]; number <= from_to[1]; number++) by_id.push_back(number); } } catch (std::invalid_argument &error) { std::cerr << "ERROR: Invalid argument. Please make sure your input is number." << std::endl; exit(EXIT_FAILURE); } catch (std::out_of_range) { std::cerr << "ERROR: Argument is out of range." << std::endl; exit(EXIT_FAILURE); } catch (...) { std::cerr << "ERROR: Unknown error" << std::endl; exit(EXIT_FAILURE); } } else // Input validation failed { std::cerr << "ERROR: Input validation failed. Please make sure your input is number." << std::endl; exit(EXIT_FAILURE); } } } void split_name_input(const std::string &str, std::vector<std::string> &by_name) { std::istringstream ss; ss.str(str); std::string str_buf; while (getline(ss, str_buf, ',')) by_name.push_back(str_buf); } int entry(int argc, char **argv) { // TODO Add new option names! arser::Arser arser("circle-opselector provides selecting operations in circle model"); arser.add_argument("--version") .nargs(0) .default_value(false) .help("Show version information and exit") .exit_with(print_version); // TODO Add new options! arser.add_argument("input").nargs(1).type(arser::DataType::STR).help("Input circle model"); arser.add_argument("output").nargs(1).type(arser::DataType::STR).help("Output circle model"); // select option arser.add_argument("--by_id") .nargs(1) .type(arser::DataType::STR) .help("Input operation id to select nodes."); arser.add_argument("--by_name") .nargs(1) .type(arser::DataType::STR) .help("Input operation name to select nodes."); try { arser.parse(argc, argv); } catch (const std::runtime_error &err) { std::cerr << err.what() << std::endl; std::cout << arser; return EXIT_FAILURE; } std::string input_path = arser.get<std::string>("input"); std::string output_path = arser.get<std::string>("output"); std::string operator_input; std::vector<int> by_id; std::vector<std::string> by_name; std::string op; std::vector<int> oplist; bool select_mode = false; if (!arser["--by_id"] && !arser["--by_name"] || arser["--by_id"] && arser["--by_name"]) { std::cerr << "ERROR: Either option '--by_id' or '--by_name' must be specified" << std::endl; std::cerr << arser; return EXIT_FAILURE; } if (arser["--by_id"]) { operator_input = arser.get<std::string>("--by_id"); split_id_input(operator_input, by_id); } if (arser["--by_name"]) { operator_input = arser.get<std::string>("--by_name"); split_name_input(operator_input, by_name); } // option parsing test code. for (int x : by_id) std::cout << "by_id: " << x << std::endl; for (std::string line : by_name) std::cout << "by_name: " << line << std::endl; // Load model from the file foder::FileLoader file_loader{input_path}; std::vector<char> model_data = file_loader.load(); // Verify flatbuffers flatbuffers::Verifier verifier{reinterpret_cast<uint8_t *>(model_data.data()), model_data.size()}; if (!circle::VerifyModelBuffer(verifier)) { std::cerr << "ERROR: Invalid input file '" << input_path << "'" << std::endl; return EXIT_FAILURE; } const circle::Model *circle_model = circle::GetModel(model_data.data()); if (circle_model == nullptr) { std::cerr << "ERROR: Failed to load circle '" << input_path << "'" << std::endl; return EXIT_FAILURE; } // Import from input Circle file luci::Importer importer; auto module = importer.importModule(circle_model); // Select and Import from user input. auto selector = std::make_unique<opselector::OpSelector>(circle_model); std::vector<const luci::CircleNode *> selected_nodes; // put selected nodes into map. if (by_id.size()) { loco::Graph *graph = module.get()->graph(0); // get main subgraph. for (auto node : loco::all_nodes(graph)) { auto cnode = loco::must_cast<const luci::CircleNode *>(node); try { auto node_id = luci::get_node_id(cnode); // if the node is not operator, throw runtime_error for (auto selected_id : by_id) if (selected_id == node_id) // find the selected id selected_nodes.emplace_back(cnode); } catch (std::runtime_error) { continue; } } } if (by_name.size()) { loco::Graph *graph = module.get()->graph(0); // get main subgraph. for (auto node : loco::all_nodes(graph)) { auto cnode = loco::must_cast<const luci::CircleNode *>(node); std::string node_name = cnode->name(); try { luci::get_node_id(cnode); // if the node is not operator, throw runtime_error for (auto selected_name : by_name) if (selected_name.compare(node_name) == 0) // find the selected id selected_nodes.emplace_back(cnode); } catch (std::runtime_error) { continue; } } } // Import selected nodes. module = selector->select_nodes(selected_nodes); // Export to output Circle file luci::CircleExporter exporter; luci::CircleFileExpContract contract(module.get(), output_path); if (!exporter.invoke(&contract)) { std::cerr << "ERROR: Failed to export '" << output_path << "'" << std::endl; return EXIT_FAILURE; } return 0; }
// !CHECK_TYPE fun arrayAccessRHS(a: Int?, b: Array<Int>) { b[0] = a!! checkSubtype<Int>(a) } fun arrayAccessLHS(a: Int?, b: Array<Int>) { b[a!!] = a checkSubtype<Int>(a) }
require 'rails_helper' describe Auth::SignOut do include_context 'with interactor' let(:initial_context) do { user: user, everywhere: everywhere, token: 'token' } end let(:user) { create :user } before do create :refresh_token, user: user create :refresh_token, token: 'other', user: user end describe '.call' do context 'with everywhere is false' do let(:everywhere) { false } it 'remove refresh token' do interactor.run expect(user.refresh_tokens.count).to eq(1) end end context 'with everywhere is true' do let(:everywhere) { true } it 'remove all refresh tokens' do interactor.run expect(user.refresh_tokens.count).to be_zero end end end end
package main import ( "fmt" ) // START OMIT type Sounder interface { Sound() string } type Dog struct{} func (d Dog) Sound() string { return "Woof" } func AnimalSound(s Sounder) string { return s.Sound() } func main() { d := Dog{} fmt.Println(AnimalSound(d)) } // END OMIT
# How did Rebekah solve the problem of Esau being a hairy man, and Jacob a smooth man? Rebekah put Esau’s clothes on Jacob and put goatskins upon his hands and neck.
package deps.dsl import org.gradle.api.artifacts.Dependency import org.gradle.api.artifacts.dsl.DependencyHandler /** * Adds dependencies to the 'api' configuration. * * @param dependencyNotations notations for the dependencies to be added. * @return The dependencies. * * @see [DependencyHandler.add] */ fun DependencyHandler.api(vararg dependencyNotations: Any): List<Dependency?> = dependencyNotations.map { dependencyNotation -> add("api", dependencyNotation) } /** * Adds dependencies to the 'compileOnly' configuration. * * @param dependencyNotations notations for the dependencies to be added. * @return The dependencies. * * @see [DependencyHandler.add] */ fun DependencyHandler.compileOnly(vararg dependencyNotations: Any): List<Dependency?> = dependencyNotations.map { dependencyNotation -> add("compileOnly", dependencyNotation) } /** * Adds dependencies to the 'implementation' configuration. * * @param dependencyNotations notations for the dependencies to be added. * @return The dependencies. * * @see [DependencyHandler.add] */ fun DependencyHandler.implementation(vararg dependencyNotations: Any): List<Dependency?> = dependencyNotations.map { dependencyNotation -> add("implementation", dependencyNotation) } /** * Adds dependencies to the 'kapt' configuration. * * @param dependencyNotations notations for the dependencies to be added. * @return The dependencies. * * @see [DependencyHandler.add] */ fun DependencyHandler.kapt(vararg dependencyNotations: Any): List<Dependency?> = dependencyNotations.map { dependencyNotation -> add("kapt", dependencyNotation) } /** * Adds dependencies to the 'testImplementation' configuration. * * @param dependencyNotations notations for the dependencies to be added. * @return The dependencies. * * @see [DependencyHandler.add] */ fun DependencyHandler.testImplementation(vararg dependencyNotations: Any): List<Dependency?> = dependencyNotations.map { dependencyNotation -> add("testImplementation", dependencyNotation) }
require 'savon' require 'pp' #ENV['http_proxy'] = "http://127.0.0.1:8888" Savon.configure do |config| config.log = true end HTTPI.log = true client = Savon::Client.new do http.auth.basic "yeti@rallydev.com","RallyDev" http.auth.ssl.verify_mode = :none wsdl.document = "https://trial.rallydev.com/slm/webservice/1.22/meta/1148554124/rally.wsdl" end #pp client.wsdl.soap_actions #response = client.request :get_current_user #object = response.to_hash[:get_current_user_response][:get_current_user_return] #puts "#{object[:user_name]} (#{object[:email_address]})" query_response = client.request :query_original_request do soap.body = { :workspace => nil, :artifact_type => 'Defect', :query => '(State = "Open")', :order => nil, :fetch => true, :start => 1, :pagesize => 100 } end query_result_hash = query_response.to_hash[:query_response][:query_return] puts "Total defects found: #{query_result_hash[:total_result_count]}" puts "-------------------" query_result_hash[:results][:object].each do |defect| puts "#{defect[:name]} --- #{defect[:formatted_id]} --- #{defect[:object_id]}" end
/*Q3 - Program to use a function to find the highest value of 3 numbers and return to main*/ #include <stdio.h> /*Declare function prototypes*/ int highest (int, int, int); main() { int a,b,c; int result; printf("Input number a:\n"); scanf("%d",&a); printf("Input number b:\n"); scanf("%d",&b); printf("Input number c:\n"); scanf("%d",&c); /*Call function*/ result = highest(a,b,c); printf("\nThe highest is %d.\n", result); flushall(); getchar(); } /*Implent funcion*/ int highest (int num1, int num2, int num3) { if(num1>num2) if(num1>num3) return(num1); else return(num3); else if(num2>num3) return(num2); else return(num3); }