text
stringlengths
27
775k
import { RequestHandler } from 'express'; import { PistoletConfig } from 'pistolet'; export interface ExpressPistoletConfig extends PistoletConfig { port: number; middlewares?: RequestHandler[]; }
These files contain implementations of the basic compression algorithms used: *wilt-compressor *Arithmetic Coding *Lempel-Ziv-Welch Compression *PPMD *Run-Length Encoding *LZ4 *SMAZ ...Jesus Christ, I spent an hour choosing these. What the hell is my life? Also, make sure each file has a header AND a C++ file in it, numnuts.
//----------------------------------------------------------------------------- // // // File: smproute.h // // Description: // Simple routing header file. Defines a simple/default IMessageRouter // as well as constants that are defined in rei.h (which currently // uses the old IMsg). // // Author: Mike Swafford - mikeswa // // History: // 5/19/98 - mikeswa Created // 1/23/99 - MikeSwa Moved important constants to smtpevent.idl // // Copyright (C) 1998 Microsoft Corporation // //----------------------------------------------------------------------------- #ifndef __SMPROUTE_H__ #define __SMPROUTE_H__ #include <aqincs.h> #include <smtpevent.h> class CAQSvrInst; #define AQ_DEFAULT_ROUTER_SIG 'RDQA' #define NUM_MESSAGE_TYPES 4 class CAQDefaultMessageRouter : public IMessageRouter, public CBaseObject { public: CAQDefaultMessageRouter(GUID *pguid, CAQSvrInst *paqinst); ~CAQDefaultMessageRouter(); public: //IUnknown STDMETHOD(QueryInterface)(REFIID riid, LPVOID * ppvObj) {return E_NOTIMPL;}; STDMETHOD_(ULONG, AddRef)(void) {InterlockedIncrement((PLONG) &m_cPeakReferences);return CBaseObject::AddRef();}; STDMETHOD_(ULONG, Release)(void) {return CBaseObject::Release();}; public: //IMessageRouter STDMETHOD_(GUID,GetTransportSinkID) (); STDMETHOD (GetMessageType) ( IN IMailMsgProperties *pIMailMsg, OUT DWORD *pdwMessageType); STDMETHOD (ReleaseMessageType) ( IN DWORD dwMessageType, IN DWORD dwReleaseCount); STDMETHOD (GetNextHop) ( IN LPSTR szDestinationAddressType, IN LPSTR szDestinationAddress, IN DWORD dwMessageType, OUT LPSTR *pszRouteAddressType, OUT LPSTR *pszRouteAddress, OUT LPDWORD pdwScheduleID, OUT LPSTR *pszRouteAddressClass, OUT LPSTR *pszConnectorName, OUT LPDWORD pdwNextHopType); STDMETHOD (GetNextHopFree) ( IN LPSTR szDestinationAddressType, IN LPSTR szDestinationAddress, IN LPSTR szConnectorName, IN LPSTR szRouteAddressType, IN LPSTR szRouteAddress, IN LPSTR szRouteAddressClass); STDMETHOD (ConnectionFailed) ( IN LPSTR pszConnectorName) { return S_OK; } protected: DWORD m_dwSignature; DWORD m_rgcMsgTypeReferences[NUM_MESSAGE_TYPES]; DWORD m_dwCurrentReference; GUID m_guid; //My TransportSinkID DWORD m_cPeakReferences; CAQSvrInst *m_paqinst; }; #endif //__SMPROUTE_H__
package org.opentele.server.dgks.monitoringdataset.version1_0_1.generated; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for KramPredictorType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="KramPredictorType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Weight" type="{urn:oio:medcom:chronicdataset:1.0.0}LaboratoryReportType" minOccurs="0"/> * &lt;element name="Height" type="{urn:oio:medcom:chronicdataset:1.0.0}LaboratoryReportType" minOccurs="0"/> * &lt;element name="Smoking" type="{urn:oio:medcom:chronicdataset:1.0.0}LaboratoryReportType" minOccurs="0"/> * &lt;element name="Alcohol" type="{urn:oio:medcom:chronicdataset:1.0.0}LaboratoryReportType" minOccurs="0"/> * &lt;element name="Exercise" type="{urn:oio:medcom:chronicdataset:1.0.0}LaboratoryReportType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "KramPredictorType", propOrder = { "weight", "height", "smoking", "alcohol", "exercise" }) public class KramPredictorType { @XmlElement(name = "Weight") protected LaboratoryReportType weight; @XmlElement(name = "Height") protected LaboratoryReportType height; @XmlElement(name = "Smoking") protected LaboratoryReportType smoking; @XmlElement(name = "Alcohol") protected LaboratoryReportType alcohol; @XmlElement(name = "Exercise") protected LaboratoryReportType exercise; /** * Gets the value of the weight property. * * @return * possible object is * {@link LaboratoryReportType } * */ public LaboratoryReportType getWeight() { return weight; } /** * Sets the value of the weight property. * * @param value * allowed object is * {@link LaboratoryReportType } * */ public void setWeight(LaboratoryReportType value) { this.weight = value; } /** * Gets the value of the height property. * * @return * possible object is * {@link LaboratoryReportType } * */ public LaboratoryReportType getHeight() { return height; } /** * Sets the value of the height property. * * @param value * allowed object is * {@link LaboratoryReportType } * */ public void setHeight(LaboratoryReportType value) { this.height = value; } /** * Gets the value of the smoking property. * * @return * possible object is * {@link LaboratoryReportType } * */ public LaboratoryReportType getSmoking() { return smoking; } /** * Sets the value of the smoking property. * * @param value * allowed object is * {@link LaboratoryReportType } * */ public void setSmoking(LaboratoryReportType value) { this.smoking = value; } /** * Gets the value of the alcohol property. * * @return * possible object is * {@link LaboratoryReportType } * */ public LaboratoryReportType getAlcohol() { return alcohol; } /** * Sets the value of the alcohol property. * * @param value * allowed object is * {@link LaboratoryReportType } * */ public void setAlcohol(LaboratoryReportType value) { this.alcohol = value; } /** * Gets the value of the exercise property. * * @return * possible object is * {@link LaboratoryReportType } * */ public LaboratoryReportType getExercise() { return exercise; } /** * Sets the value of the exercise property. * * @param value * allowed object is * {@link LaboratoryReportType } * */ public void setExercise(LaboratoryReportType value) { this.exercise = value; } }
// // AUTO-GENERATED FILE, DO NOT MODIFY! // import 'package:built_collection/built_collection.dart'; import 'package:mattermost_dart/src/model/plugin_manifest.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; part 'marketplace_plugin.g.dart'; /// MarketplacePlugin /// /// Properties: /// * [homepageUrl] - URL that leads to the homepage of the plugin. /// * [iconData] - Base64 encoding of a plugin icon SVG. /// * [downloadUrl] - URL to download the plugin. /// * [releaseNotesUrl] - URL that leads to the release notes of the plugin. /// * [labels] - A list of the plugin labels. /// * [signature] - Base64 encoded signature of the plugin. /// * [manifest] /// * [installedVersion] - Version number of the already installed plugin, if any. abstract class MarketplacePlugin implements Built<MarketplacePlugin, MarketplacePluginBuilder> { /// URL that leads to the homepage of the plugin. @BuiltValueField(wireName: r'homepage_url') String? get homepageUrl; /// Base64 encoding of a plugin icon SVG. @BuiltValueField(wireName: r'icon_data') String? get iconData; /// URL to download the plugin. @BuiltValueField(wireName: r'download_url') String? get downloadUrl; /// URL that leads to the release notes of the plugin. @BuiltValueField(wireName: r'release_notes_url') String? get releaseNotesUrl; /// A list of the plugin labels. @BuiltValueField(wireName: r'labels') BuiltList<String>? get labels; /// Base64 encoded signature of the plugin. @BuiltValueField(wireName: r'signature') String? get signature; @BuiltValueField(wireName: r'manifest') PluginManifest? get manifest; /// Version number of the already installed plugin, if any. @BuiltValueField(wireName: r'installed_version') String? get installedVersion; MarketplacePlugin._(); @BuiltValueHook(initializeBuilder: true) static void _defaults(MarketplacePluginBuilder b) => b; factory MarketplacePlugin([void updates(MarketplacePluginBuilder b)]) = _$MarketplacePlugin; @BuiltValueSerializer(custom: true) static Serializer<MarketplacePlugin> get serializer => _$MarketplacePluginSerializer(); } class _$MarketplacePluginSerializer implements StructuredSerializer<MarketplacePlugin> { @override final Iterable<Type> types = const [MarketplacePlugin, _$MarketplacePlugin]; @override final String wireName = r'MarketplacePlugin'; @override Iterable<Object?> serialize(Serializers serializers, MarketplacePlugin object, {FullType specifiedType = FullType.unspecified}) { final result = <Object?>[]; if (object.homepageUrl != null) { result ..add(r'homepage_url') ..add(serializers.serialize(object.homepageUrl, specifiedType: const FullType(String))); } if (object.iconData != null) { result ..add(r'icon_data') ..add(serializers.serialize(object.iconData, specifiedType: const FullType(String))); } if (object.downloadUrl != null) { result ..add(r'download_url') ..add(serializers.serialize(object.downloadUrl, specifiedType: const FullType(String))); } if (object.releaseNotesUrl != null) { result ..add(r'release_notes_url') ..add(serializers.serialize(object.releaseNotesUrl, specifiedType: const FullType(String))); } if (object.labels != null) { result ..add(r'labels') ..add(serializers.serialize(object.labels, specifiedType: const FullType(BuiltList, [FullType(String)]))); } if (object.signature != null) { result ..add(r'signature') ..add(serializers.serialize(object.signature, specifiedType: const FullType(String))); } if (object.manifest != null) { result ..add(r'manifest') ..add(serializers.serialize(object.manifest, specifiedType: const FullType(PluginManifest))); } if (object.installedVersion != null) { result ..add(r'installed_version') ..add(serializers.serialize(object.installedVersion, specifiedType: const FullType(String))); } return result; } @override MarketplacePlugin deserialize(Serializers serializers, Iterable<Object?> serialized, {FullType specifiedType = FullType.unspecified}) { final result = MarketplacePluginBuilder(); final iterator = serialized.iterator; while (iterator.moveNext()) { final key = iterator.current as String; iterator.moveNext(); final Object? value = iterator.current; switch (key) { case r'homepage_url': final valueDes = serializers.deserialize(value, specifiedType: const FullType(String)) as String; result.homepageUrl = valueDes; break; case r'icon_data': final valueDes = serializers.deserialize(value, specifiedType: const FullType(String)) as String; result.iconData = valueDes; break; case r'download_url': final valueDes = serializers.deserialize(value, specifiedType: const FullType(String)) as String; result.downloadUrl = valueDes; break; case r'release_notes_url': final valueDes = serializers.deserialize(value, specifiedType: const FullType(String)) as String; result.releaseNotesUrl = valueDes; break; case r'labels': final valueDes = serializers.deserialize(value, specifiedType: const FullType(BuiltList, [FullType(String)])) as BuiltList<String>; result.labels.replace(valueDes); break; case r'signature': final valueDes = serializers.deserialize(value, specifiedType: const FullType(String)) as String; result.signature = valueDes; break; case r'manifest': final valueDes = serializers.deserialize(value, specifiedType: const FullType(PluginManifest)) as PluginManifest; result.manifest.replace(valueDes); break; case r'installed_version': final valueDes = serializers.deserialize(value, specifiedType: const FullType(String)) as String; result.installedVersion = valueDes; break; } } return result.build(); } }
export const handleDesc = (str: string | null) => str?.replace(/<.*?>(.*?)<\/>/g, '**$1**') || '暂无';
class Teacher < ActiveRecord::Base has_many :courses has_many :students, through: :courses has_secure_password validates_presence_of :name, :username, :email, :password end
+++ pre = "<b>5.4.1. </b>" title = "运行部署" weight = 1 +++ ## 部署启动 1. 执行以下命令,编译生成 ShardingSphere-Scaling 和 ShardingSphere-Proxy 二进制包: ``` git clone --depth 1 https://github.com/apache/shardingsphere.git cd shardingsphere mvn clean install -Dmaven.javadoc.skip=true -Dcheckstyle.skip=true -Drat.skip=true -Djacoco.skip=true -DskipITs -DskipTests -Prelease ``` 发布包: - /shardingsphere-distribution/shardingsphere-scaling-distribution/target/apache-shardingsphere-${latest.release.version}-shardingsphere-scaling-bin.tar.gz - /shardingsphere-distribution/shardingsphere-proxy-distribution/target/apache-shardingsphere-${latest.release.version}-shardingsphere-proxy-bin.tar.gz 或者通过[下载页面]( https://shardingsphere.apache.org/document/current/cn/downloads/ )获取安装包。 2. 解压缩 scaling 发布包,修改配置文件 `conf/server.yaml`,这里主要修改启动端口,保证不与本机其他端口冲突,同时修改断点续传服务(可选)地址即可: ```yaml scaling: port: 8888 blockQueueSize: 10000 workerThread: 30 mode: type: Cluster repository: type: ZooKeeper props: namespace: governance_ds server-lists: localhost:2181 ``` 3. 启动 ShardingSphere-Scaling: ``` sh bin/server_start.sh ``` 4. 查看 scaling 日志 `logs/stdout.log`,确保启动成功。 5. 使用 curl 命令再次确认 scaling 正常运行。 ``` curl -X GET http://localhost:8888/scaling/job/list ``` 响应应为: ``` {"success":true,"errorCode":0,"errorMsg":null,"model":[]} ``` 6. 解压缩 proxy 发布包,修改配置文件 `conf/server.yaml`,这里主要是开启 `scaling` 和 `mode` 配置: ```yaml scaling: blockQueueSize: 10000 workerThread: 40 clusterAutoSwitchAlgorithm: type: IDLE props: incremental-task-idle-minute-threshold: 30 dataConsistencyCheckAlgorithm: type: DEFAULT mode: type: Cluster repository: type: ZooKeeper props: namespace: governance_ds server-lists: localhost:2181 retryIntervalMilliseconds: 500 timeToLiveSeconds: 60 maxRetries: 3 operationTimeoutMilliseconds: 500 overwrite: false ``` 7. 启动 ShardingSphere-Proxy: ``` sh bin/start.sh ``` 8. 查看 proxy 日志 `logs/stdout.log`,确保启动成功。 ## 结束 ### ShardingSphere-Scaling ``` sh bin/server_stop.sh ``` ### ShardingSphere-Proxy ``` sh bin/stop.sh ``` ## 应用配置项 ### ShardingSphere-Scaling 应用现有配置项如下,相应的配置可在 `conf/server.yaml` 中修改: | 名称 | 说明 | 默认值 | | -------------- | -------------------------------------- | ------ | | port | HTTP服务监听端口 | 8888 | | blockQueueSize | 数据传输通道队列大小 | 10000 | | workerThread | 工作线程池大小,允许同时运行的迁移任务线程数 | 30 |
# frozen_string_literal: true require "assert" require "hella-redis/connection_pool_spy" require "hella-redis/connection_spy" class HellaRedis::ConnectionPoolSpy class UnitTests < Assert::Context desc "HellaRedis::ConnectionPoolSpy" setup do Assert.stub_tap_on_call(HellaRedis::ConnectionSpy, :new) do |_, call| @connection_spy_new_call = call end @config = Factory.config @connection_pool_spy = HellaRedis::ConnectionPoolSpy.new(@config) end subject{ @connection_pool_spy } should have_readers :config, :connection_spy, :connection_calls should have_imeths :calls, :connection, :reset! should "know its config and redis spy" do assert_that(subject.config).is(@config) assert_that(subject.connection_spy) .is_an_instance_of(HellaRedis::ConnectionSpy) assert_that(@connection_spy_new_call.args).equals([@config]) end should "default its connection calls" do assert_that(subject.connection_calls).equals([]) end should "know its calls" do assert_that(subject.calls).is(subject.connection_spy.calls) end should "yield its connection spy using `connection`" do yielded = nil subject.connection{ |c| yielded = c } assert_that(yielded).is(subject.connection_spy) end should "track calls to connection" do block = proc{ |_c| Factory.string } subject.connection(&block) call = subject.connection_calls.last assert_that(call.block).is(block) end should "remove all calls on `reset!`" do subject.connection(&:info) assert_that(subject.calls.empty?).is_false assert_that(subject.connection_calls.empty?).is_false subject.reset! assert_that(subject.calls.empty?).is_true assert_that(subject.connection_calls.empty?).is_true end should "know if it is equal to another pool spy" do equal_pool_spy = HellaRedis::ConnectionPoolSpy.new(@config) assert_that(equal_pool_spy).equals(subject) not_equal_config = HellaRedis::ConnectionPoolSpy.new(Factory.config) assert_that(not_equal_config).does_not_equal(subject) end end end
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RunningScript : MonoBehaviour { //set speed - didn't make a public var so that I could override with a 'sprint' key float Speed = 0.1f; //set sprint speed float Sprint = 0.5f; //set obj-specific movement keys public KeyCode Forward; public KeyCode Back; public KeyCode Right; public KeyCode Left; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { Vector3 movement = new Vector3(); if (Input.GetKey(Forward)) { movement.x -= Speed; //orientation is strange, but this does successfully move the player obj forward } if (Input.GetKey(Back)) { movement.x += Speed; //move player obj backwards along x axis } if (Input.GetKey(Left)) { movement.z -= Speed; //move player obj left along z axis } if (Input.GetKey(Right)) { movement.z += Speed; //move player obj right along z axis } //create sprint speed override if (Input.GetKey(KeyCode.LeftShift)) { Speed = Sprint; } else { Speed = 0.1f; } //move player obj according to key input Vector3 newPosition = transform.position; newPosition += movement; transform.position = newPosition; } }
<?php require_once 'app/controllers/tools/Request.class.php'; /** * */ final class ControllerFactory { private function __construct(){} public static function createController() { $request = new Request(); //echo $request->getPath(); switch ($request->getNextElement()) { case '': case 'index': require_once 'app/controllers/Index.class.php'; return new Index($request); break; case 'login': require_once 'app/controllers/Login.class.php'; return new Login($request); break; case 'avisocookies': require_once 'app/controllers/AvisoCookies.class.php'; return new AvisoCookies($request); break; default: require_once 'app/controllers/NotFound.class.php'; return new NotFound($request); break; } } } ?>
package secretsyncer import ( "fmt" "io/ioutil" vaultapi "github.com/hashicorp/vault/api" ) type Syncer struct { Source Source Sink Sink } type Source interface { Read() (Data, error) } type Sink interface { WriteSimple(string, SimpleValue) error WriteCompound(string, CompoundValue) error Clear() error // TODO determining path templates is a slightly different // responsibility than writing secrets. split out a different interface. PipelinePath(PipelinePath) string TeamPath(TeamPath) string SharedPath(SharedPath) string } func FileSyncer(secretsFile string) (Syncer, error) { fileBytes, err := ioutil.ReadFile(secretsFile) if err != nil { return Syncer{}, err } client, err := vaultapi.NewClient(nil) if err != nil { return Syncer{}, fmt.Errorf("creating vault client: %s", err) } return Syncer{ Source: BytesSource{fileBytes}, Sink: &VaultSink{DefaultVaultClient{client}}, }, nil } func (s Syncer) Sync() error { data, err := s.Source.Read() if err != nil { return fmt.Errorf("reading secrets: %s", err) } err = s.Sink.Clear() if err != nil { return fmt.Errorf("clearing sink: %s", err) } for _, credential := range data { var path string switch l := credential.Location.(type) { case PipelinePath: path = s.Sink.PipelinePath(l) case TeamPath: path = s.Sink.TeamPath(l) case SharedPath: path = s.Sink.SharedPath(l) } switch v := credential.Value.(type) { case SimpleValue: err := s.Sink.WriteSimple(path, v) if err != nil { return fmt.Errorf("writing simple secret: %s", err) } case CompoundValue: err := s.Sink.WriteCompound(path, v) if err != nil { return fmt.Errorf("writing compound secret: %s", err) } } } return nil } // a sample of what a secret store contains: // []Credential{ // { // Location: TeamPath{team:"main", secret:"secret1"}, // Value: SimpleValue("value"), // }, // { // Location: PipelinePath{team:"main",pipeline:"pipeline",secret:"secret2"}, // Value: CompoundValue{"foo":"bar","baz":"qux"}, // } // } type Data = []Credential type Credential struct { Location interface{} Value interface{} } type PipelinePath struct { Team string Pipeline string Secret string } type TeamPath struct { Team string Secret string } type SharedPath struct { Secret string } type SimpleValue string type CompoundValue map[string]interface{}
--- layout: post title: "マルコフ過程" date: 2021-04-02 excerpt: "マルコフ過程について" kaggle: true hide_from_post: true tag: ["markov", "statistics"] comments: false --- # マルコフ過程について ## 定常マルコフ連鎖のパラメータ推定 - n -> ∞で以下の状態になる $$ \pi = \pi Q $$ Qが判別していればπを求めることができる ## 有限マルコフ連鎖のパラメータ推定 1. ある推移確率がわかっているときその積を計算する 2. logを取り尤度にする 3. 尤度を微分し、0としたとき、パラメータを推定できる
SET NOCOUNT ON; GO USE DotNetCampusDemoDatabase_Dev1; GO IF EXISTS(SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('dbo.UserContacts')) DROP TABLE dbo.UserContacts; GO IF EXISTS(SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('dbo.Users')) DROP TABLE dbo.Users; GO IF EXISTS(SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('dbo.Countries')) DROP TABLE dbo.Countries; GO -- dbo.Users table CREATE TABLE dbo.Users ( UserId int IDENTITY(1, 1) NOT NULL PRIMARY KEY CLUSTERED , Username varchar(30) NOT NULL , FirstName varchar(30) NOT NULL , LastName varchar(30) NOT NULL , BirthDate date NOT NULL ); GO -- dbo.UserContacts table CREATE TABLE dbo.UserContacts ( UserId int NOT NULL PRIMARY KEY CLUSTERED , Street varchar(50) NOT NULL , Town varchar(30) NOT NULL , ZipCode char(5) NOT NULL , StateOrProvince varchar(30) NOT NULL ); GO -- FKs ALTER TABLE dbo.UserContacts ADD CONSTRAINT FK_Users_UserContacts FOREIGN KEY (UserId) REFERENCES dbo.Users (UserId); GO -- dbo.Countries table CREATE TABLE dbo.Countries ( CountryId smallint NOT NULL PRIMARY KEY CLUSTERED , CountryName varchar(30) NOT NULL ); GO INSERT INTO dbo.Users (Username, FirstName, LastName, BirthDate) VALUES ('EttaGab', 'Gabriele', 'Etta', '19940725'), ('SuxStellino', 'Alessandro', 'Alpi', '19810422'), ('MicDenny', 'Michael', 'Denny', '19850714'); GO INSERT INTO dbo.UserContacts (UserId, Street, Town, ZipCode, StateOrProvince) VALUES (1, 'Via Roma, 10', 'Parma', '43100', 'Parma'), (2, 'Via Verdi, 20', 'Parma', '43100', 'Parma'), (3, 'Via Dante, 30', 'Parma', '43100', 'Parma'); GO INSERT INTO dbo.Countries (CountryId, CountryName) VALUES (1, 'Italy'), (2, 'Germany'), (3, 'England'); GO IF OBJECT_ID('dbo.SearchUsers') IS NULL EXEC ('CREATE PROCEDURE dbo.SearchUsers AS RETURN 0;') GO -- customer procedure ALTER PROCEDURE dbo.SearchUsers @UserId int = NULL , @LastName varchar(30) = NULL AS BEGIN SET NOCOUNT ON; IF @UserId IS NOT NULL OR @LastName IS NOT NULL BEGIN SELECT U.UserId , U.Username , U.FirstName , U.LastName , U.BirthDate , UC.Street , UC.Town , UC.ZipCode , UC.StateOrProvince FROM dbo.Users U JOIN dbo.UserContacts UC ON UC.UserId = U.UserId WHERE @UserId IS NULL OR U.UserId = @UserId AND (@LastName IS NULL OR U.LastName LIKE @LastName + '%'); END; END; GO
use std::ffi::CString; use std::mem::size_of; use std::os::raw::c_int; use std::sync::atomic::{AtomicUsize, Ordering}; use super::bindings::{ cef_base_ref_counted_t, cef_browser_settings_t, cef_browser_view_create, cef_browser_view_delegate_t, cef_client_t, cef_dictionary_value_create, cef_image_create, cef_image_t, cef_panel_delegate_t, cef_panel_t, cef_request_context_get_global_context, cef_size_t, cef_state_t_STATE_DISABLED, cef_state_t_STATE_ENABLED, cef_string_t, cef_string_utf8_to_utf16, cef_view_delegate_t, cef_view_t, cef_window_delegate_t, cef_window_t, }; use super::{browser_view_delegate, client}; #[derive(Debug)] pub struct WindowOptions { pub url: String, pub title: Option<String>, pub maximized: bool, pub fullscreen: bool, pub size: Option<(i32, i32)>, pub window_icon: Option<&'static [u8]>, pub window_app_icon: Option<&'static [u8]>, } impl Default for WindowOptions { fn default() -> WindowOptions { WindowOptions { url: "https://hamaluik.ca/".to_string(), title: None, maximized: false, fullscreen: false, size: Some((1280, 720)), window_icon: None, window_app_icon: None, } } } #[derive(Debug)] #[repr(C)] pub struct WindowDelegate { pub window_delegate: cef_window_delegate_t, pub ref_count: AtomicUsize, pub options: WindowOptions, pub window_icon: Option<*mut cef_image_t>, pub window_app_icon: Option<*mut cef_image_t>, } impl WindowDelegate { pub fn inc_ref(&self) { self.ref_count.fetch_add(1, Ordering::SeqCst); } } extern "C" fn is_frameless(_: *mut cef_window_delegate_t, _: *mut cef_window_t) -> c_int { 0 } extern "C" fn can_resize(_: *mut cef_window_delegate_t, _: *mut cef_window_t) -> c_int { 1 } extern "C" fn can_maximize(_: *mut cef_window_delegate_t, _: *mut cef_window_t) -> c_int { 1 } extern "C" fn can_minimize(_: *mut cef_window_delegate_t, _: *mut cef_window_t) -> c_int { 1 } extern "C" fn can_close(_: *mut cef_window_delegate_t, _: *mut cef_window_t) -> c_int { 1 } extern "C" fn window_delegate_created(slf: *mut cef_window_delegate_t, window: *mut cef_window_t) { log::debug!("window delegate created!"); let window_delegate = slf as *mut WindowDelegate; let mut cef_url = cef_string_t::default(); unsafe { let url = (*window_delegate).options.url.as_bytes(); let url = CString::new(url).unwrap(); cef_string_utf8_to_utf16(url.as_ptr(), url.to_bytes().len() as u64, &mut cef_url); } let mut browser_settings = cef_browser_settings_t::default(); browser_settings.databases = cef_state_t_STATE_DISABLED; browser_settings.local_storage = cef_state_t_STATE_ENABLED; browser_settings.application_cache = cef_state_t_STATE_DISABLED; let client = client::allocate(window); let browser_view_delegate = browser_view_delegate::allocate(); let browser_view = unsafe { (*client).inc_ref(); (*browser_view_delegate).inc_ref(); cef_browser_view_create( client as *mut cef_client_t, &cef_url, &browser_settings, cef_dictionary_value_create(), cef_request_context_get_global_context(), browser_view_delegate as *mut cef_browser_view_delegate_t, ) }; unsafe { (*browser_view).base.base.add_ref.unwrap()(browser_view as *mut cef_base_ref_counted_t); (*window).base.add_child_view.unwrap()( window as *mut cef_panel_t, browser_view as *mut cef_view_t, ); (*window).show.unwrap()(window); if let Some(title) = &(*window_delegate).options.title { let mut cef_title = cef_string_t::default(); let title = title.as_bytes(); let title = CString::new(title).unwrap(); cef_string_utf8_to_utf16( title.as_ptr(), title.to_bytes().len() as u64, &mut cef_title, ); (*window).set_title.unwrap()(window, &cef_title); } if let Some(icon) = (*window_delegate).window_icon { (*window).set_window_icon.unwrap()(window, icon); } if let Some(icon) = (*window_delegate).window_app_icon { (*window).set_window_app_icon.unwrap()(window, icon); } if let Some(size) = (*window_delegate).options.size { let size: cef_size_t = cef_size_t { width: size.0, height: size.1, }; (*window).center_window.unwrap()(window, &size); } if (*window_delegate).options.maximized { (*window).maximize.unwrap()(window); } if (*window_delegate).options.fullscreen { (*window).set_fullscreen.unwrap()(window, 1); } } } pub unsafe fn allocate(options: WindowOptions) -> *mut WindowDelegate { let window_icon = if let Some(data) = options.window_icon { let image = cef_image_create(); (*image).add_png.unwrap()(image, 1.0, data.as_ptr() as *const _, data.len() as u64); Some(image) } else { None }; let window_app_icon = if let Some(data) = options.window_app_icon { let image = cef_image_create(); (*image).add_png.unwrap()(image, 1.0, data.as_ptr() as *const _, data.len() as u64); Some(image) } else { None }; let window_delegate = WindowDelegate { window_delegate: cef_window_delegate_t { base: cef_panel_delegate_t { base: cef_view_delegate_t { base: cef_base_ref_counted_t { size: size_of::<WindowDelegate>() as u64, add_ref: Some(add_ref), release: Some(release), has_one_ref: Some(has_one_ref), has_at_least_one_ref: Some(has_at_least_one_ref), }, get_preferred_size: None, get_minimum_size: None, get_maximum_size: None, get_height_for_width: None, on_parent_view_changed: None, on_child_view_changed: None, on_focus: None, on_blur: None, }, }, on_window_created: Some(window_delegate_created), on_window_destroyed: None, get_parent_window: None, is_frameless: Some(is_frameless), can_resize: Some(can_resize), can_maximize: Some(can_maximize), can_minimize: Some(can_minimize), can_close: Some(can_close), on_accelerator: None, on_key_event: None, }, ref_count: AtomicUsize::new(1), options, window_icon, window_app_icon, }; Box::into_raw(Box::from(window_delegate)) } extern "C" fn add_ref(base: *mut cef_base_ref_counted_t) { let window_delegate = base as *mut WindowDelegate; unsafe { (*window_delegate).ref_count.fetch_add(1, Ordering::SeqCst); } } extern "C" fn release(base: *mut cef_base_ref_counted_t) -> c_int { let window_delegate = base as *mut WindowDelegate; let count = unsafe { (*window_delegate).ref_count.fetch_sub(1, Ordering::SeqCst) - 1 }; if count == 0 { unsafe { Box::from_raw(window_delegate); } 1 } else { 0 } } extern "C" fn has_one_ref(base: *mut cef_base_ref_counted_t) -> c_int { let window_delegate = base as *mut WindowDelegate; let count = unsafe { (*window_delegate).ref_count.load(Ordering::SeqCst) }; if count == 1 { 1 } else { 0 } } extern "C" fn has_at_least_one_ref(base: *mut cef_base_ref_counted_t) -> c_int { let window_delegate = base as *mut WindowDelegate; let count = unsafe { (*window_delegate).ref_count.load(Ordering::SeqCst) }; if count >= 1 { 1 } else { 0 } }
//SCRIPT PARA A FUNÇÃO DE VISUALIZAR SENHA NO LOGIN $(document).ready(function () { $("#showPassword").on("click", function () { var passwordField = $("#password"); var passwordFieldType = passwordField.attr("type"); if (passwordFieldType == "password") { passwordField.attr("type", "text"); $(this).val("Ocultar Senha"); } else { passwordField.attr("type", "password"); $(this).val("Mostrar Senha"); } }); }); //MOSTRAR SENHA NO REPETIR SENHA DO CADASTRO DE USUÁRIO $(document).ready(function () { $("#showPassword2").on("click", function () { var passwordField = $("#password_confirmation"); var passwordFieldType = passwordField.attr("type"); if (passwordFieldType == "password") { passwordField.attr("type", "text"); $(this).val("Ocultar Senha"); } else { passwordField.attr("type", "password"); $(this).val("Mostrar Senha"); } }); }); //TRANSFORMANDO TEXTO EM MAÍUSCULO function upperCaseF(a) { setTimeout(function () { a.value = a.value.toUpperCase(); }, 1); } // $(document).ready(function () { $("#end_id_log").select2(); }); $(document).ready(function () { $("#log_id_bai").select2(); }); $(document).ready(function () { $("#doc_id_tdo").select2(); }); // function Mudarestado(el) { var display = document.getElementById(el).style.display; if (display == "none") document.getElementById(el).style.display = "block"; else document.getElementById(el).style.display = "none"; }
# Global Uninitialized Statics in Rust Published May 30th, 2017 Before we jump into things I want to put the following disclaimer: > Uninitialized Global Statics are generally not what you want to have in Rust. > In fact if this is the first thing you're reaching for you might want to > rethink your design. Why though? If it's uninitialized you then need to give it some value later meaning the static variable needs to be mutable which is not thread safe if accessed later after being created. If a static variable changes throughout the lifetime of the program then Rust can't guarantee you won't have different results. If you need things to be static but immutable and the only way to initialize them is through non constant functions I would highly recommend the `lazy_static` crate. It allows you to create things like `HashMap`s and things where you already know everything that will be in them and won't change. You can see some examples on it's repo [here](https://github.com/rust-lang-nursery/lazy-static.rs). Generally you could use this and a value wrapped in a `Mutex` in order to [have mutability with statics](https://github.com/rust-lang-nursery/lazy-static.rs/issues/39). Sometimes though that doesn't work. I couldn't use this crate this time since `ucontext_t` is not `Send` because it has raw pointers in it's fields. When we don't use don't use a `Mutex` here that `Send` restriction is gone. Instead we use `static mut` which as mentioned before is `unsafe`. That being said there are times where having an uninitialized global static might be useful, usually when dealing with C libraries. I came onto this issue of creating uninitialized statics recently while using the context switching functions from `libc`. I wanted to get the hang of them by just doing a one to one port of C and later making a more Rust like interface for my library some other time. The code I was porting came from [this](http://pubs.opengroup.org/onlinepubs/009695399/functions/makecontext.html) site and was an example of how the `makecontext` function worked. Here's the code I ended coming up with to get it all working: ```rust extern crate libc; use libc::{c_char, swapcontext, makecontext, getcontext, ucontext_t, c_void}; use std::mem; // All of the uninitialized context types we'll need later, where a context is // a point in the code we can swap back to with all of the registers and values // restored as if we had never jumped to some other point in the code. static mut CTX_0: Option<ucontext_t> = None; static mut CTX_1: Option<ucontext_t> = None; static mut CTX_2: Option<ucontext_t> = None; pub fn main() { println!("Start Main"); unsafe { // We need empty arrays for the context types later. These act as a // stack to store values let mut st1: [c_char; 8192] = [mem::zeroed(); 8192]; let mut st2: [c_char; 8192] = [mem::zeroed(); 8192]; // This code could be done without this variable but I wanted // to make it close to the port. Think of it as a context that // doesn't point to anywhere, allowing us to come back to where // we left off later. CTX_0 = Some(mem::uninitialized()); // We're creating an empty context here. let mut ctx_1_tmp: ucontext_t = mem::uninitialized(); // We pass the raw pointer to the context to initialize it getcontext(&mut ctx_1_tmp as *mut ucontext_t); // We now assign it to the global static CTX_1 = Some(ctx_1_tmp); // We set up a stack for registers and keeping track of stuff // As well as the size of the stack. ctx_1().uc_stack.ss_sp = st1.as_mut_ptr() as *mut c_void; ctx_1().uc_stack.ss_size = mem::size_of_val(&st1); // Once we finish with this part of the code where do we go next? ctx_1().uc_link = ctx_0() as *mut ucontext_t; // We now point the context to a specific function. In this case the // function f1 makecontext(ctx_1() as *mut ucontext_t, f1, 0); // This part is much like before except we have a different stack and // have it go to CTX_1 after completion rather than CTX_0 let mut ctx_2_tmp: ucontext_t = mem::uninitialized(); getcontext(&mut ctx_2_tmp as *mut ucontext_t); CTX_2 = Some(ctx_2_tmp); ctx_2().uc_stack.ss_sp = st2.as_mut_ptr() as *mut c_void; ctx_2().uc_stack.ss_size = mem::size_of_val(&st2); ctx_2().uc_link = ctx_1() as *mut ucontext_t; makecontext(ctx_2() as *mut ucontext_t, f2, 0); // Now we start by going from where we're at to whatever CTX_2 points // to in this case that's the function f2 swapcontext(ctx_0() as *mut ucontext_t, ctx_2() as *const ucontext_t); } println!("Finished Main"); } // The function given for CTX_1 extern "C" fn f1() { println!("Start f1"); unsafe { swapcontext(ctx_1() as *mut ucontext_t, ctx_2() as *const ucontext_t) }; println!("Finish f1"); } // The function given for CTX_2 extern "C" fn f2() { println!("Start f2"); unsafe { swapcontext(ctx_2() as *mut ucontext_t, ctx_1() as *const ucontext_t) }; println!("Finish f2"); } // Convenience function to access the variable inside CTX_0 unsafe fn ctx_0() -> &'static mut ucontext_t { match CTX_0 { Some(ref mut x) => &mut *x, None => panic!(), } } // Convenience function to access the variable inside CTX_1 unsafe fn ctx_1() -> &'static mut ucontext_t { match CTX_1 { Some(ref mut x) => &mut *x, None => panic!(), } } // Convenience function to access the variable inside CTX_2 unsafe fn ctx_2() -> &'static mut ucontext_t { match CTX_2 { Some(ref mut x) => &mut *x, None => panic!(), } } ``` If you run the above code you get the following output: ``` Start Main Start f2 Start f1 Finish f2 Finish f1 Finish Main ``` This might be a bit confusing since the control flow goes all over the place but it has its place for things like coroutines. However, this code is an example for uninitialized global statics in Rust something that I didn't find documented specifically anywhere and had to be pulled from disparate information sources. If you don't care or understand about the context switching that's okay! Let's take a look at the important bits above so you can understand how to do what I described: ```rust static mut CTX_0: Option<ucontext_t> = None; static mut CTX_1: Option<ucontext_t> = None; static mut CTX_2: Option<ucontext_t> = None; ``` Here we're declaring our variables and assigning them a value of `None`. This satisfies the constraints for statics in Rust. They need an initial value at compile time. We use `Option` in Rust to represent the possibility of a value existing. Here we assign it a value of `None` to let the compiler know that there is no value right now! This will change later but the compiler trusts we'll know what we're doing. How do we access the inner value mutably though? As you might have noticed we have three different functions to access each variable: ```rust unsafe fn ctx_0() -> &'static mut ucontext_t { match CTX_0 { Some(ref mut x) => &mut *x, None => panic!(), } } unsafe fn ctx_1() -> &'static mut ucontext_t { match CTX_1 { Some(ref mut x) => &mut *x, None => panic!(), } } unsafe fn ctx_2() -> &'static mut ucontext_t { match CTX_2 { Some(ref mut x) => &mut *x, None => panic!(), } } ``` We're extracting those values and making a mutable reference to them and claiming that their lifetime is static. This can't be elided right now so we need to add the `'static` lifetime annotation to the return type. We've also marked the function as `unsafe` since we're accessing a global static mutably, which as I've mentioned before is an incredibly bad idea unless you absolutely need to do this. > N.B. You could do something else other than `panic!()` here and probably > should, but this is for an example where I knew how everything would work out. > That might not be the case though in other code. Now if we ever need to assign a value to it we access the variable and assign it a value of `Some(T)`. In this case we do it in the code in three separate places: ```rust // This function is also unsafe. Be careful! CTX_0 = Some(mem::uninitialized()); let mut ctx_1_tmp: ucontext_t = mem::uninitialized(); getcontext(&mut ctx_1_tmp as *mut ucontext_t); CTX_1 = Some(ctx_1_tmp); // Code omitted let mut ctx_2_tmp: ucontext_t = mem::uninitialized(); getcontext(&mut ctx_2_tmp as *mut ucontext_t); CTX_2 = Some(ctx_2_tmp); // Code omitted ``` We first make an uninitialized `ucontext_t` then use the `libc` function `getcontext` to give it a value then assign them to the variables. After that if we ever want access to the inner content we just call the helper functions we created earlier. ## Conclusion I can't stress how much you really shouldn't be doing this unless you can do all of the book keeping and making sure everything works correctly. This is a useful technique to have when dealing with languages like C where this behavior is normal. This is more something you'd do with FFI than anything else. In Rust you shouldn't really be using uninitialized statics. You can generally do what you want through some other way in Rust. That being said I hope you learned a little bit of what's possible with `unsafe` Rust and can use this as a reference if you ever do need a little of this black magic. Big thanks to [Manishearth](https://github.com/Manishearth) for proofreading and offering suggestions on a few things here.
using System; using Azos.Data; using Azos.Log; using Azos.Serialization.Arow; using Azos.Sky.Social.Graph.Server.Data; using Azos.Sky.Workers; using Azos.Sky.Mdb; namespace Azos.Sky.Social.Graph.Server.Workers { [Arow] [TodoQueue(SocialConsts.TQ_EVT_SUB_REMOVE, "A0BE51EB-E20B-4AC3-8615-86E6EDDB62BA")] public sealed class EventRemoveNodeTodo : Todo { /// <summary> /// Увеличивается на OffsetSize по завершении обработки конкретного volume. /// При селдующей итерации индекс последующего volume вычисляется по формуле : VolumeIteration + OffsetSize /// </summary> [Field(backendName: "vol_idx")] public int VolumeIndex { get; set; } /// <summary> /// Remove by Node /// </summary> [Field(backendName: "g_nod")] public GDID G_Node { get; set; } /// <summary> /// Current volume subscribers /// </summary> [Field(backendName: "g_vol")] public GDID G_Volume { get; set; } protected override ExecuteState Execute(ITodoHost host, DateTime utcBatchNow) { try { if (G_Volume.IsZero) G_Volume = getVolume(); removeSubscribers(); G_Volume = getNextVolume(); if (G_Volume.IsZero) { removeVolumes(); removeNode(); return ExecuteState.Complete; } return ExecuteState.ReexecuteUpdated; } catch (Exception error) { host.Log(MessageType.Error, this, "RemoveNode()", error.ToMessageWithType(), error); } return ExecuteState.ReexecuteAfterError; } public CRUDOperations ForNode(GDID gNode) { return GraphOperationContext.Instance.DataStore.PartitionedOperationsFor(SocialConsts.MDB_AREA_NODE, gNode); } protected override int RetryAfterErrorInMs(DateTime utcBatchNow) { #warning code repetition - refactor if (SysTries < 2) return App.Random.NextScaledRandomInteger(1000, 3000); if (SysTries < 5) return App.Random.NextScaledRandomInteger(20000, 60000); if (SysTries <= 10) return App.Random.NextScaledRandomInteger(80000, 160000); return App.Random.NextScaledRandomInteger(1600000, 320000); // throw new SocialException("Event redeliver after failure {0} retries".Args(10)); } private GDID getNextVolume() { VolumeIndex = VolumeIndex + 1; return getVolume(); } private GDID getVolume() { var qry = Queries.GetNextVolume<SubscriberVolumeRow>(G_Node, VolumeIndex); var row = ForNode(G_Node).LoadDoc(qry); return row != null ? row.G_SubscriberVolume : GDID.Zero; } private void removeSubscribers() { var qry = Queries.RemoveSubscribers(G_Volume); ForNode(G_Node).ExecuteWithoutFetch(qry); } private void removeVolumes() { var qry = Queries.RemoveSubVol(G_Node); ForNode(G_Node).ExecuteWithoutFetch(qry); } private void removeNode() { var qry = Queries.RemoveNode(G_Node); ForNode(G_Node).ExecuteWithoutFetch(qry); } } }
@extends('reservation.layout') @section('content') <div class="row"> <br> <br> <div class="col-lg-12 margin-tb"> <div class="pull-left"> <h2>Ateliers</h2> </div> <div class="pull-right"> <a class="btn btn-primary" href="{{ ('/admin') }}"> Retour</a> </div> </div> </div> <br> <br> @if ($message = Session::get('success')) <div class="alert alert-success"> <p>{{ $message }}</p> </div> @endif <table class="table table-bordered"> <tr> <th>Nom</th> <th>Atelier</th> <th>E-mail</th> <th>Téléhone</th> <th>Message</th> <th width="280px">Action</th> </tr> @foreach ($reservations as $reservation) <tr> <td>{{ $reservation->name }}</td> @foreach ($lies as $lie) @if($lie->id==$reservation->product_id) <td> {{ $lie-> titre }} </td> @endif @endforeach <td>{{ $reservation->email }}</td> <td>{{ $reservation->phone }}</td> <td>{{ $reservation->message }}</td> <td> <form action="{{ route('reservation.destroy',$reservation->id) }}" method="POST"> <a class="btn btn-info" href="{{ route('reservation.show',$reservation->id) }}">Voir</a> @csrf @method('DELETE') <button type="submit" class="btn btn-danger">Supprimer</button> </form> </td> </tr> @endforeach </table> <!-- function pour signifier une erreur avec toastr --> @if ($errors->any()) @foreach ($errors->all() as $error) <script> toastr.error('{{ $error }}'); </script> @endforeach @endif <!-- lien pour la petite fenêtre Success Toastr --> <script src="jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css"> @jquery @toastr_js @toastr_render <!-- lien pour pagination --> {!! $reservations->links() !!} @endsection
import { ILogger } from './ILogger'; import { injectable } from 'inversify'; @injectable() export class ConsoleLogger implements ILogger { debug(message: string): void { console.debug(`DEBUG: ${message}`); } error(message: string): void { console.error(`ERROR: ${message}`); } info(message: string): void { console.info(`INFO: ${message}`); } warn(message: string): void { console.warn(`WARN: ${message}`); } metric(message: string): void { console.log(message); } }
#!/bin/bash # Run tests in golang docker container go get -d -v pushd bin go get -d -v popd go test -test.v --running_under_docker
from typing import Dict, List, Tuple, Union import cv2 import numpy as np import json class CropOptions: CROP = 0 PRESERVE = 1 class PosOptions: CENTER = 0 START = 1 END = 2 def getPos(x: Union[int, float], dx: Union[int, float], opt) -> Tuple[int, int]: opt = int(opt) if(opt == PosOptions.START): return 0, round(x) elif opt == PosOptions.CENTER: return round(dx), round(x+dx) elif opt == PosOptions.END: return round(2*dx), round(2*dx+x) else: raise Exception("opt is not valid PosOptions") def resizeImage( pic: np.ndarray, size: List[int], posOption=PosOptions.CENTER ) -> np.ndarray: py, px = pic.shape[0:2] ratio = max(size[0]/px, size[1]/py) resized = cv2.resize(pic, dsize=( round(px*ratio), round(py*ratio))) ysize, xsize = resized.shape[0:2] dx = (xsize - size[0])/2 dy = (ysize - size[1])/2 sx, ex = getPos(size[0], dx, posOption) sy, ey = getPos(size[1], dy, posOption) return resized[sy:ey, sx:ex] def buildGoldenFrame( frame: np.ndarray, picture: np.ndarray, pos: List[int], posOption=PosOptions.CENTER ) -> np.ndarray: resized = resizeImage( picture, [pos[2]-pos[0], pos[3]-pos[1]], posOption) xstart, ystart = pos[0:2] ysize, xsize = resized.shape[0:2] # Why can't you use same axis system? frame[ystart:ystart+ysize, xstart:xstart+xsize] = resized return frame def loadConfig(name: str) -> Dict: with open(".".join(name.split(".")[:-1]) + ".json") as f: return json.load(f) def buildFromPreset(frame: str, image: str, out: str, opt=PosOptions.CENTER): # Temporary Solution frame = f"./assets/{frame}" out = f"./{out}" try: frameimg = cv2.imread(frame) if not frameimg.data: raise except: print( f"ERROR: Cannot Read {frame}! Did you execute this script from correct location and frame name is correct?" ) return try: inputimg = cv2.imread(image) if not inputimg.data: raise except: print(f"ERROR: Cannot Read Input Image {image}!") return cfg = loadConfig(frame)["pos"] outim = buildGoldenFrame(frameimg, inputimg, list(int(k) for k in cfg.split(",")), opt) try: cv2.imwrite(out, outim) except: print(f"Error writing Image!") def listFrames() -> str: import os items = list(filter(lambda x: not x.endswith( ".json"), os.listdir("./assets"))) text = f"There are {len(items)} frames available.\n" for item in items: cfg = loadConfig(f"./assets/{item}") text += f"\n{item} : {cfg['name']}" return text
#!/usr/bin/env python # -*- coding: utf-8 -*- import psutil from common import bytes2human, right_text, title_text, tiny_font def render(draw, width, height): df = psutil.disk_usage("/") margin = 3 title_text(draw, margin, width, text="Disk") draw.text((margin, 20), text="Used:", font=tiny_font, fill="white") draw.text((margin, 35), text="Free:", font=tiny_font, fill="white") draw.text((margin, 45), text="Total:", font=tiny_font, fill="white") right_text(draw, 20, width, margin, text="{0:0.1f}%".format(df.percent)) right_text(draw, 35, width, margin, text=bytes2human(df.free, "{0:0.0f}")) right_text(draw, 45, width, margin, text=bytes2human(df.total, "{0:0.0f}"))
! written by jxzou at 20201209: move some subroutines from bas_gms2molcas.f90 to this file ! updated by jxzou at 20210222: merge subroutine read_prim_gau1 and read_prim_gau2 module pg implicit none integer :: natom ! the number of atoms integer :: highest ! highest angular momentum integer, parameter :: iout = 6 integer, allocatable :: ram(:), ntimes(:) ! ram: relative atomic mass ! I made a mistake, ram should be interpreted as atomic order real(kind=8), allocatable :: coor(:,:) ! Cartesian coordinates character(len=2), allocatable :: elem(:) ! elements ! 'L' will be divided into two parts: 'S' and 'P' type primitive_gaussian character(len=1) :: stype = ' ' ! 'S','P','D','F','G','H','I' integer :: nline = 0 integer :: ncol = 0 real(kind=8), allocatable :: coeff(:,:) end type primitive_gaussian ! 7 for 'S', 'P', 'D', 'F', 'G', 'H', 'I' ! 1 , 2 , 3 , 4 , 5 , 6 , 7 type(primitive_gaussian) :: prim_gau(7) ! --- below are arrays for ECP/PP --- type ecp_potential integer :: n = 0 ! size for col1, 2, and 3 real(kind=8), allocatable :: col1(:) integer , allocatable :: col2(:) real(kind=8), allocatable :: col3(:) end type ecp_potential type ecp4atom logical :: ecp = .false. ! whether this atom has ECP/PP integer :: core_e = 0 ! number of core electrons integer :: highest = 0 ! highest angular momentum type(ecp_potential), allocatable :: potential(:) ! size highest+1 end type ecp4atom type(ecp4atom), allocatable :: all_ecp(:) ! size natom logical :: ecp_exist = .false. end module pg ! check whether UHF in a given GAMESS .inp file subroutine check_uhf_in_gms_inp(inpname, uhf) implicit none integer :: fid character(len=240) :: buf character(len=240), intent(in) :: inpname logical, intent(out) :: uhf uhf = .false. open(newunit=fid,file=TRIM(inpname),status='old',position='rewind') do while(.true.) read(fid,'(A)') buf call upper(buf) if(index(buf,'SCFTYP=UHF') > 0) then uhf = .true. exit end if if(index(buf,'$END') > 0) exit end do ! for while close(fid) return end subroutine check_uhf_in_gms_inp ! find the number of atoms in GAMESS .inp file subroutine read_natom_from_gms_inp(inpname, natom) implicit none integer :: i, fid, nline integer, intent(out) :: natom integer, parameter :: iout = 6 character(len=1) :: str character(len=240):: buf character(len=240), intent(in) :: inpname natom = 0 open(newunit=fid,file=TRIM(inpname),status='old',position='rewind') do while(.true.) read(fid,'(A)',iostat=i) buf if(i /= 0) exit call upper(buf(2:6)) if(buf(2:6) == '$DATA') exit end do ! for while if(i /= 0) then write(iout,'(A)') 'ERROR in subroutine read_natom_from_gms_inp: wrong format& & in file '//TRIM(inpname) stop end if read(fid,'(A)') buf read(fid,'(A)') buf do while(.true.) read(fid,'(A)') buf call upper(buf(3:5)) if(buf(2:5) == '$END') exit do while(.true.) read(fid,'(A)') buf read(buf,*,iostat=i) str, nline if(i /= 0) exit do i = 1, nline, 1 read(fid,'(A)') buf end do ! for i end do ! for while natom = natom + 1 end do ! for while close(fid) if(natom == 0) then write(iout,'(A)') 'ERROR in subroutine read_natom_from_gms_inp: zero atom& & found in file '//TRIM(inpname) stop end if return end subroutine read_natom_from_gms_inp ! read charge, spin multiplicity, uhf(bool) bohrs(bool) from a given GAMESS ! .inp/.dat file subroutine read_charge_and_mult_from_gms_inp(inpname, charge, mult, uhf, ecp) implicit none integer :: i, fid integer, intent(out) :: charge, mult character(len=240) :: buf character(len=480) :: buf1 character(len=240), intent(in) :: inpname logical, intent(out) :: uhf, ecp charge = 0 mult = 1 uhf = .false. ecp = .false. open(newunit=fid,file=TRIM(inpname),status='old',position='rewind') read(fid,'(A)') buf read(fid,'(A)') buf1 buf1 = TRIM(buf)//' '//TRIM(buf1) call upper(buf1) if(index(buf1,'UHF') > 0) uhf = .true. i = index(buf1,'ICHAR') if(i > 0) read(buf1(i+7:),*) charge i = index(buf1,'MULT') if(i > 0) read(buf1(i+5:),*) mult do while(.true.) read(fid,'(A)',iostat=i) buf if(i /= 0) exit if(buf(2:2) == '$') then call upper(buf(3:5)) if(buf(2:5) == '$ECP') then ecp = .true. exit end if end if end do ! for while close(fid) return end subroutine read_charge_and_mult_from_gms_inp ! read elements, nuclear charges and Cartesian coordinates from a GAMESS .inp file subroutine read_elem_nuc_coor_from_gms_inp(inpname, natom, elem, nuc, coor) implicit none integer :: i, k, fid, nline integer, intent(in) :: natom integer, intent(out) :: nuc(natom) real(kind=8), parameter :: Bohr_const = 0.52917721092d0 real(kind=8), allocatable :: nuc1(:) real(kind=8), intent(out) :: coor(3,natom) character(len=1) :: str character(len=2), intent(out) :: elem(natom) character(len=240) :: buf character(len=240), intent(in) :: inpname logical :: bohrs allocate(nuc1(natom), source=0.0d0) nuc = 0; coor = 0d0; elem = ' ' open(newunit=fid,file=TRIM(inpname),status='old',position='rewind') ! find in the first 6 lines whether the coordinates are in Angstrom or Bohr bohrs = .false. do i = 1, 6 read(fid,'(A)') buf call upper(buf) if(index(buf,'UNITS=BOHR') /= 0) then bohrs = .true. exit end if if(index(buf,'$END') /= 0) exit end do ! for i ! Angstrom/Bohr determined rewind(fid) do while(.true.) read(fid,'(A)') buf if(buf(2:6) == '$DATA') exit end do ! for while read(fid,'(A)') buf read(fid,'(A)') buf do k = 1, natom, 1 read(fid,*) elem(k), nuc1(k), coor(1:3,k) do while(.true.) read(fid,'(A)') buf read(buf,*,iostat=i) str, nline if(i /= 0) exit do i = 1, nline, 1 read(fid,'(A)') buf end do ! for do end do ! for while end do ! for k close(fid) forall(i = 1:natom) nuc(i) = DNINT(nuc1(i)) deallocate(nuc1) if(bohrs) coor = coor*Bohr_const return end subroutine read_elem_nuc_coor_from_gms_inp ! read nbf and nif from a given GAMESS .inp/.dat file subroutine read_nbf_and_nif_from_gms_inp(inpname, nbf, nif) implicit none integer:: i, j, k, fid integer, intent(out) :: nbf, nif integer, parameter :: iout = 6 character(len=240) :: buf character(len=240), intent(in) :: inpname nbf = 0; nif = 0 open(newunit=fid,file=TRIM(inpname),status='old',position='rewind') do while(.true.) read(fid,'(A)',iostat=i) buf if(i /= 0) exit call upper(buf) j = index(buf,'$GUESS'); k = index(buf,'NORB=') if(j/=0 .and. k/=0) then read(buf(k+5:),*) nif exit end if end do ! for while if(i /= 0) then close(fid) return end if rewind(fid) do while(.true.) read(fid,'(A)',iostat=i) buf if(i /= 0) exit call upper(buf(3:6)) if(buf(2:6)=='$DATA') exit end do ! for while if(i /= 0) then write(iout,'(A)') 'ERROR in subroutine bas_gms2py: No $DATA section found& & in file '//TRIM(inpname)//'.' close(fid) stop end if ! read the Title Card line, find nbf in it read(fid,'(A)') buf i = index(buf,'nbf=') if(i == 0) then ! if not found, set to nif nbf = nif else read(buf(i+4:),*) nbf end if close(fid) return end subroutine read_nbf_and_nif_from_gms_inp ! read na, nb, nif and nbf from a given GAMESS .inp file ! Note: when spherical harmonic functions are used, the nbf here will <= ! the number of basis functions in $VEC (where MOs are always expanded ! on Cartesian functions) subroutine read_na_nb_nif_nbf_from_gms_inp(inpname, na, nb, nif, nbf) implicit none integer :: i, fid integer, intent(out) :: na, nb, nif, nbf integer, parameter :: iout = 6 character(len=240) :: buf character(len=240), intent(in) :: inpname na = 0; nb = 0; nif = 0; nbf = 0 open(newunit=fid,file=TRIM(inpname),status='old',position='rewind') do while(.true.) read(fid,'(A)',iostat=i) buf if(i /= 0) exit call upper(buf(3:6)) if(buf(2:6)=='$DATA') exit end do ! for while if(i /= 0) then write(iout,'(A)') 'ERROR in subroutine read_na_nb_nif_nbf_from_gms_inp: No& & $DATA section found in' write(iout,'(A)') 'file '//TRIM(inpname)//'.' close(fid) stop end if ! read the Title Card line read(fid,'(A)') buf close(fid) i = index(buf,'nbf=') read(buf(i+4:),*) nbf buf(i-1:) = ' ' i = index(buf,'nif=') read(buf(i+4:),*) nif buf(i-1:) = ' ' i = index(buf,'nb=') read(buf(i+3:),*) nb buf(i-1:) = ' ' i = index(buf,'na=') read(buf(i+3:),*) na return end subroutine read_na_nb_nif_nbf_from_gms_inp ! read type all_ecp from a given GAMESS .inp/.dat file subroutine read_all_ecp_from_gms_inp(inpname) use pg, only: iout, natom, all_ecp, ecp_exist implicit none integer :: i, j, k, m, n, fid character(len=240) :: buf character(len=240), intent(in) :: inpname if(natom == 0) then write(iout,'(A)') 'ERROR in subroutine read_all_ecp_from_gms_inp: natom = 0.' write(iout,'(A)') 'The variable natom should be initialized before calling& & this subroutine.' stop end if allocate(all_ecp(natom)) all_ecp(:)%ecp = .false. if(.not. ecp_exist) return open(newunit=fid,file=TRIM(inpname),status='old',position='rewind') do while(.true.) read(fid,'(A)') buf if(buf(2:2) == '$') then call upper(buf(3:5)) if(buf(3:5) == 'ECP') exit end if end do ! for while do i = 1, natom, 1 read(fid,'(A)') buf call upper(buf) if(index(buf,'NONE') /= 0) cycle all_ecp(i)%ecp = .true. k = index(buf,'GEN') read(buf(k+3:),*) all_ecp(i)%core_e, m all_ecp(i)%highest = m allocate(all_ecp(i)%potential(m+1)) do j = 1, m+1, 1 read(fid,'(A)') buf if(j == 1) then k = index(buf,'ul') if(k == 0) then write(iout,'(A)') "ERROR in subroutine read_all_ecp_from_gms_inp: ECP/PP& & does not start with '-ul potential'." write(iout,'(A)') 'You should check the format of ECP/PP data in file '//TRIM(inpname) stop end if end if read(buf,*) n all_ecp(i)%potential(j)%n = n allocate(all_ecp(i)%potential(j)%col1(n), source=0d0) allocate(all_ecp(i)%potential(j)%col2(n), source=0) allocate(all_ecp(i)%potential(j)%col3(n), source=0d0) do k = 1, n, 1 read(fid,*) all_ecp(i)%potential(j)%col1(k), all_ecp(i)%potential(j)%col2(k), & all_ecp(i)%potential(j)%col3(k) end do ! for k end do ! for j end do ! for i return end subroutine read_all_ecp_from_gms_inp ! deallocate the allocatable arrays in array prim_gau subroutine clear_prim_gau() use pg, only: prim_gau implicit none integer :: i do i = 1, 7, 1 prim_gau(i)%stype = ' ' prim_gau(i)%nline = 0 prim_gau(i)%ncol = 0 if(allocated(prim_gau(i)%coeff)) deallocate(prim_gau(i)%coeff) end do return end subroutine clear_prim_gau ! read this type of primitive gaussians, i.e., 'S', 'L', etc. subroutine read_prim_gau(stype, nline, fid) use pg, only: iout, prim_gau implicit none integer :: i, j, k, itmp, ncol, ncol1, nline0, nline1 integer, intent(in) :: nline, fid real(kind=8), parameter :: zero = 1d-6 real(kind=8) :: exp0, rtmp, rtmp1 real(kind=8), allocatable :: coeff(:,:) character(len=1), intent(in) :: stype logical :: share call stype2itype(stype, k) ! two cases: 'L', or not 'L' if(k /= 0) then ! 'S','P','D','F','G','H','I', not 'L' ! two subcases: whether or not this angular momentum has occurred if(allocated(prim_gau(k)%coeff)) then read(fid,*) itmp, exp0, rtmp BACKSPACE(fid) nline0 = prim_gau(k)%nline ncol = prim_gau(k)%ncol allocate(coeff(nline0,ncol), source=prim_gau(k)%coeff) deallocate(prim_gau(k)%coeff) ! further two sub-subcases: whether sharing the same exponents share = .false. ! initialization if(DABS(coeff(1,1)-exp0) < zero) then nline1 = max(nline0,nline) share = .true. end if if((.not.share) .and. nline==1 .and. DABS(coeff(nline0,1)-exp0)<zero) then ! this rare case occurs in nobasistransform cc-pVDZ for Zn nline1 = nline0 share = .true. end if if(.not. share) nline1 = nline0 + nline allocate(prim_gau(k)%coeff(nline1,ncol+1),source=0d0) prim_gau(k)%coeff(1:nline0,1:ncol) = coeff deallocate(coeff) ncol = ncol + 1 prim_gau(k)%ncol = ncol prim_gau(k)%nline = nline1 do i = 1, nline, 1 read(fid,*) itmp, exp0, rtmp if(nline == 1) rtmp = 1d0 if(share) then if(i > nline0) then prim_gau(k)%coeff(i,1) = exp0 prim_gau(k)%coeff(i,ncol) = rtmp else ! i <= nline0 do j = 1, nline0, 1 if(DABS(prim_gau(k)%coeff(j,1)-exp0) < zero) then prim_gau(k)%coeff(j,ncol) = rtmp exit end if end do ! for j if(j == nline0+1) then write(iout,'(/,A)') "ERROR in subroutine read_prim_gau: I've never seen such basis." write(iout,'(A)') "Did you forget to add 'int(nobasistransform)' in .gjf file?" write(iout,'(3(A,I0))') 'stype='//stype//', i=',i,', nline=',nline,', nline0=',nline0 write(iout,'(2(A,E16.8))') 'exp0=', exp0, ', rtmp=', rtmp stop end if end if else ! not share prim_gau(k)%coeff(nline0+i,1) = exp0 prim_gau(k)%coeff(nline0+i,ncol) = rtmp end if end do ! for i else ! never occurs before, read first time prim_gau(k)%stype = stype prim_gau(k)%nline = nline prim_gau(k)%ncol = 2 allocate(prim_gau(k)%coeff(nline,2), source=0d0) do i = 1, nline, 1 read(fid,*) itmp, prim_gau(k)%coeff(i,1), rtmp if(nline == 1) rtmp = 1d0 prim_gau(k)%coeff(i,2) = rtmp end do ! for i end if else ! k == 0, this is 'L' for Pople-type basis sets ! sharing exponents for 'L' is unlikely in Pople basis sets, don't consider if(allocated(prim_gau(1)%coeff)) then ! 'S' nline0 = prim_gau(1)%nline ncol = prim_gau(1)%ncol prim_gau(1)%nline = nline0 + nline prim_gau(1)%ncol = ncol + 1 allocate(coeff(nline0,ncol), source=prim_gau(1)%coeff) deallocate(prim_gau(1)%coeff) allocate(prim_gau(1)%coeff(nline0+nline,ncol+1),source=0d0) prim_gau(1)%coeff(1:nline0,1:ncol) = coeff deallocate(coeff) ncol = ncol + 1 else prim_gau(1)%stype = 'S' prim_gau(1)%nline = nline prim_gau(1)%ncol = 2 allocate(prim_gau(1)%coeff(nline,2),source=0d0) nline0 = 0; ncol = 2 end if if(allocated(prim_gau(2)%coeff)) then ! 'P' nline1 = prim_gau(2)%nline ncol1 = prim_gau(2)%ncol prim_gau(2)%nline = nline1 + nline prim_gau(2)%ncol = ncol1 + 1 allocate(coeff(nline1,ncol1), source=prim_gau(2)%coeff) deallocate(prim_gau(2)%coeff) allocate(prim_gau(2)%coeff(nline1+nline,ncol1+1),source=0d0) prim_gau(2)%coeff(1:nline1,1:ncol1) = coeff deallocate(coeff) ncol1 = ncol1 + 1 else prim_gau(2)%stype = 'P' prim_gau(2)%nline = nline prim_gau(2)%ncol = 2 allocate(prim_gau(2)%coeff(nline,2),source=0d0) nline1 = 0; ncol1 = 2 end if do i = 1, nline, 1 read(fid,*) itmp, exp0, rtmp, rtmp1 if(nline == 1) then rtmp = 1d0; rtmp1 = 1d0 end if prim_gau(1)%coeff(nline0+i,1) = exp0 prim_gau(1)%coeff(nline0+i,ncol) = rtmp prim_gau(2)%coeff(nline1+i,1) = exp0 prim_gau(2)%coeff(nline1+i,ncol1) = rtmp1 end do ! for i end if return end subroutine read_prim_gau ! determine the highest angular momentum quantum number subroutine get_highest_am() use pg, only: highest, prim_gau implicit none if(allocated(prim_gau(7)%coeff)) then highest = 6 else if(allocated(prim_gau(6)%coeff)) then highest = 5 else if(allocated(prim_gau(5)%coeff)) then highest = 4 else if(allocated(prim_gau(4)%coeff)) then highest = 3 else if(allocated(prim_gau(3)%coeff)) then highest = 2 else if(allocated(prim_gau(2)%coeff)) then highest = 1 else highest = 0 end if return end subroutine get_highest_am ! print primitive gaussians subroutine prt_prim_gau(iatom, fid) use pg, only: prim_gau, ram, highest, all_ecp, elem, ecp_exist implicit none integer :: i, j, k, m, n, nline, ncol integer, intent(in) :: iatom, fid integer, allocatable :: list(:) character(len=1), parameter :: am(0:6) = ['S','P','D','F','G','H','I'] call get_highest_am() if(ecp_exist) then write(fid,'(5X,I0,A1,3X,I1)') ram(iatom)-all_ecp(iatom)%core_e,'.',highest else write(fid,'(5X,I0,A1,3X,I1)') ram(iatom), '.', highest end if do i = 1, 7, 1 if(.not. allocated(prim_gau(i)%coeff)) cycle write(fid,'(A)') '* '//prim_gau(i)%stype//'-type functions' nline = prim_gau(i)%nline ncol = prim_gau(i)%ncol write(fid,'(2(1X,I4))') nline, ncol-1 do j = 1, nline, 1 write(fid,'(3X,ES16.9)') prim_gau(i)%coeff(j,1) end do ! for j do j = 1, nline, 1 write(fid,'(10(ES16.9,2X))') (prim_gau(i)%coeff(j,k), k=2,ncol) end do ! for j end do ! for i if(.not. ecp_exist) return if(all_ecp(iatom)%ecp) then m = all_ecp(iatom)%highest write(fid,'(A2,1X,A2,1X,I0,1X,I0)') 'PP', elem(iatom), all_ecp(iatom)%core_e, m allocate(list(m+1)) list(1) = m forall(i=2:m+1) list(i) = i-2 do i = 1, m+1, 1 n = all_ecp(iatom)%potential(i)%n if(i == 1) then write(fid,'(I0,A)') n,';!'//am(list(1))//' POTENTIAL' else ! i > 1 write(fid,'(I0,A)') n,';!'//am(list(i))//'-'//am(list(1))//' POTENTIAL' end if do j = 1, n, 1 write(fid,'(I0,2(1X,F16.8))') all_ecp(iatom)%potential(i)%col2(j),& all_ecp(iatom)%potential(i)%col3(j), all_ecp(iatom)%potential(i)%col1(j) end do ! for j end do ! for i write(fid,'(A1,/,A,/,A)') '*', 'Spectral', 'End of Spectral' end if return end subroutine prt_prim_gau ! update the number of times each atom occurred subroutine update_ntimes(iatom) use pg, only: elem, ntimes implicit none integer :: i integer, intent(in) :: iatom character(len=2) :: ctmp ctmp = elem(iatom) do i = iatom-1, 1, -1 if(ctmp == elem(i)) then ntimes(iatom) = ntimes(i) + 1 exit end if end do ! for i return end subroutine update_ntimes ! update the number of times each atom occurred subroutine calc_ntimes(natom, elem, ntimes) implicit none integer :: i, j integer, intent(in) :: natom integer, intent(out) :: ntimes(natom) character(len=2) :: tmp character(len=2), intent(in) :: elem(natom) ntimes = 1 do i = 2, natom, 1 tmp = elem(i) do j = i-1, 1, -1 if(tmp == elem(j)) then ntimes(i) = ntimes(j) + 1 exit end if end do ! for j end do ! for i return end subroutine calc_ntimes ! generate contracted string, e.g. 5s3p1d -> 3s2p1d subroutine gen_contracted_string(nline, ncol, str1, str2) implicit none integer :: i integer, intent(in) :: nline(7), ncol(7) character(len=1), parameter :: am(7) = ['s','p','d','f','g','h','i'] character(len=3) :: str character(len=21), intent(out) :: str1, str2 !10s10p10d10f10g10h10i str1 = ' '; str2 = ' ' do i = 1, 7, 1 if(nline(i) > 0) then write(str,'(I0,A1)') nline(i), am(i) str1 = TRIM(str1)//TRIM(str) write(str,'(I0,A1)') ncol(i)-1,am(i) str2 = TRIM(str2)//TRIM(str) end if end do ! for i return end subroutine gen_contracted_string ! read Alpha or (both Alpha and Beta) MOs from a GAMESS .dat or .inp file ! Note: if you want to read both Alpha and Beta MOs, just double the variable ! nif subroutine read_mo_from_dat(datname, nbf, nif, coeff) use pg, only: iout implicit none integer i, j, k, nline, nleft, fid integer, intent(in) :: nbf, nif character(len=5) :: str1 character(len=30) :: str2 character(len=240) :: buf character(len=240), intent(in) :: datname real(kind=8), intent(out) :: coeff(nbf,nif) coeff = 0d0 open(newunit=fid,file=TRIM(datname),status='old',position='append') do while(.true.) BACKSPACE(fid) BACKSPACE(fid) read(fid,'(A)',iostat=i) buf if(i /= 0) exit call upper(buf(3:5)) if(buf(2:5) == '$VEC') exit end do if(i /= 0) then write(iout,'(A)') "ERROR in subroutine read_mo_from_dat: No '$VEC' section in& & file "//TRIM(datname) close(fid) stop end if nline = nbf/5 nleft = nbf - nline*5 do i = 1, nif, 1 k = 1 do j = 1, nline, 1 read(fid,'(A)') buf buf = buf(6:) read(buf,'(5ES15.8)') coeff(k:k+4,i) k = k + 5 end do ! for j if(nleft > 0) then read(fid,'(A)') buf buf = buf(6:) str1 = ' ' write(str1,'(I5)') nleft str1 = ADJUSTL(str1) str2 = '('//TRIM(str1)//'ES15.8)' read(buf,TRIM(str2)) coeff(k:nbf,i) end if end do ! for i close(fid) return end subroutine read_mo_from_dat
#!/bin/bash # # centos7 イメージ上で、sshdを開始する # set -e touch /etc/rc.d/init.d/functions echo "create host's key" bash -x /usr/sbin/sshd-keygen echo "start sshd daemon" /usr/sbin/sshd -D & echo "create users key pair." ssh-keygen -t rsa -m PEM -N "" -f ~/.ssh/id_rsa echo "set authorized_keys" cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys echo "SUCCESS."
#Installing YARN apt update -y curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list .d/yarn.list apt-get update && sudo apt-get install yarn #Installing NodeJS curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash - apt-get install -y nodejs apt-get update && sudo apt-get install yarn #Remove cmdtest in case it conflicts with available old YARN apt remove cmdtest apt-get update && sudo apt-get install yarn #Adding Webpack yarn add global webpack yarn install apt add --update nodejs nodejs-npm && npm install npm@latest -g npm install npm@latest -gyarn add global webpack yarn add global webpack npm install webpack -g apt add --update nodejs nodejs-npm && npm install npm@latest -g npm install npm@latest -g npm install webpack -g webpack --watch --config config/webpack.js
package chrome.alarms.bindings import chrome.events.bindings.Event import scala.scalajs.js import scala.scalajs.js.annotation.JSGlobal @js.native @JSGlobal("chrome.alarms") object Alarms extends js.Object { val onAlarm: Event[js.Function1[Alarm, _]] = js.native def create(name: String = "", alarmInfo: AlarmInfo): Unit = js.native def get(name: String = "", callback: js.Function1[js.UndefOr[Alarm], _]): Unit = js.native def getAll(callback: js.Function1[js.Array[Alarm], _]): Unit = js.native def clear(name: String = "", callback: js.UndefOr[js.Function1[Boolean, _]] = js.undefined): Unit = js.native def clearAll(callback: js.UndefOr[js.Function1[Boolean, _]] = js.undefined): Unit = js.native }
package com.github.bbantonia.webserver.logging; import com.github.bbantonia.webserver.config.Config; public abstract class AbstractLogger implements Logger { protected AbstractLogger() {} protected final boolean shouldLog(LogLevel intent) { LogLevel.LogLevelComparator comparator = new LogLevel.LogLevelComparator(); return comparator.compare(intent, Config.getInstance().getLogLevel()) >= 0; } protected abstract void log(LogLevel level, String message); protected abstract void log(LogLevel level, Throwable th, String message); @Override public void debug(String message) { log(LogLevel.DEBUG, message); } @Override public void info(String message) { log(LogLevel.INFO, message); } @Override public void warn(String message) { log(LogLevel.WARN, message); } @Override public void error(String message) { log(LogLevel.ERROR, message); } @Override public void error(Throwable th, String message) { log(LogLevel.ERROR, th, message); } }
var searchData= [ ['open',['Open',['../struct_serial_interface.html#ab506189cbcec1de46dfc75142fb82068',1,'SerialInterface']]] ];
# RandomizeList Randomize a list of ASCII text: mix the lines. (Finished, tutorial).
package it.unibo.sc.activities import android.os.Bundle import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import it.unibo.sc.adapters.ProductShelfAdapter import it.unibo.sc.databinding.ActivityNotificationsBinding import it.unibo.sc.utils.ProductShelfComparator import it.unibo.sc.viewmodel.ProductsShelfViewModel import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch /** * Activity that shows all the expiring products. * */ class NotificationsActivity : AppCompatActivity() { private lateinit var binding: ActivityNotificationsBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityNotificationsBinding.inflate(layoutInflater) setContentView(binding.root) val viewModel: ProductsShelfViewModel by viewModels() val listAdapter = ProductShelfAdapter(ProductShelfComparator, this) val recyclerView = binding.notificationsRecyclerView recyclerView.adapter = listAdapter recyclerView.layoutManager = LinearLayoutManager(this) lifecycleScope.launch { viewModel.productShelves().collectLatest { prodSh -> listAdapter.submitList(prodSh) } } } }
# frozen_string_literal: true namespace :html5_validator do desc 'each run of test generates html files for validation, ' \ 'cleanup previous generated files' task flush_cached_responses: :environment do puts 'run flush_cached_responses' Html5Validator.flush_cached_responses end desc 'run html5 validation on generated files from test' task run: :environment do puts 'run Html5Validator.run' Html5Validator.run end desc 'run all of w3c tests and adds functional screenshots from test' task run_with_screenshots: :environment do puts 'run Html5Validator.run with screenshots' system 'FUNCTIONAL_SCREENSHOTS=true ./infra/test/w3c.sh' end end
from django.urls import path, include from . import views urlpatterns = [ path('', views.index), path('results',views.results), # path('get_portfolio',views.get_portfolio), path('collect_user_data',views.collect_user_data), # path('style', views.styles), ]
--- layout: post title: 自定义Django内置的User系统 categories: [后端] tags: [] date: 2019-11-10 11:48:07 comments: true --- #### 自定义User系统步骤 Django内置的User系统可以帮我们完成后台用户验证,授权,非常强大。 但内置的User系统验证是以Username和Password,也就是Username是unique,而我们常用的是手机号或者邮箱是来验证。而且内置的User还有一些字段如:first_name,last_name等等也不符合我们的需求。 所以我们需要来改写AbstractBaseUser来自定义我们的User系统,修改验证系统以手机号来验证,另外自定义我们需求的字段。 步骤: 1. 创建一个cmsauth,用来管理用户系统。(不能使用auth,auth已经被系统占用) 2. 继承AbstractBaseUser重写User系统的验证、字段,定义UserManager。 3. 注册app,设置AUTH_USER_MODEL。修改系统的User路径(告诉Django你现在不用内置的User系统了,用自定义的User系统) 4. 在第一次进行migrations和migrate之前必须先完成以上两个步骤,然后映射到数据库中。 #### 继承AbstractBaseUser重写User系统 在创建的cmsauth这个app内的model模型中写模型,代码如下: ```Python from django.db import models from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin class UserManager(BaseUserManager): """重写user的object模型""" def _create_user(self, telephone, username, password, **kwargs): if not telephone: raise ValueError('手机号不能为空') if not username: raise ValueError('姓名不能为空') if not password: raise ValueError('密码不能为空') user = self.model(telephone=telephone, username=username, **kwargs) user.set_password(password) user.save() return user """创建普通用户""" def create_user(self, telephone, username, password, **kwargs): kwargs['is_superuser'] = False self._create_user(telephone=telephone, username=username, password=password, **kwargs) """创建超级用户""" def create_superuser(self, telephone, username, password, **kwargs): kwargs['is_superuser'] = True self._create_user(telephone=telephone, username=username, password=password, **kwargs) class User(AbstractBaseUser, PermissionsMixin): """重新定义user模型""" telephone = models.CharField(max_length=11, unique=True) email = models.CharField(max_length=100, null=True) username = models.CharField(max_length=100) is_active = models.BooleanField(default=True) data_joined = models.DateTimeField(auto_now_add=True) """设置手机号为验证方式""" USERNAME_FIELD = 'telephone' REQUIRED_FIELDS = ['username'] """把重写objects模型赋值到重写的user模型中""" objects = UserManager() def get_full_name(self): return self.username def get_short_name(self): return self.username ``` #### 注册app,设置AUTH_USER_MODEL 在settings.py中注册cmsauth这个app,不注册无法进行migrations操作。代码如下: ```Python INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.cmsauth', ] ``` 在settings.py中设置AUTH_USER_MODEL,告诉Django现在用我们自定义的User。代码如下: ```Python AUTH_USER_MODEL = 'cmsauth.User' ``` 不是完整路径,只需要app的名字,和模型的名字就可以了。不需要写成app.cmsauth.forms.User或者app.cmsauth.User这些都是不可以的。 #### 把自定义的User映射到数据库 配置好数据库,运行makemigrations,然后再migrate就可以了。
package club.broking.cdn.servlets.products; import club.broking.cdn.models.Product; import club.broking.cdn.models.ProductAccessor; import club.broking.cdn.services.CassandraService; import club.broking.cdn.servlets.AbstractJsonServlet; import com.datastax.driver.mapping.MappingManager; import java.util.List; public class ProductsServlet extends AbstractJsonServlet<ProductsRequest, ProductsResponse> { private final ProductAccessor productAccessor; public ProductsServlet() { super(ProductsRequest.class, ProductsResponse.class); CassandraService cassandraService = CassandraService.getInstance(); MappingManager mappingManager = cassandraService.getMappingManager(); this.productAccessor = mappingManager.createAccessor(ProductAccessor.class); } @Override protected void doPost(ProductsRequest request, ProductsResponse response) { List<Product> products = this.productAccessor.all().all(); response.products = products.toArray(new Product[products.size()]); } }
--- uid: System.Xml.Serialization.XmlNamespaceDeclarationsAttribute --- --- uid: System.Xml.Serialization.XmlNamespaceDeclarationsAttribute.#ctor ---
# Change Log ## 0.2.1 - Small fix to standardize the namespace used for both configuration and command. ## 0.2.0 - Added feature to automatically run the command when an editor with the specified language is activated. ## 0.1.1 - Use `registerTextEditorCommand` instead of `registerCommand`. ## 0.1.0 - Initial release.
# frozen_string_literal: true module Resolvers class TopicsResolver < BaseResolver type Types::Projects::TopicType, null: true argument :search, GraphQL::Types::String, required: false, description: 'Search query for topic name.' def resolve(**args) if args[:search].present? ::Projects::Topic.search(args[:search]).order_by_total_projects_count else ::Projects::Topic.order_by_total_projects_count end end end end
# Copyright (C) 2019-2020 Greenweaves Software Limited # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # Optimize flow through a branching network, after West et al-- # A General Model for the Origin of Allometric Scaling Laws in Biology # http://hermes.ffn.ub.es/oscar/Biologia/Escala/Science_276_122_1997.pdf from random import random, seed, choice from ga import evolve,plot_fitness, perturb, perturb_n from matplotlib.pyplot import plot, show, legend, xlabel, ylabel, ylim, title, figure, savefig, subplot from numpy import mean, std from math import sqrt # create_branching_network # # Create a representation of flow though a network # def create_branching_network(c = 10, #Number of levels gamma0 = 0.1): gamma = [gamma0+(1-gamma0)*random() for _ in range(c)] # scale factor for branching - lengths n = [choice([2,4,8,16,32]) for _ in range(c)] # number of branches at each level beta = [1/sqrt(n0) for n0 in n] # scale factor for branching - radii return (beta,gamma,n) # get_resistance # # Calculate resistance using West et al equation (6) def get_resistance(beta, # scale factor for branching - radii gamma, # scale factor for branching - lengths n, # number of branches at each level r_c=1, # initial radius at root of tree l_c=1): # initial length at root of tree r = r_c l = l_c R = [] for k in range(len(beta),0,-1): r /= beta[k-1] l /= gamma[k-1] R.append(l * r**-4) Z = 0 N = 1 for k in range(len(beta)): Z += R[k]/N N *= n[k] return Z # evaluate_branching_network # # The score is 1/resiatnce, as we want a network that minimizes resistance. def evaluate_branching_network(individual): beta, gamma,n = individual return 1/get_resistance(beta,gamma,n) # mutate_branching_network def mutate_branching_network(individual, # Individual to be mutated probability = 0.5, # Probability of mutation sigma = 0.5): # standard deviation for mutating continuous values beta,gamma,n = individual gamma = [perturb(g,probability=probability) for g in gamma] n = [perturb_n(n0,probability=probability) for n0 in n] beta = [1/sqrt(n0) for n0 in n] return beta, gamma,n if __name__=='__main__': import argparse from matplotlib import rc rc('text', usetex=True) parser = argparse.ArgumentParser('Evolve branching network') parser.add_argument('--seed', default=None, type=int, help='Seed for random number generation') parser.add_argument('--N', default=1000, type=int, help='Number of generations') parser.add_argument('--M', default=100, type=int, help='Population size') parser.add_argument('--c', default=10, type=int, help='c') parser.add_argument('--m', default=0.1, type=float, help='mutation probability') parser.add_argument('--gamma', default=0.1, type=float, help='Initial gamma') parser.add_argument('--savefig', default=None, help='File name for saving plots') args = parser.parse_args() seed(args.seed) population,statistics,indices = evolve( N = args.N, M = args.M, create = lambda :create_branching_network(c=args.c, gamma0=args.gamma), evaluate = evaluate_branching_network, mutate = lambda individual:mutate_branching_network(individual,probability=args.m), crossover = lambda population:population) beta,gamma,n = population[indices[-1]] print (std(n)/mean(n), std(beta)/mean(beta), std(gamma)/mean(gamma)) fig=figure(figsize=(10,10)) fig.tight_layout() subplot(211) plot_fitness(statistics,name='Fitness') subplot(212) title('Evolution of Parameters') plot([b/max(beta) for b in beta], 'r', label=r'$\beta$') plot([g/max(gamma) for g in gamma], 'g', label=r'$\gamma$') plot([n0/max(n) for n0 in n], 'b', label='n') legend() if args.savefig!=None: savefig(args.savefig) show()
package redbot.discord.impl.d4j import java.awt.Color import discord4j.core.`object`.entity.{GuildChannel, MessageChannel, PrivateChannel, TextChannel} import discord4j.core.`object`.presence.{Activity, Presence} import discord4j.core.`object`.util.{Permission, Snowflake} import discord4j.core.`object`.{entity => d4j} import discord4j.core.event.domain.message.MessageCreateEvent import discord4j.core.{DiscordClient, DiscordClientBuilder} import reactor.core.scala.publisher.SMono import redbot.discord.Channel.Id import redbot.discord.Embed import redbot.discord.impl.d4j.JavaConversions._ import redbot.discord.impl.d4j.SnowflakeConversions._ import redbot.utils.Logger import redbot.{discord => red} import scala.concurrent.Future final class D4JClient(private val tok: String) extends red.Client(tok) { private val client: DiscordClient = new DiscordClientBuilder(token) .setInitialPresence(Presence.online(Activity.playing(s"Mention me to get started!"))) .build() override def login(): Unit = client.login().block() override lazy val getSelfId: red.User.Id = client.getSelfId .orElseThrow(() => new IllegalStateException("Tried to get self id before client was logged in!")) .as[red.User.Id] override def getUser(id: red.User.Id): Future[red.User] = client.getUserById(Snowflake.of(id)).asScala.map(new User(_)). asFuture override def getPM(id: red.User.Id): Future[red.Channel.Id] = client.getUserById(Snowflake.of(id)).asScala. flatMap(_.getPrivateChannel.asScala). map(_.getId.as[red.Channel.Id]).toFuture override def getChannel(id: red.Channel.Id): Future[red.Channel] = client.getChannelById(Snowflake.of(id)).asScala.map(new Channel(_)) .asFuture override def getGuilds(): Stream[red.Guild.Id] = client.getGuilds().asScala.map(_.getId.as[red.Guild.Id]).toStream() override def getMembers(id: red.Guild.Id): Stream[red.User.Id] = client.getGuildById(Snowflake.of(id)).asScala. flatMapMany(_.getMembers.asScala). map(_.getId.as[red.User.Id]).toStream() override def sendMessage(channel: red.Channel.Id, content: String): Unit = client.getChannelById(Snowflake.of(channel)).flatMap( _.asInstanceOf[MessageChannel].createMessage(content) ).subscribe() override def sendEmbed(channel: Id, embed: Embed): Unit = client.getChannelById(Snowflake.of(channel)) .flatMap(_.asInstanceOf[MessageChannel].createEmbed(spec => { embed.title.map(spec.setTitle) embed.description.map(spec.setDescription) embed.url.map(spec.setUrl) embed.timestamp.map(spec.setTimestamp) embed.color.map(c => spec.setColor(new Color(c))) embed.footer.map(f => spec.setFooter(f.text, f.iconUrl.orNull)) embed.imageUrl.map(spec.setImage) embed.thumbnailUrl.map(spec.setThumbnail) embed.author.map(a => spec.setAuthor(a.name, a.url.orNull, a.iconUrl.orNull)) embed.fields.map(f => spec.addField(f.name, f.value, f.inline)) })).subscribe() override def addMessageListener(handler: red.Message => Unit): Unit = client.getEventDispatcher.on(classOf[MessageCreateEvent]) .subscribe{e => handler(new Message(e.getMessage))} override def setPresence(presence: String): Unit = client.updatePresence(Presence.online(Activity.playing(presence))) .subscribe() override def hasPermission(u: red.User.Id, c: red.Channel.Id, ps: red.Permission*): Future[Boolean] = { client.getChannelById(Snowflake.of(c)).asScala.flatMap { case gc: GuildChannel => gc.getEffectivePermissions(Snowflake.of(u)).asScala.map { d4jPerms => ps.map(D4JClient.permissionMap.apply).forall(d4jPerms.contains(_)) } case pc: PrivateChannel => SMono.just( ps.forall(red.Permission.DM_PERMISSION_SET.contains) ) case _ => throw new IllegalArgumentException("Channel argument was neither a DM channel or a guild channel! :(") }.asFuture } } object D4JClient { val permissionMap = Map[red.Permission, Permission]( red.Permission.ManageChannels -> Permission.MANAGE_CHANNELS ) } final class Message(private val msg: d4j.Message) extends AnyVal with red.Message { override def id: red.Message.Id = msg.getId.as[red.Message.Id] override def content: Option[String] = msg.getContent.toScala override def author: Option[red.User.Id] = msg.getAuthor.toScala.map(_.getId.as[red.User.Id]) override def channel: red.Channel.Id = msg.getChannelId.as[red.Channel.Id] } final class User(private val u: d4j.User) extends AnyVal with red.User { override def id: red.User.Id = u.getId.as[red.User.Id] override def isBot: Boolean = u.isBot override def username: String = u.getUsername override def discrim: String = u.getDiscriminator } final class Channel(private val c: d4j.Channel) extends AnyVal with red.Channel { override def id: red.Channel.Id = c.getId.as[red.Channel.Id] override def isPM: Boolean = c.isInstanceOf[PrivateChannel] }
package com.tiarebalbi.opala.models.compiler import java.io.File import java.time.Duration /** * Compilation summary * * @author Tiarê Balbi Bonamini * @version 1.0.0 */ data class Summary( val duration: Duration, val compiledFiles: Set<File> )
{-# LANGUAGE DeriveDataTypeable #-} module F where import Data.Typeable import Language.Inferno.Solver (TermVar) data Ty b a = TyVar a | TyBool | TyArrow (Ty a b) (Ty a b) | TyProduct (Ty a b) (Ty a b) | TyForall b (Ty a b) | TyMu b (Ty b a) -- skip rectypes for now deriving (Eq, Show, Typeable) type NominalType = Ty Int Int data Tm b a = Var TermVar | Abs TermVar (Ty b a) (Tm b a) | App (Tm b a) (Tm b a) | Let TermVar [a] (Ty b a) (Tm b a) (Tm b a) | TyAbs b (Tm b a) | TyApp (Tm b a) (Ty b a) | Pair (Tm b a) (Tm b a) | Proj Int (Tm b a) | Bool Bool | If (Tm b a) (Tm b a) (Tm b a) deriving (Eq, Show, Typeable) type NominalTerm = Tm Int Int ftyabs :: [b] -> Tm b a -> Tm b a ftyabs [] t = t ftyabs (v:vs) t = TyAbs v (ftyabs vs t) ftyapp :: Tm b a -> [Ty b a] -> Tm b a ftyapp t [] = t ftyapp t (v:vs) = ftyapp (TyApp t v) vs
# --- Created by Ebean DDL # To stop Ebean DDL generation, remove this comment and start using Evolutions # --- !Ups create table genre ( id bigserial not null, name varchar(255), constraint pk_genre primary key (id)) ; create table movie ( id bigserial not null, title varchar(255), summary varchar(255), url varchar(255), genre_id bigint, constraint pk_movie primary key (id)) ; create table users ( id bigserial not null, username varchar(255), password_hash varchar(255), constraint uq_users_username unique (username), constraint pk_users primary key (id)) ; alter table movie add constraint fk_movie_genre_1 foreign key (genre_id) references genre (id); create index ix_movie_genre_1 on movie (genre_id); # --- !Downs drop table if exists genre cascade; drop table if exists movie cascade; drop table if exists users cascade;
package org.nearbyshops.enduserappnew.EditDataScreens.EditItem; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.PopupMenu; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.RecyclerView; import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat; import com.squareup.picasso.Picasso; import org.nearbyshops.enduserappnew.Model.ModelImages.ItemImage; import org.nearbyshops.enduserappnew.Preferences.PrefGeneral; import org.nearbyshops.enduserappnew.R; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by sumeet on 19/12/15. */ public class AdapterItemImages extends RecyclerView.Adapter<RecyclerView.ViewHolder>{ private List<ItemImage> dataset; private Context context; private AppCompatActivity activity; private notificationsFromAdapter notificationReceiver; // final String IMAGE_ENDPOINT_URL = "/api/Images"; public AdapterItemImages(List<ItemImage> dataset, Context context, notificationsFromAdapter notificationReceiver) { this.notificationReceiver = notificationReceiver; this.dataset = dataset; this.context = context; this.activity = activity; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = null; if(viewType==VIEW_TYPE_IMAGE) { v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_item_image,parent,false); return new ViewHolderItemImage(v); } else if(viewType == VIEW_TYPE_ADD_IMAGE) { v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_add_item,parent,false); return new ViewHolderAddItem(v); } return null; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holderGiven, final int position) { if(holderGiven instanceof ViewHolderItemImage) { ViewHolderItemImage holder = (ViewHolderItemImage) holderGiven; holder.copyrights.setText(dataset.get(position-1).getImageCopyrights()); String imagePath = PrefGeneral.getServiceURL(context) + "/api/v1/ItemImage/Image/five_hundred_" + dataset.get(position-1).getImageFilename() + ".jpg"; Drawable placeholder = VectorDrawableCompat .create(context.getResources(), R.drawable.ic_nature_people_white_48px, context.getTheme()); Picasso.get() .load(imagePath) .placeholder(placeholder) .into(holder.itemImage); } } public static final int VIEW_TYPE_ADD_IMAGE = 2; public static final int VIEW_TYPE_IMAGE = 1; @Override public int getItemViewType(int position) { if(position==0) { return VIEW_TYPE_ADD_IMAGE; } else { return VIEW_TYPE_IMAGE; } } @Override public int getItemCount() { return dataset.size()+1; } public class ViewHolderAddItem extends RecyclerView.ViewHolder { @BindView(R.id.list_item) RelativeLayout listItem; public ViewHolderAddItem(View itemView) { super(itemView); ButterKnife.bind(this,itemView); } @OnClick(R.id.list_item) void listItemClick() { // showToastMessage("Add Item Click!"); notificationReceiver.addItemImage(); } } public class ViewHolderItemImage extends RecyclerView.ViewHolder implements PopupMenu.OnMenuItemClickListener { @BindView(R.id.list_item) RelativeLayout listItem; @BindView(R.id.item_image) ImageView itemImage; @BindView(R.id.copyright_info) TextView copyrights; public ViewHolderItemImage(View itemView) { super(itemView); ButterKnife.bind(this,itemView); } @OnClick(R.id.list_item) public void itemCategoryListItemClick() { } @OnClick(R.id.more_options) void optionsOverflowClick(View v) { PopupMenu popup = new PopupMenu(context, v); MenuInflater inflater = popup.getMenuInflater(); inflater.inflate(R.menu.item_image_item_overflow, popup.getMenu()); popup.setOnMenuItemClickListener(this); popup.show(); } @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.action_remove: // showToastMessage("Remove"); notificationReceiver.removeItemImage(dataset.get(getLayoutPosition()-1),getLayoutPosition()-1); break; case R.id.action_edit: // showToastMessage("Edit"); notificationReceiver.editItemImage(dataset.get(getLayoutPosition()-1),getLayoutPosition()-1); break; default: break; } return false; } }// ViewHolder Class declaration ends void showToastMessage(String message) { Toast.makeText(context,message,Toast.LENGTH_SHORT).show(); } public interface notificationsFromAdapter { // method for notifying the list object to request sub category void addItemImage(); void editItemImage(ItemImage itemImage, int position); void removeItemImage(ItemImage itemImage, int position); } }
"use strict"; class MessageControls { constructor() { this.DOM = document.createElement("div"); this.DOM.classList.add("messageControls"); this.input = document.createElement("input"); this.input.classList.add("messageInput"); this.input.placeholder = "message"; this.emojisButton = document.createElement("button"); this.emojisButton.classList.add("button"); this.emojisButton.classList.add("emojisButton"); this.emojisButton.innerText = "emojis"; this.sendButton = document.createElement("button"); this.sendButton.classList.add("button"); this.sendButton.classList.add("sendButton"); this.sendButton.innerText = "send"; document.addEventListener("keypress", (e) => { if(e.keyCode == 13 && this.input == document.activeElement) { this.send(); } }); this.sendButton.onclick = () => this.send(); this.emojisButton.onclick = () => this.showEmojisListener(); this.DOM.append(this.input, this.emojisButton, this.sendButton); } setSendListener(fun) { this.sendListener = fun; } setShowEmojisListener(fun) { this.showEmojisListener = fun; } send() { this.sendListener(this.input.value); } resetMessageInput() { this.input.value = ""; } }
package invdapi import ( "errors" "strconv" "github.com/Invoiced/invoiced-go/invdendpoint" ) type File struct { *Connection *invdendpoint.File } type Files []*File func (c *Connection) NewFile() *File { file := new(invdendpoint.File) return &File{c, file} } func (c *File) Create(file *File) (*File, error) { endpoint := invdendpoint.FileEndpoint fileResp := new(File) // safe prune file data for creation invdFileDataToCreate, err := SafeFileForCreation(file.File) if err != nil { return nil, err } apiErr := c.create(endpoint, invdFileDataToCreate, fileResp) if apiErr != nil { return nil, apiErr } fileResp.Connection = c.Connection return fileResp, nil } func (c *File) Delete() error { endpoint := invdendpoint.FileEndpoint + "/" + strconv.FormatInt(c.Id, 10) err := c.delete(endpoint) if err != nil { return err } return nil } func (c *File) Retrieve(id int64) (*File, error) { endpoint := invdendpoint.FileEndpoint + "/" + strconv.FormatInt(id, 10) custEndpoint := new(invdendpoint.File) file := &File{c.Connection, custEndpoint} _, err := c.retrieveDataFromAPI(endpoint, file) if err != nil { return nil, err } return file, nil } // SafeCustomerForCreation prunes customer data for just fields that can be used for creation of a customer func SafeFileForCreation(file *invdendpoint.File) (*invdendpoint.File, error) { if file == nil { return nil, errors.New("file is nil") } fileData := new(invdendpoint.File) fileData.Name = file.Name fileData.Size = file.Size fileData.Type = file.Type fileData.Url = file.Url return fileData, nil }
<?php /* CONNECT-DB.PHP PHP to connect to your database */ $server = 'localhost'; $user = 'kadyszew_johnk'; $pass = 'Steven12'; $db = 'kadyszew_bio'; $connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ()); mysql_select_db($db) or die ("Could not connect to database ... \n" . mysql_error ()); ?>
const $ = require('jquery'); const _ = require('underscore'); const Backbone = require('backbone'); const examples = require('../examples/index'); const applicationRouter = require('./router'); require('../style/app.less'); var HomeView = Backbone.View.extend({ el: '#view-container', template: _.template([ '<div>This is home view</div>' ].join('')), initialize: function () { this.listenTo(applicationRouter, 'route:home', this.render); }, render: function() { this.$el.html(this.template()); return this; } }); var ApplicationView = Backbone.View.extend({ el: $('body'), events: { 'click .home-menu': 'displayHome', 'click .modelView-menu': 'displayModelView', 'click .collectionView-menu': 'displayCollectionView', 'click .collectionModelView-menu': 'displayCollectionModelView', 'click .layoutView-menu': 'displayLayoutView', 'click .layoutCollection-menu': 'displayLayoutCollection', 'click .cycleView-menu': 'displayCycleView' }, initialize: function(){ this.homeView = new HomeView(); //call to begin monitoring uri and route changes Backbone.history.start(); }, displayHome: function(){ applicationRouter.navigate("home", true); this.homeView.render(); }, displayModelView: function(){ applicationRouter.navigate("modelView", true); }, displayCollectionView: function(){ applicationRouter.navigate("collectionView", true); }, displayCollectionModelView: function(){ applicationRouter.navigate("collectionModelView", true); }, displayLayoutView: function() { applicationRouter.navigate("layoutView", true); }, displayLayoutCollection: function() { applicationRouter.navigate("layoutCollection", true); }, displayCycleView: function() { applicationRouter.navigate("cycleView", true); } }); //load application new ApplicationView();
#[test] fn adder_go() { elrond_wasm_debug::mandos_go("mandos/bmi-token.scen.json"); }
import semver from "semver"; export const isValidBumpArg = (bumpArg: string): boolean => { const validBumpArgs = new Set(["patch", "minor", "major", "from-package"]); // If it isn't a bumpArg in the set and isn't a semver version number if (!validBumpArgs.has(bumpArg) && !semver.valid(bumpArg)) { return false; } return true; };
{-| [@ISO639-1@] fr [@ISO639-2B@] fre [@ISO639-3@] fra [@Native name@] Français [@English name@] French -} module Text.Numeral.Language.FRA.TestData (cardinals, ordinals) where -------------------------------------------------------------------------------- -- Imports -------------------------------------------------------------------------------- import "numerals" Text.Numeral.Grammar import "numerals" Text.Numeral.Grammar ( defaultInflection ) import "numerals" Text.Numeral.Misc ( dec ) import "this" Text.Numeral.Test ( TestData ) -------------------------------------------------------------------------------- -- Test data -------------------------------------------------------------------------------- {- Sources: http://www.sf.airnet.ne.jp/~ts/language/number/french.html http://www.french-linguistics.co.uk/tutorials/numbers/ http://www.parisbypod.com/2007/10/23/french-ordinal-numbers/ -} cardinals :: (Integral i) => TestData i cardinals = [ ( "masculine" , masculine defaultInflection , [ (0, "zéro") , (1, "un") , (2, "deux") , (3, "trois") , (4, "quatre") , (5, "cinq") , (6, "six") , (7, "sept") , (8, "huit") , (9, "neuf") , (10, "dix") , (11, "onze") , (12, "douze") , (13, "treize") , (14, "quatorze") , (15, "quinze") , (16, "seize") , (17, "dix-sept") , (18, "dix-huit") , (19, "dix-neuf") , (20, "vingt") , (21, "vingt et un") , (22, "vingt-deux") , (23, "vingt-trois") , (24, "vingt-quatre") , (25, "vingt-cinq") , (26, "vingt-six") , (27, "vingt-sept") , (28, "vingt-huit") , (29, "vingt-neuf") , (30, "trente") , (31, "trente et un") , (32, "trente-deux") , (33, "trente-trois") , (34, "trente-quatre") , (35, "trente-cinq") , (36, "trente-six") , (37, "trente-sept") , (38, "trente-huit") , (39, "trente-neuf") , (40, "quarante") , (41, "quarante et un") , (42, "quarante-deux") , (43, "quarante-trois") , (44, "quarante-quatre") , (45, "quarante-cinq") , (46, "quarante-six") , (47, "quarante-sept") , (48, "quarante-huit") , (49, "quarante-neuf") , (50, "cinquante") , (51, "cinquante et un") , (52, "cinquante-deux") , (53, "cinquante-trois") , (54, "cinquante-quatre") , (55, "cinquante-cinq") , (56, "cinquante-six") , (57, "cinquante-sept") , (58, "cinquante-huit") , (59, "cinquante-neuf") , (60, "soixante") , (61, "soixante et un") , (62, "soixante-deux") , (63, "soixante-trois") , (64, "soixante-quatre") , (65, "soixante-cinq") , (66, "soixante-six") , (67, "soixante-sept") , (68, "soixante-huit") , (69, "soixante-neuf") , (70, "soixante-dix") , (71, "soixante et onze") , (72, "soixante-douze") , (73, "soixante-treize") , (74, "soixante-quatorze") , (75, "soixante-quinze") , (76, "soixante-seize") , (77, "soixante-dix-sept") , (78, "soixante-dix-huit") , (79, "soixante-dix-neuf") , (80, "quatre-vingts") , (81, "quatre-vingt-un") , (82, "quatre-vingt-deux") , (83, "quatre-vingt-trois") , (84, "quatre-vingt-quatre") , (85, "quatre-vingt-cinq") , (86, "quatre-vingt-six") , (87, "quatre-vingt-sept") , (88, "quatre-vingt-huit") , (89, "quatre-vingt-neuf") , (90, "quatre-vingt-dix") , (91, "quatre-vingt-onze") , (92, "quatre-vingt-douze") , (93, "quatre-vingt-treize") , (94, "quatre-vingt-quatorze") , (95, "quatre-vingt-quinze") , (96, "quatre-vingt-seize") , (97, "quatre-vingt-dix-sept") , (98, "quatre-vingt-dix-huit") , (99, "quatre-vingt-dix-neuf") , (100, "cent") , (101, "cent et un") , (102, "cent deux") , (103, "cent trois") , (104, "cent quatre") , (105, "cent cinq") , (111, "cent et onze") , (122, "cent vingt-deux") , (123, "cent vingt-trois") , (144, "cent quarante-quatre") , (196, "cent quatre-vingt-seize") , (199, "cent quatre-vingt-dix-neuf") , (200, "deux cents") , (300, "trois cents") , (400, "quatre cents") , (500, "cinq cents") , (600, "six cents") , (700, "sept cents") , (800, "huit cents") , (900, "neuf cents") , (1000, "mille") , (1999, "mille neuf cent quatre-vingt-dix-neuf") , (2000, "deux mille") , (2999, "deux mille neuf cent quatre-vingt-dix-neuf") , (dec 4, "dix mille") , (dec 5, "cent mille") , (dec 6, "un million") , (dec 9, "un milliard") , (dec 12, "un billion") , (dec 15, "un billiard") , (dec 18, "un trillion") , (dec 21, "un trilliard") , (dec 24, "un quadrillion") , (dec 27, "un quadrilliard") , (dec 30, "un quintillion") , (dec 33, "un quintilliard") , (dec 36, "un sextillion") , (dec 39, "un sextilliard") , (dec 42, "un septillion") , (dec 45, "un septilliard") , (dec 48, "un octillion") , (dec 51, "un octilliard") , (dec 54, "un nonillion") , (dec 57, "un nonilliard") , (dec 60, "un décillion") , (dec 63, "un décilliard") , (dec 66, "un unodécillion") , (dec 69, "un unodécilliard") , (dec 72, "un duodécillion") , (dec 75, "un duodécilliard") , (dec 78, "un trédécillion") , (dec 81, "un trédécilliard") , (dec 84, "un quattuordécillion") , (dec 87, "un quattuordécilliard") , (dec 90, "un quindécillion") , (dec 93, "un quindécilliard") , (dec 96, "un sexdécillion") , (dec 99, "un sexdécilliard") , (dec 102, "un septendécillion") , (dec 105, "un septendécilliard") , (dec 108, "un octodécillion") , (dec 111, "un octodécilliard") , (dec 114, "un novemdécillion") , (dec 117, "un novemdécilliard") , (dec 120, "un vigintillion") , (dec 123, "un vigintilliard") , (dec 150, "un quinquavigintillion") , (dec 153, "un quinquavigintilliard") , (dec 180, "un trigintillion") , (dec 183, "un trigintilliard") , (dec 210, "un quinquatrigintillion") , (dec 213, "un quinquatrigintilliard") , (dec 240, "un quadragintillion") , (dec 243, "un quadragintilliard") , (dec 270, "un quinquaquadragintillion") , (dec 273, "un quinquaquadragintilliard") , (dec 300, "un quinquagintillion") , (dec 303, "un quinquagintilliard") , (dec 306, "un unoquinquagintillion") , (dec 309, "un unoquinquagintilliard") , (dec 360, "un sexagintillion") , (dec 363, "un sexagintilliard") , (dec 420, "un septuagintillion") , (dec 423, "un septuagintilliard") , (dec 480, "un octogintillion") , (dec 483, "un octogintilliard") , (dec 540, "un nonagintillion") , (dec 543, "un nonagintilliard") , (dec 600, "un centillion") , (dec 603, "un centilliard") ] ) , ( "feminine" , feminine defaultInflection , [ (1, "une") ] ) ] ordinals :: (Integral i) => TestData i ordinals = [ ( "masculine" , masculine defaultInflection , [ (0, "zéroth") , (1, "premier") , (2, "deuxième") , (3, "troisième") , (4, "quatrième") , (5, "cinquième") , (6, "sixième") , (7, "septième") , (8, "huitième") , (9, "neuvième") , (10, "dixième") , (11, "onzième") , (12, "douzième") , (13, "treizième") , (14, "quatorzième") , (15, "quinzième") , (16, "seizième") , (17, "dix-septième") , (18, "dix-huitième") , (19, "dix-neuvième") , (20, "vingtième") , (21, "vingt et unième") , (22, "vingt-deuxième") , (23, "vingt-troisième") , (24, "vingt-quatrième") , (25, "vingt-cinquième") , (26, "vingt-sixième") , (27, "vingt-septième") , (28, "vingt-huitième") , (29, "vingt-neuvième") , (30, "trentième") , (31, "trente et unième") , (32, "trente-deuxième") , (33, "trente-troisième") , (34, "trente-quatrième") , (35, "trente-cinquième") , (36, "trente-sixième") , (37, "trente-septième") , (38, "trente-huitième") , (39, "trente-neuvième") , (40, "quarantième") , (41, "quarante et unième") , (42, "quarante-deuxième") , (43, "quarante-troisième") , (44, "quarante-quatrième") , (45, "quarante-cinquième") , (46, "quarante-sixième") , (47, "quarante-septième") , (48, "quarante-huitième") , (49, "quarante-neuvième") , (50, "cinquantième") , (51, "cinquante et unième") , (52, "cinquante-deuxième") , (53, "cinquante-troisième") , (54, "cinquante-quatrième") , (55, "cinquante-cinquième") , (56, "cinquante-sixième") , (57, "cinquante-septième") , (58, "cinquante-huitième") , (59, "cinquante-neuvième") , (60, "soixantième") , (61, "soixante et unième") , (62, "soixante-deuxième") , (63, "soixante-troisième") , (64, "soixante-quatrième") , (65, "soixante-cinquième") , (66, "soixante-sixième") , (67, "soixante-septième") , (68, "soixante-huitième") , (69, "soixante-neuvième") , (70, "soixante-dixième") , (71, "soixante et onzième") , (72, "soixante-douzième") , (73, "soixante-treizième") , (74, "soixante-quatorzième") , (75, "soixante-quinzième") , (76, "soixante-seizième") , (77, "soixante-dix-septième") , (78, "soixante-dix-huitième") , (79, "soixante-dix-neuvième") , (80, "quatre-vingtième") , (81, "quatre-vingt-unième") , (82, "quatre-vingt-deuxième") , (83, "quatre-vingt-troisième") , (84, "quatre-vingt-quatrième") , (85, "quatre-vingt-cinquième") , (86, "quatre-vingt-sixième") , (87, "quatre-vingt-septième") , (88, "quatre-vingt-huitième") , (89, "quatre-vingt-neuvième") , (90, "quatre-vingt-dixième") , (91, "quatre-vingt-onzième") , (92, "quatre-vingt-douzième") , (93, "quatre-vingt-treizième") , (94, "quatre-vingt-quatorzième") , (95, "quatre-vingt-quinzième") , (96, "quatre-vingt-seizième") , (97, "quatre-vingt-dix-septième") , (98, "quatre-vingt-dix-huitième") , (99, "quatre-vingt-dix-neuvième") , (100, "centième") , (200, "deux centième") , (300, "trois centième") , (400, "quatre centième") , (500, "cinq centième") , (600, "six centième") , (700, "sept centième") , (800, "huit centième") , (900, "neuf centième") , (1000, "millième") , (dec 6, "millionième") , (dec 9, "milliardième") ] ) , ( "feminine" , feminine defaultInflection , [ (1, "première") , (41, "quarante et uneième") ] ) ]
/* * Field * * Controls the aspects of the field, but doesn't display it */ import $ from "jquery"; import { FieldMap } from "./FieldMap"; import { FieldDefaultWidth, FieldDefaultHeight, FieldDefaultHiddenRows, PuyoType, SimulationDefaultPuyoToClear, } from "../constants"; import { PuyoSim } from "../PuyoSim"; import EventTarget from "@ungap/event-target"; declare global { interface Window { chainData?: { id?: number; chain: string; width: number; height: number; hiddenRows: number; popLimit?: number; title?: string; legacyQueryString?: string; }; } } export class Field extends EventTarget { // Field Width (Default = 6) width = FieldDefaultWidth; // Field Height (Default = 12) height = FieldDefaultHeight; // Hidden Rows (Default = 1) hiddenRows = FieldDefaultHiddenRows; // Total height (height + hidden rows) totalHeight = FieldDefaultHeight + FieldDefaultHiddenRows; // A chain is in the URL and can be successfully set chainInURL = false; private map: FieldMap; // The map used during the "editing" portion of the simulator private mapEditor: FieldMap; // The map used during the simulation private mapSimulation?: FieldMap; constructor(readonly sim: PuyoSim) { super(); this.mapEditor = new FieldMap(this.width, this.totalHeight); this.map = this.mapEditor; if (window.chainData) { // We have a chain in the URL. Attempt to use it. this.setChainFromURL(); } } resetMap() { this.mapEditor = new FieldMap(this.width, this.totalHeight); this.map = this.mapEditor; } returnToEditor() { this.map = this.mapEditor; // TODO: make reactive for (let y = 0; y < this.totalHeight; y++) { for (let x = 0; x < this.width; x++) { this.sim.puyoDisplay.renderer.drawPuyo(x, y, this.map.get(x, y)); } } } enterSimulation() { this.mapSimulation = new FieldMap( this.width, this.totalHeight, this.mapEditor ); this.map = this.mapSimulation; } puyo(x: number, y: number) { return this.map.puyo(x, y); } get(x: number, y: number) { return this.map.get(x, y); } set(x: number, y: number, p: PuyoType) { this.map.set(x, y, p); // TODO: make reactive this.sim.puyoDisplay.renderer.drawPuyo(x, y, this.map.map[x][y]); if (!this.sim.puyoDisplay.puyoAnimation.running) { // Redraw all puyo around us if (y > 0) { this.sim.puyoDisplay.renderer.drawPuyo(x, y - 1, this.map.map[x][y - 1]); } if (x > 0) { this.sim.puyoDisplay.renderer.drawPuyo(x - 1, y, this.map.map[x - 1][y]); } if (y < this.height - 1) { this.sim.puyoDisplay.renderer.drawPuyo(x, y + 1, this.map.map[x][y + 1]); } if (x < this.width - 1) { this.sim.puyoDisplay.renderer.drawPuyo(x + 1, y, this.map.map[x + 1][y]); } } } // Sets the chain with the specified width and height setChain(chain: string, w: number, h: number, hr?: number) { let pos: number; w = w || FieldDefaultWidth; h = h || FieldDefaultHeight; hr = hr || FieldDefaultHiddenRows; if (this.sim.simulation.running) { // Stop the simulation this.sim.simulation.back(); } if (w !== this.width || h !== this.height || hr !== this.hiddenRows) { this.width = w; this.height = h; this.hiddenRows = hr; this.totalHeight = h + hr; this.resetMap(); // TODO: make reactive this.sim.puyoDisplay.renderer.uninit(); $("#field").css({ width: this.width * this.sim.puyoDisplay.puyoSize + "px", height: this.totalHeight * this.sim.puyoDisplay.puyoSize + "px", }); $("#field-bg-2").css( "top", this.sim.field.hiddenRows * this.sim.puyoDisplay.puyoSize + "px" ); $("#field-bg-3").css( "height", this.sim.field.hiddenRows * this.sim.puyoDisplay.puyoSize + "px" ); // Refresh the layout. window.dispatchEvent(new Event('resize')); this.sim.puyoDisplay.renderer.init(); $("#field-size-width").val(this.width); $("#field-size-height").val(this.height); $("#field-hidden-rows").val(this.hiddenRows); } pos = chain.length - 1; for (let y = this.totalHeight - 1; y >= 0; y--) { for (let x = this.width - 1; x >= 0; x--) { if (pos < 0) { this.map.set(x, y, PuyoType.None); } else { this.map.set(x, y, parseInt(chain.charAt(pos), 36)); pos--; if (!this.sim.puyoDisplay.renderer) { continue; } this.sim.puyoDisplay.renderer.drawPuyo(x, y, this.map.get(x, y)); if (!this.sim.puyoDisplay.puyoAnimation.running) { // Redraw all puyo around us if (y > 0) { this.sim.puyoDisplay.renderer.drawPuyo( x, y - 1, this.map.get(x, y - 1) ); } if (x > 0) { this.sim.puyoDisplay.renderer.drawPuyo( x - 1, y, this.map.get(x - 1, y) ); } if (y < this.totalHeight - 1) { this.sim.puyoDisplay.renderer.drawPuyo( x, y + 1, this.map.get(x, y + 1) ); } if (x < this.width - 1) { this.sim.puyoDisplay.renderer.drawPuyo( x + 1, y, this.map.get(x + 1, y) ); } } } } } } // Attempts to set the chain from the URL setChainFromURL() { if (!window.chainData) { return; } // Set the chain. setChain takes care of providing default values if they are passed as undefined this.setChain( window.chainData.chain, window.chainData.width, window.chainData.height, window.chainData.hiddenRows ); this.sim.simulation.puyoToClear = window.chainData.popLimit || SimulationDefaultPuyoToClear; $("#puyo-to-clear").val(this.sim.simulation.puyoToClear); this.chainInURL = true; } // Converts mapEditor to a string that can be shared mapToString() { // Add zeros to the front let addZeros = false; // The chain string let chainString = ""; for (let y = 0; y < this.totalHeight; y++) { for (let x = 0; x < this.width; x++) { if (this.mapEditor.puyo(x, y) === PuyoType.None && !addZeros) { continue; // Don't need to add zeros to the front of the string } addZeros = true; chainString += this.mapEditor.puyo(x, y).toString(16); } } return chainString; } }
package no.nav.fo.veilarbregistrering.arbeidssoker.resources import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.Parameter import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.responses.ApiResponses import io.swagger.v3.oas.annotations.tags.Tag import java.time.LocalDate @Tag(name = "ArbeidssokerResource") interface ArbeidssokerApi { @Operation(summary = "Henter alle perioder hvor bruker er registrert som arbeidssøker.") @ApiResponses( ApiResponse(responseCode = "200", description = "Ok"), ApiResponse(responseCode = "400", description = "Ugyldig periode - fra og med dato må være før til dato"), ApiResponse(responseCode = "403", description = "Ingen tilgang"), ApiResponse(responseCode = "500", description = "Ukjent feil") ) fun hentArbeidssokerperioder( @Parameter(required = true, description = "Fødselsnummer") fnr: String, @Parameter(required = true, description = "Fra og med dato") fraOgMed: LocalDate, @Parameter(description = "Til og med dato") tilOgMed: LocalDate? ): ArbeidssokerperioderDto }
@extends('backoffice.template.mainBack') @section('baka') <h2 class="page-section-heading text-center text-uppercase py-5">Modifiez les informations générales</h2> <section class="container"> @if ($errors->any()) <div class="container alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <form class="container d-flex flex-column w-75 pb-5" action="{{ route('bookinks.update', $bookink->id) }}" method="post"> @csrf @method('PUT') {{-- <label class="my-3" for="title">Titre : </label> <div class="d-flex"> <input type="text" value="{{$bookink->title1}}" name="title1" id="title"> <input type="text" value="{{$bookink->title2}}" name="title2" id="title"> <input type="text" value="{{$bookink->title3}}" name="title3" id="title"> </div> <label class="my-3" for="subtitle">Sous-titre : </label> <input type="text" value="{{$bookink->subtitle}}" name="subtitle" id="title"> --}} <label class="my-3" for="adress">Adresse : </label> <input type="text" value="{{ $bookink->adress1 }}" name="adress1" id="adress"> <input class="my-2" type="text" value="{{ $bookink->adress2 }}" name="adress2" id=""> <input type="text" value="{{ $bookink->adress3 }}" name="adress3" id=""> <label class="my-3" for="phone">Numéro de téléphone : </label> <input type="text" value="{{ $bookink->phone }}" name="phone" id="phone"> <label class="my-3" for="">Horaires de la semaine</label> <div class="d-flex flex-column container"> <label for="mday">Lundi : </label> <input value="{{ $bookink->mday }}" type="text" name="mday" id="mday"> <label for="tuday">Mardi : </label> <input value="{{ $bookink->tuday }}" type="text" name="tuday" id="tuday"> <label for="wday">Mercredi : </label> <input value="{{ $bookink->wday }}" type="text" name="wday" id="wday"> <label for="thday">Jeudi : </label> <input value="{{ $bookink->thday }}" type="text" name="thday" id="thday"> <label for="fday">Vendredi : </label> <input value="{{$bookink->fday}}" type="text" name="fday" id="fday"> <label for="satday">Samedi : </label> <input value="{{$bookink->satday}}" type="text" name="satday" id="satday"> <label for="sunday">Dimanche : </label> <input value="{{$bookink->sunday}}" type="text" name="sunday" id="sunday"> </div> <button class="btn btn-success w-25 mt-5" type="submit">Modifier</button> </form> </section> @endsection
#!/bin/bash if [ "$#" -lt 1 ] then printf "\n Usage: cCompiler <input.js> <output.js> \n\n" exit 1 fi INPUT=$1 OUTPUT=$2 if [ ! -e "$INPUT" ] then printf "\nCLOSURE COMPILER - Error: INPUT file '$INPUT' not found.\n\n" exit 1 fi CLOSURE_COMPILER=closure-compiler-v20170218.jar # Create default output filename if needed... if [ -z "$2" ] then OUTPUT="${INPUT%.*}".min.js fi printf "\nCLOSURE COMPILER - Processing: $INPUT >>> $OUTPUT \n\n" java -jar $CLOSURE_COMPILER --js $INPUT --js_output_file $OUTPUT printf "\n... Done !\n\n"
#!/bin/sh curl="curl -S -s" url="http://localhost:55732" metricJson='{ "name": "MyCounter", "description": "this is my metric", "units": "Count" }' metricId=`$curl -XPOST -d "$metricJson" $url/metric | jq -r .data.id` echo MetridId: $metricId dataJson1='{ "metricId": "'"$metricId"'", "value": 10, "timestamp": "2016-09-28T01:10:00.000Z" }' dataJson2='{ "metricId": "'"$metricId"'", "value": 20, "timestamp": "2016-09-28T02:10:00.000Z" }' dataJson3='{ "metricId": "'"$metricId"'", "value": 100, "timestamp": "2016-09-28T03:10:00.000Z" }' dataJson4='{ "metricId": "'"$metricId"'", "value": 101, "timestamp": "2016-09-28T04:10:00.000Z" }' dataId=`$curl -XPOST -d "$dataJson1" $url/data | jq -r .data.id` echo "DataId1: $dataId" dataId=`$curl -XPOST -d "$dataJson2" $url/data | jq -r .data.id` echo "DataId2: $dataId" dataId=`$curl -XPOST -d "$dataJson3" $url/data | jq -r .data.id` echo "DataId3: $dataId" dataId=`$curl -XPOST -d "$dataJson4" $url/data | jq -r .data.id` echo "DataId4: $dataId" sleep 3 reportJson='{ "start": "2016-09-28T00:00:00.000Z", "end": "2016-09-28T12:06:00.000Z", "valueInterval": "10", "dateInterval": "1h" }' $curl -XGET -d "$reportJson" $url/report/$metricId
// //! Copyright 2020 Alibaba Group Holding Limited. //! //! 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. //! pub mod error; pub mod token; use std::convert::{TryFrom, TryInto}; use crate::expr_parse::error::{ExprError, ExprResult}; use crate::expr_parse::token::{tokenize, Token}; use crate::generated::common as pb; use crate::VAR_PREFIX; fn idents_to_vars(idents: Vec<String>) -> ExprResult<pb::VariableKeys> { let mut vars = Vec::with_capacity(idents.len()); for ident in idents { if !ident.starts_with(VAR_PREFIX) { return Err(format!("invalid variable token: {:?}, a variable must start with \"@\"", ident) .as_str() .into()); } else { let var: pb::Variable = ident.into(); vars.push(var) } } Ok(pb::VariableKeys { keys: vars }) } impl TryFrom<Token> for pb::ExprOpr { type Error = ExprError; fn try_from(token: Token) -> ExprResult<Self> { match token { Token::Plus => Ok(pb::Arithmetic::Add.into()), Token::Minus => Ok(pb::Arithmetic::Sub.into()), Token::Star => Ok(pb::Arithmetic::Mul.into()), Token::Slash => Ok(pb::Arithmetic::Div.into()), Token::Percent => Ok(pb::Arithmetic::Mod.into()), Token::Hat => Ok(pb::Arithmetic::Exp.into()), Token::Eq => Ok(pb::Logical::Eq.into()), Token::Ne => Ok(pb::Logical::Ne.into()), Token::Gt => Ok(pb::Logical::Gt.into()), Token::Lt => Ok(pb::Logical::Lt.into()), Token::Ge => Ok(pb::Logical::Ge.into()), Token::Le => Ok(pb::Logical::Le.into()), Token::And => Ok(pb::Logical::And.into()), Token::Or => Ok(pb::Logical::Or.into()), Token::Not => Ok(pb::Logical::Not.into()), Token::Within => Ok(pb::Logical::Within.into()), Token::Without => Ok(pb::Logical::Without.into()), Token::Boolean(b) => Ok(pb::Value::from(b).into()), Token::Int(i) => Ok(pb::Value::from(i).into()), Token::Float(f) => Ok(pb::Value::from(f).into()), Token::String(s) => Ok(pb::Value::from(s).into()), Token::IntArray(v) => Ok(pb::Value::from(v).into()), Token::FloatArray(v) => Ok(pb::Value::from(v).into()), Token::StrArray(v) => Ok(pb::Value::from(v).into()), Token::LBrace => Ok(pb::ExprOpr { item: Some(pb::expr_opr::Item::Brace(0)) }), Token::RBrace => Ok(pb::ExprOpr { item: Some(pb::expr_opr::Item::Brace(1)) }), Token::Identifier(ident) => { if !ident.starts_with(VAR_PREFIX) { Err(format!("invalid variable token: {:?}, a variable must start with \"@\"", ident) .as_str() .into()) } else { let var: pb::Variable = ident.into(); Ok(var.into()) } } Token::IdentArray(idents) => Ok((idents_to_vars(idents)?, false).into()), Token::IdentMap(idents) => Ok((idents_to_vars(idents)?, true).into()), } } } pub trait ExprToken { fn is_operand(&self) -> bool; fn is_left_brace(&self) -> bool; fn is_right_brace(&self) -> bool; /// Returns the precedence of the operator. /// A high precedence means that the operator has larger priority to get operated fn precedence(&self) -> i32; } impl ExprToken for pb::ExprOpr { fn is_operand(&self) -> bool { match self.item { Some(pb::expr_opr::Item::Const(_)) => true, Some(pb::expr_opr::Item::Var(_)) => true, _ => false, } } fn is_left_brace(&self) -> bool { match self.item { Some(pb::expr_opr::Item::Brace(i)) => i == 0, _ => false, } } fn is_right_brace(&self) -> bool { match self.item { Some(pb::expr_opr::Item::Brace(i)) => i == 1, _ => false, } } fn precedence(&self) -> i32 { use pb::expr_opr::Item::*; if self.item.is_some() { match self.item.as_ref().unwrap() { &Arith(a) => { let arith = unsafe { std::mem::transmute::<i32, pb::Arithmetic>(a) }; match arith { pb::Arithmetic::Add | pb::Arithmetic::Sub => 95, pb::Arithmetic::Mul | pb::Arithmetic::Div | pb::Arithmetic::Mod => 100, pb::Arithmetic::Exp => 120, } } &Logical(l) => { let logical = unsafe { std::mem::transmute::<i32, pb::Logical>(l) }; match logical { pb::Logical::Eq | pb::Logical::Ne | pb::Logical::Lt | pb::Logical::Le | pb::Logical::Gt | pb::Logical::Ge | pb::Logical::Within | pb::Logical::Without => 80, pb::Logical::And => 75, pb::Logical::Or => 70, pb::Logical::Not => 110, } } &Brace(_) => 0, _ => 200, } } else { -1 } } } #[allow(dead_code)] /// Turn a sequence of tokens with bracket, into a suffix order pub fn to_suffix_expr<E: ExprToken + std::fmt::Debug>(expr: Vec<E>) -> ExprResult<Vec<E>> { let mut stack: Vec<E> = Vec::with_capacity(expr.len()); let mut results: Vec<E> = Vec::with_capacity(expr.len()); for token in expr { if token.is_operand() { results.push(token); } else if token.is_left_brace() { stack.push(token); } else if token.is_right_brace() { let mut is_left_brace = false; while !stack.is_empty() { let recent = stack.pop().unwrap(); if recent.is_left_brace() { is_left_brace = true; break; } else { results.push(recent); } } if !is_left_brace { return Err(ExprError::UnmatchedLRBraces); } } else { // the operator if stack.is_empty() { stack.push(token); } else { while !stack.is_empty() && stack.last().unwrap().precedence() >= token.precedence() { results.push(stack.pop().unwrap()); } stack.push(token); } } } while !stack.is_empty() { results.push(stack.pop().unwrap()); } Ok(results) } pub fn str_to_expr_pb(expr_str: String) -> ExprResult<pb::Expression> { let mut operators = vec![]; for token in tokenize(&expr_str)? { operators.push(token.try_into()?); } Ok(pb::Expression { operators }) } #[cfg(test)] mod tests { use super::*; use crate::expr_parse::token::tokenize; #[test] fn test_to_suffix_expr() { // 1 + 2 let case1 = tokenize("1 + 2").unwrap(); let expected_case1 = vec![Token::Int(1), Token::Int(2), Token::Plus]; assert_eq!(to_suffix_expr(case1).unwrap(), expected_case1); // 1 + 2 == 3 let case2 = tokenize("1 + 2 == 3").unwrap(); let expected_case2 = vec![Token::Int(1), Token::Int(2), Token::Plus, Token::Int(3), Token::Eq]; assert_eq!(to_suffix_expr(case2).unwrap(), expected_case2); // 1 + 2 * 3 let case3 = tokenize("1 + 2 * 3").unwrap(); let expected_case3 = vec![Token::Int(1), Token::Int(2), Token::Int(3), Token::Star, Token::Plus]; assert_eq!(to_suffix_expr(case3).unwrap(), expected_case3); // (1 + 2) * 3 let case4 = tokenize("(1 + 2) * 3").unwrap(); let expected_case4 = vec![Token::Int(1), Token::Int(2), Token::Plus, Token::Int(3), Token::Star]; assert_eq!(to_suffix_expr(case4).unwrap(), expected_case4); // 1 + 2 ^ 3 > 6 let case5 = tokenize(" 1 + 2 ^ 3 > 6").unwrap(); let expected_case5 = vec![ Token::Int(1), Token::Int(2), Token::Int(3), Token::Hat, Token::Plus, Token::Int(6), Token::Gt, ]; assert_eq!(to_suffix_expr(case5).unwrap(), expected_case5); // (1 + 2) ^ 3 > 6 let case6 = tokenize("(1 + 2) ^ 3 > 6").unwrap(); let expected_case6 = vec![ Token::Int(1), Token::Int(2), Token::Plus, Token::Int(3), Token::Hat, Token::Int(6), Token::Gt, ]; assert_eq!(to_suffix_expr(case6).unwrap(), expected_case6); // ((1 + 2) * 2) ^ 3 == 6 ^ 3 let case7 = tokenize("((1 + 1e-3) * 2) ^ 3 == 6 ^ 3").unwrap(); let expected_case7 = vec![ Token::Int(1), Token::Float(0.001), Token::Plus, Token::Int(2), Token::Star, Token::Int(3), Token::Hat, Token::Int(6), Token::Int(3), Token::Hat, Token::Eq, ]; assert_eq!(to_suffix_expr(case7).unwrap(), expected_case7); } }
package com.openlattice.linking import com.openlattice.data.EntityDataKey import java.util.* /** * @author Drew Bailey (drew@openlattice.com) * Wrapper for Pair<EntityDataKey, Map<EntityDataKey, Map<UUID, Set<Any>>> */ data class Block( val entityDataKey: EntityDataKey, val entities: Map<EntityDataKey, Map<UUID, Set<Any>>> ) { val size = entities.values.map { it.size }.sum() companion object { fun emptyBlock(edk: EntityDataKey): Block { return Block(edk, mapOf(edk to mapOf())) } } }
# PDM Trust-Loader Web Loader for the Wallet User Interface #include "./workdocs/howitworks.md"
#!/bin/bash sudo apt-get install python3 sudo apt-get install python3-pip sudo pip3 install flask tensorflow
# Kasa.Vchasno Client integrated with ```Microsoft.Extensions.DependencyInjection``` and designed to use with IHttpClientFactory
<?php namespace common\modules\user\models; use Yii; use yii\base\Model; class Teacher extends Model{ public $email; public $username; public $password; public $confirmPassword; public $fname; public $lname; public $tel; public function rules() { return[ [['email','username','password','confirmPassword','fname','lname','tel'],'required'], ['confirmPassword', 'compare', 'compareAttribute'=>'password', 'message'=>"รหัสผ่านไม่ตรงกัน" ], ['password', 'string', 'min' => 6, 'max' => 72], ['tel', 'string', 'min' => 10, 'max' => 10,'message'=>'เบอร์โทรศัพทต้องมี 10 ตัว'] ]; } public function attributeLabels() { return [ 'email' => Yii::t('user', 'Email'), 'username' => Yii::t('user', 'ชื่อผู้ใช้งาน'), 'password' => Yii::t('user', 'รหัสผ่าน'), 'confirmPassword' => Yii::t('user', 'ยืนยันรหัสผ่าน'), 'fname' => Yii::t('user', 'ชื่อ'), 'lname' => Yii::t('user', 'นามสกุล'), 'tel' => Yii::t('user', 'เบอร์โทรศัพท์'), ]; } }
package com.tek271.util2.reflection; import org.joor.Reflect; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import static com.google.common.collect.Sets.newHashSet; import static org.joor.Reflect.on; public class MethodReflector<T> { private final T obj; private final Class<?> objClass; private final Reflect reflect; private boolean excludeObjectMethods; private boolean excludeInheritedMethods; private final Set<ScopeEnum> excludedScopes = new HashSet<>(); public MethodReflector(T obj) { this(obj, on(obj)); } private MethodReflector(T obj, Reflect reflect) { this.obj = obj; this.reflect = reflect; this.objClass = obj.getClass(); } public <R> R callFunction(String methodName, Object... args) { return reflect.call(methodName, args).get(); } public void callVoid(String methodName, Object... args) { reflect.call(methodName, args); } public MethodReflector<T> excludeObjectMethods(boolean exclude) { this.excludeObjectMethods = exclude; return this; } public MethodReflector<T> excludeObjectMethods() { return excludeObjectMethods(true); } public MethodReflector<T> excludeInheritedMethods(boolean exclude) { this.excludeInheritedMethods = exclude; return this; } public MethodReflector<T> excludeInheritedMethods() { return excludeInheritedMethods(true); } public MethodReflector<T> excludeScope(Set<ScopeEnum> scopes) { excludedScopes.addAll(scopes); return this; } public MethodReflector<T> excludeScope(ScopeEnum... scopes) { return excludeScope(newHashSet(scopes)); } private Set<Method> getAllMethods() { Class<?> cls = obj.getClass(); Set<Method> methods = newHashSet(cls.getDeclaredMethods()); if (!excludeInheritedMethods) { methods.addAll(newHashSet(cls.getMethods())); } return methods; } private boolean isExcluded(Method method) { if (excludedScopes.contains(ScopeEnum.scopeOf(method))) return true; if (excludeInheritedMethods && isInherited(method)) return true; //noinspection RedundantIfStatement if (excludeObjectMethods && isObjectMethod(method)) return true; return false; } private boolean isIncluded(Method method) { return !isExcluded(method); } private boolean isInherited(Method method) { return !method.getDeclaringClass().equals(objClass); } private boolean isObjectMethod(Method method) { return method.getDeclaringClass().equals(Object.class); } public Set<Method> getMethods() { return getAllMethods().stream().filter(this::isIncluded).collect(Collectors.toSet()); } }
package id.derysudrajat.easyadapter import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import androidx.viewbinding.ViewBinding abstract class EasyAdapter<T, Binding : ViewBinding>( private val data: MutableList<T>, ) : RecyclerView.Adapter<EasyAdapter.ViewHolder>(), EasyListener<T, Binding> { class ViewHolder(view: View) : RecyclerView.ViewHolder(view) private lateinit var binding: Binding override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { binding = create(parent) return ViewHolder(binding.root) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { onBind(binding, data[position]) } override fun getItemCount(): Int = data.size }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.table.runtime.operators.sort; import org.apache.flink.core.memory.MemorySegment; import org.apache.flink.core.memory.MemorySegmentFactory; import org.apache.flink.table.data.DecimalData; import org.apache.flink.table.data.StringData; import org.apache.flink.table.data.binary.BinaryStringData; import org.junit.Test; import java.math.BigDecimal; import java.util.Arrays; import java.util.Random; import static org.assertj.core.api.Assertions.assertThat; /** Test for {@link SortUtil}. */ public class SortUtilTest { @Test public void testNormalizedKey() { int len = 10; Random random = new Random(); MemorySegment[] segments = new MemorySegment[len]; MemorySegment[] compareSegs = new MemorySegment[len]; for (int i = 0; i < len; i++) { segments[i] = MemorySegmentFactory.allocateUnpooledSegment(20); compareSegs[i] = MemorySegmentFactory.allocateUnpooledSegment(20); } { SortUtil.minNormalizedKey(segments[0], 0, 20); SortUtil.maxNormalizedKey(segments[1], 0, 20); for (int i = 0; i < len; i++) { byte[] rndBytes = new byte[20]; random.nextBytes(rndBytes); segments[2].put(0, rndBytes); assertThat(segments[0].compare(segments[2], 0, 0, 20)).isLessThanOrEqualTo(0); assertThat(segments[1].compare(segments[2], 0, 0, 20)).isGreaterThanOrEqualTo(0); } } { DecimalData[] arr = new DecimalData[len]; for (int i = 0; i < len; i++) { arr[i] = DecimalData.fromBigDecimal(new BigDecimal(random.nextInt()), 18, 0); SortUtil.putDecimalNormalizedKey(arr[i], segments[i], 0, 8); } Arrays.sort(arr, DecimalData::compareTo); for (int i = 0; i < len; i++) { SortUtil.putDecimalNormalizedKey(arr[i], compareSegs[i], 0, 8); } Arrays.sort(segments, (o1, o2) -> o1.compare(o2, 0, 0, 8)); for (int i = 0; i < len; i++) { assertThat(compareSegs[i].equalTo(segments[i], 0, 0, 8)).isTrue(); } } { Float[] arr = new Float[len]; for (int i = 0; i < len; i++) { arr[i] = random.nextFloat(); SortUtil.putFloatNormalizedKey(arr[i], segments[i], 0, 4); } Arrays.sort(arr, Float::compareTo); for (int i = 0; i < len; i++) { SortUtil.putFloatNormalizedKey(arr[i], compareSegs[i], 0, 4); } Arrays.sort(segments, (o1, o2) -> o1.compare(o2, 0, 0, 4)); for (int i = 0; i < len; i++) { assertThat(compareSegs[i].equalTo(segments[i], 0, 0, 4)).isTrue(); } } { Double[] arr = new Double[len]; for (int i = 0; i < len; i++) { arr[i] = random.nextDouble(); SortUtil.putDoubleNormalizedKey(arr[i], segments[i], 0, 8); } Arrays.sort(arr, Double::compareTo); for (int i = 0; i < len; i++) { SortUtil.putDoubleNormalizedKey(arr[i], compareSegs[i], 0, 8); } Arrays.sort(segments, (o1, o2) -> o1.compare(o2, 0, 0, 8)); for (int i = 0; i < len; i++) { assertThat(compareSegs[i].equalTo(segments[i], 0, 0, 8)).isTrue(); } } { BinaryStringData[] arr = new BinaryStringData[len]; for (int i = 0; i < len; i++) { arr[i] = BinaryStringData.fromString(String.valueOf(random.nextLong())); SortUtil.putStringNormalizedKey(arr[i], segments[i], 0, 8); } Arrays.sort(arr, StringData::compareTo); for (int i = 0; i < len; i++) { SortUtil.putStringNormalizedKey(arr[i], compareSegs[i], 0, 8); } Arrays.sort(segments, (o1, o2) -> o1.compare(o2, 0, 0, 8)); for (int i = 0; i < len; i++) { assertThat(compareSegs[i].equalTo(segments[i], 0, 0, 8)).isTrue(); } } } }
/** * ************************************************* * Copyright (c) 2019, Grindrod Bank Limited * License MIT: https://opensource.org/licenses/MIT * ************************************************** */ package za.co.grindrodbank.security.service.accesstokenpermissions; public interface AccessTokenPermissionsService { public Boolean hasPermission(String permission); }
module Chewy::Web class Configuration attr_accessor :redis, :queue, :max_history def initialize @queue = :chewy_web @max_history = 20 end end end
using Azure.Data.AppConfiguration; using Azure.Sdk.Tools.CheckEnforcer.Configuration; using Microsoft.Extensions.Azure; using System; using System.Collections.Generic; using System.Text; namespace Azure.Sdk.Tools.CheckEnforcer { public class GlobalConfigurationProvider : IGlobalConfigurationProvider { private ConfigurationClient configurationClient; public GlobalConfigurationProvider(ConfigurationClient configurationClient) { this.configurationClient = configurationClient; } private object applicationIDLock = new object(); private string applicationID; public string GetApplicationID() { if (applicationID == null) { lock(applicationIDLock) { if (applicationID == null) { ConfigurationSetting applicationIDSetting = configurationClient.GetConfigurationSetting( "checkenforcer/github-app-id" ); applicationID = applicationIDSetting.Value; } } } return applicationID; } private object applicationNameLock = new object(); private string applicationName; public string GetApplicationName() { if (applicationName == null) { lock (applicationNameLock) { if (applicationName == null) { ConfigurationSetting applicationNameSetting = configurationClient.GetConfigurationSetting( "checkenforcer/check-name" ); applicationName = applicationNameSetting.Value; } } } return applicationName; } private object maxRequestsPerPeriodLock = new object(); private int maxRequestsPerPeriod = -1; public int GetMaxRequestsPerPeriod() { if (maxRequestsPerPeriod == -1) { lock (maxRequestsPerPeriodLock) { if (maxRequestsPerPeriod == -1) { ConfigurationSetting applicationNameSetting = configurationClient.GetConfigurationSetting( "checkenforcer/max-requests-per-period" ); maxRequestsPerPeriod = int.Parse(applicationNameSetting.Value); } } } return maxRequestsPerPeriod; } private object periodDurationInSecondsLock = new object(); private int periodDurationInSeconds = -1; public int GetPeriodDurationInSeconds() { if (periodDurationInSeconds == -1) { lock (periodDurationInSecondsLock) { if (periodDurationInSeconds == -1) { ConfigurationSetting applicationNameSetting = configurationClient.GetConfigurationSetting( "checkenforcer/period-duration-in-seconds" ); periodDurationInSeconds = int.Parse(applicationNameSetting.Value); } } } return periodDurationInSeconds; } } }
Authors: - [Josh Speagle](https://github.com/joshspeagle) Contributors: - [Gus Beane](https://github.com/gusbeane) - [Catherine Zucker](https://github.com/catherinezucker) - [Phil Cargile](https://github.com/pacargile) - [Greg Green](https://github.com/gregreen) - [Ben Johnson](https://github.com/bd-j) - [Eddie Schlafly](https://github.com/schlafly)
#!/usr/bin/env bash ## test ci echo "$DOCKER_PASSWORD" | docker login --username "$DOCKER_USERNAME" --password-stdin docker build --tag odyseeteam/commentron:$TRAVIS_BRANCH ./ docker push odyseeteam/commentron:$TRAVIS_BRANCH
#!/bin/bash # Adapted from https://gist.github.com/domenic/ec8b0fc8ab45f39403dd set -e REPO=`git config remote.origin.url` SSH_REPO=${REPO/https:\/\/github.com\//git@github.com:} cd scripts/deploy # Get the deploy key by using Travis's stored variables to decrypt deploy_key.enc ENCRYPTED_KEY_VAR="encrypted_${ENCRYPTION_LABEL}_key" ENCRYPTED_IV_VAR="encrypted_${ENCRYPTION_LABEL}_iv" ENCRYPTED_KEY=${!ENCRYPTED_KEY_VAR} ENCRYPTED_IV=${!ENCRYPTED_IV_VAR} openssl aes-256-cbc -K $ENCRYPTED_KEY -iv $ENCRYPTED_IV -in ./deploy_key.enc -out ./deploy_key -d chmod 600 deploy_key eval `ssh-agent -s` ssh-add ./deploy_key cd ../.. rm -rf doc/ || true git clone $REPO --branch gh-pages --single-branch --depth 1 doc scripts/build_docs.sh cd doc/ git config user.name "Travis CI" git config user.email $DEPLOY_COMMIT_AUTHOR_EMAIL git add -A git commit -m "Docs for v$(npm info .. version)" git push $SSH_REPO $TARGET_BRANCH
## Release 1.4.0 ### Summary First Puppet Labs supported release of this module! Contains new features and bug fixes for tests. #### Features: - New readme file added for tests. Also several new tests added. - Addition of handling in tests to run with Debian 8. #### Bug Fixes: - Tests tweaked to handle several Debian versions. - Fixed acceptance tests for Windows. ## Release 1.3.0 ### Summary This release adds documentation updates, test improvements, and os support. #### Features: - Acceptance testing on Linux platforms - Rewritten documentation, inclusion of strings for automated documentation. - Linting of manifest to conform to style guidelines. - Adds support for several operating systems: - Debian 6, 7 - CentOS 5, 6, 7 - Oracle Linux 6, 7 - Scientific Linux 5, 6, 7 ### 2014-10-31 Release 1.2.0 ### Summary - Add content parameter to allow setting static motd content ## 2014-07-15 Release 1.1.1 ###Summary This release merely updates metadata.json so the module can be uninstalled and upgraded via the puppet module command. ## 2014-05-28 Release 1.1.0 ###Summary The main feature of this release is support for external templates. It also includes documentation and testing improvements. ####Features - Added class parameter to support external templates - Updated README documentation - Improved Testing ####Fixes - Add LICENSE file ####Known Bugs
-- SELECT * FROM HR.EMPLOYEES; declare -- store the retive data in bellow varible f_name varchar(20); l_name varchar(20); begin select FIRST_NAME,LAST_NAME into f_name,l_name FROM HR.EMPLOYEES WHERE EMPLOYEE_ID=100000; -- output of the varible dbms_output.put_line(f_name|| ' ' || l_name); select FIRST_NAME,LAST_NAME into f_name,l_name FROM HR.EMPLOYEES WHERE EMPLOYEE_ID=101; dbms_output.put_line(f_name|| ' ' || l_name); exception when NO_DATA_FOUND THEN dbms_output.put_line('no such recordes'); end; /
Ore-Ore Language ================ A ultra primitive programming language that is a bit like Lisp * [Demo](https://yamahei.github.io/orelang/index.html) Overview -------- ![screen](/img/screen-min.png) * JavaScript製オレオレ言語の実行環境 * Lisp風?文法 * FizzBuzzまでは動いた * 構文木からフローチャート描画 * [Viz.js](http://viz-js.com/)を利用 Usage ----- ### ソースコード ![code](/img/title-code-min.png) ここにソースコードを記述します。 文法はサンプルコードとソースコードをご参照ください。 ### サンプルコード ![sample](/img/title-sample-min.png) Hello worldからFizzBuzzまで、4つのサンプルコードを準備しました。 クリックすると`Code`にコピーします。 ### フローチャート ![flow](/img/title-flow-min.png) `Code`の内容からフローチャートを描画します。 ### 実行結果 ![output](/img/title-output-min.png) `Code`の内容を実行した結果を出力します。
/* SQL Exercise: Name: Average Population. [Easy] Link: https://www.hackerrank.com/challenges/average-population/problem */ SELECT FLOOR(AVG(POPULATION)) FROM CITY;
#!/usr/bin/env python # requirements: apt install git wget python gcc flex bison make import platform import subprocess if subprocess.call('which sudo', shell=True) == 0: with_sudo = 'sudo ' else: with_sudo = '' major = int(platform.release().split('.')[0]) minor = int(platform.release().split('.')[1]) revision = int(platform.release().split('.')[2].split('-')[0]) url_kernel = 'https://mirrors.edge.kernel.org/pub/linux/kernel/v%d.x/linux-%d.%d.tar.gz' % (major, major, minor) tarfile = 'linux-%d.%d.tar.gz' % (major, minor) source_dir = 'linux-%d.%d' % (major, minor) print('URL: ', url_kernel) print('TarFile: ', tarfile) subprocess.call('rm -r %s' % (source_dir), shell=True) subprocess.call('rm %s' % (tarfile), shell=True) subprocess.call('wget %s' % (url_kernel) , shell=True) subprocess.call('tar xf %s && make -j -C %s/tools/perf' % (tarfile, source_dir) , shell=True) subprocess.call(with_sudo + 'cp %s/tools/perf/perf /usr/bin/' % (source_dir) , shell=True) subprocess.call('rm -r %s' % (source_dir), shell=True) subprocess.call('rm %s' % (tarfile), shell=True) subprocess.call('ls -lah /usr/bin/perf', shell=True) #get kernelversion #wget http://www.kernel.org/pub/linux/kernel/v2.6/testing/linux-2.6.33-rc3.tar.bz2
import 'package:flutter/material.dart'; import 'package:pikapika/basic/Method.dart'; import 'package:pikapika/screens/components/ContentLoading.dart'; import '../basic/Common.dart'; import 'components/RightClickPop.dart'; class ModifyPasswordScreen extends StatefulWidget { const ModifyPasswordScreen({Key? key}) : super(key: key); @override State<StatefulWidget> createState() => _ModifyPasswordScreenState(); } class _ModifyPasswordScreenState extends State<ModifyPasswordScreen> { late bool _loading = false; late String _oldPassword = ""; late String _newPassword = ""; late String _newPasswordRep = ""; @override Widget build(BuildContext context){ return RightClickPop(buildScreen(context)); } Widget buildScreen(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("修改密码"), ), body: _loading ? Stack( children: [ const ContentLoading(label: "请稍后"), WillPopScope( child: Container(), onWillPop: () async { return false; }, ), ], ) : _buildForm(), ); } Widget _buildForm() { return ListView( children: [ const Divider(), ListTile( title: const Text("旧密码"), subtitle: Text(_oldPassword == "" ? "未填写" : '\u2022' * 10), onTap: () async { String? input = await displayTextInputDialog( context, src: _oldPassword, title: '旧密码', hint: '请输入旧密码', isPasswd: true, ); if (input != null) { setState(() { _oldPassword = input; }); } }, ), const Divider(), ListTile( title: const Text("新密码"), subtitle: Text(_newPassword == "" ? "未填写" : '\u2022' * 10), onTap: () async { String? input = await displayTextInputDialog( context, src: _newPassword, title: '新密码', hint: '请输入新密码', isPasswd: true, ); if (input != null) { setState(() { _newPassword = input; }); } }, ), const Divider(), ListTile( title: const Text("重复输入新密码"), subtitle: Text(_newPasswordRep == "" ? "未填写" : '\u2022' * 10), onTap: () async { String? input = await displayTextInputDialog( context, src: _newPasswordRep, title: '重复输入新密码', hint: '请重复输入新密码', isPasswd: true, ); if (input != null) { setState(() { _newPasswordRep = input; }); } }, ), const Divider(), Container( margin: const EdgeInsets.all(10), child: MaterialButton( textColor: Colors.white, color: Theme.of(context).appBarTheme.backgroundColor, onPressed: () async { if (_newPasswordRep != _newPassword) { defaultToast(context, "新密码不匹配"); return; } setState(() { _loading = true; }); try { await method.updatePassword(_oldPassword, _newPassword); defaultToast(context, "修改成功"); Navigator.of(context).pop(); } catch (e) { defaultToast(context, "失败 : $e"); setState(() { _loading = false; }); } }, child: const Text("确认"), ), ), ], ); } }
// Reference - https://kotlinlang.org/docs/reference/using-gradle.html // Update at 20190705 import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet import org.jetbrains.kotlin.gradle.tasks.KotlinCompile group = "shijian.su" version = "0.0.1-SNAPSHOT" plugins { kotlin("jvm") version "1.3.41" } repositories { jcenter() } dependencies { // implementation(kotlin("stdlib")) // Java6 // implementation(kotlin("stdlib-jdk7")) // Java7 implementation(kotlin("stdlib-jdk8")) // Java8 // use Kotlin reflection implementation(kotlin("reflect")) // use testing facilities testImplementation(kotlin("test")) testImplementation(kotlin("test-junit")) } // To specify additional compilation options, use the kotlinOptions property of a Kotlin compilation task. tasks.withType<KotlinCompile> { kotlinOptions.suppressWarnings = true } sourceSets["main"].withConvention(KotlinSourceSet::class) { kotlin.srcDir("part-1-introducing-kotlin/src/main/kotlin") kotlin.srcDir("part-2-embracing-kotlin/src/main/kotlin") }
#!/bin/bash USAGE_TXT=" usage: $0 This is a front-end for Linux- and MacOS- maxiconda installers. It fetches the appropriate and most recent maxiconda installer for the current OS/CPU, checks the SHA256 signature and then runs it. " OS=`uname -s` case $OS in "Linux") OS_NAME="Linux" ;; "Darwin") OS_NAME="MacOS" ;; *) printf "WOOPS: OS '%s' is not yet implemented...\\n" $OS exit 1 ;; esac CPU=`uname -m` case $CPU in "x86_64") CPU_NAME="x86_64" ;; "aarch64") CPU_NAME="aarch64" ;; "arm64") CPU_NAME="arm64" ;; *) printf "WOOPS: CPU '%s' is not yet implemented...\\n" $OS exit 1 ;; esac ## URI's & COMMANDS ### BASE_URL="https://github.com/Semi-ATE/maxiconda/releases/latest/download/" VERSION_URL="https://github.com/Semi-ATE/maxiconda/releases/latest/" [[ `curl -s $VERSION_URL` =~ [^0-9]+([^\"]+)\" ]] VERSION=${BASH_REMATCH[1]} INSTALLER="maxiconda-$VERSION-$OS_NAME-$CPU_NAME.sh" RUN_INSTALLER="bash $INSTALLER" SHA256="$INSTALLER.sha256" INSTALLER_URL="$BASE_URL$INSTALLER" DOWNLOAD_INSTALLER="curl -SL $INSTALLER_URL --output $INSTALLER" SHA256_URL="$BASE_URL$SHA256" DOWNLOAD_SHA256="curl -SL $SHA256_URL --output $SHA256" if [ "$OS_NAME" == "MacOS" ]; then SHASUM="shasum ./$INSTALLER" else SHA256SUM="sha256sum ./$INSTALLER" fi printf "\\nStep #1: Downloading '$INSTALLER'\\n" printf -- "-------------------------------------------------------------------------------\\n" $DOWNLOAD_INSTALLER printf "\\nStep #2: Downloading '$SHA256'\\n" printf -- "-------------------------------------------------------------------------------\\n" $DOWNLOAD_SHA256 printf "\\nStep #3: Checking installer integrity ..." CALCULATED_CHECKSUM=$(shasum -a 256 "./$INSTALLER" | cut -d' ' -f1) GIVEN_CHECKSUM=$(head -n 1 $SHA256 | cut -d' ' -f1) if [ "$CALCULATED_CHECKSUM" == "$GIVEN_CHECKSUM" ] then printf "PASS\\n" else printf "FAIL:\\n" printf "Calculated: '%s'\\n" $CALCULATED_CHECKSUM printf " Given: '%s'\\n" $GIVEN_CHECKSUM exit 1 fi printf -- "-------------------------------------------------------------------------------\\n" printf "\\nStep #4: Installing '$INSTALLER $PTA'\\n" printf -- "-------------------------------------------------------------------------------\\n" $RUN_INSTALLER printf "\\nStep #5: Cleaning up ... " `rm -f $INSTALLER` `rm -f $SHA256` printf "Done.\\n" printf -- "-------------------------------------------------------------------------------\\n" printf "\\nYou are all set and ready to go!\\n"
; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py ; RUN: llc -mtriple=thumbv8.1m.main-none-eabi -mattr=+mve -o - %s | FileCheck %s ; RUN: llc -mtriple=thumbv8.1m.main-none-eabi -mattr=+mve.fp -o - %s | FileCheck --check-prefix=CHECK --check-prefix=CHECK-FP %s define <16 x i8> @vector_add_i8(<16 x i8> %lhs, <16 x i8> %rhs) { ; CHECK-LABEL: vector_add_i8: ; CHECK: @ %bb.0: @ %entry ; CHECK-NEXT: vmov d1, r2, r3 ; CHECK-NEXT: vmov d0, r0, r1 ; CHECK-NEXT: mov r0, sp ; CHECK-NEXT: vldrw.u32 q1, [r0] ; CHECK-NEXT: vadd.i8 q0, q0, q1 ; CHECK-NEXT: vmov r0, r1, d0 ; CHECK-NEXT: vmov r2, r3, d1 ; CHECK-NEXT: bx lr entry: %sum = add <16 x i8> %lhs, %rhs ret <16 x i8> %sum } define <8 x i16> @vector_add_i16(<8 x i16> %lhs, <8 x i16> %rhs) { ; CHECK-LABEL: vector_add_i16: ; CHECK: @ %bb.0: @ %entry ; CHECK-NEXT: vmov d1, r2, r3 ; CHECK-NEXT: vmov d0, r0, r1 ; CHECK-NEXT: mov r0, sp ; CHECK-NEXT: vldrw.u32 q1, [r0] ; CHECK-NEXT: vadd.i16 q0, q0, q1 ; CHECK-NEXT: vmov r0, r1, d0 ; CHECK-NEXT: vmov r2, r3, d1 ; CHECK-NEXT: bx lr entry: %sum = add <8 x i16> %lhs, %rhs ret <8 x i16> %sum } define <4 x i32> @vector_add_i32(<4 x i32> %lhs, <4 x i32> %rhs) { ; CHECK-LABEL: vector_add_i32: ; CHECK: @ %bb.0: @ %entry ; CHECK-NEXT: vmov d1, r2, r3 ; CHECK-NEXT: vmov d0, r0, r1 ; CHECK-NEXT: mov r0, sp ; CHECK-NEXT: vldrw.u32 q1, [r0] ; CHECK-NEXT: vadd.i32 q0, q0, q1 ; CHECK-NEXT: vmov r0, r1, d0 ; CHECK-NEXT: vmov r2, r3, d1 ; CHECK-NEXT: bx lr entry: %sum = add <4 x i32> %lhs, %rhs ret <4 x i32> %sum } define <2 x i64> @vector_add_i64(<2 x i64> %lhs, <2 x i64> %rhs) { ; CHECK-FP-LABEL: vector_add_i64: ; CHECK-FP: @ %bb.0: @ %entry ; CHECK-FP-NEXT: .save {r7, lr} ; CHECK-FP-NEXT: push {r7, lr} ; CHECK-FP-NEXT: vmov d1, r2, r3 ; CHECK-FP-NEXT: vmov d0, r0, r1 ; CHECK-FP-NEXT: add r0, sp, #8 ; CHECK-FP-NEXT: vldrw.u32 q1, [r0] ; CHECK-FP-NEXT: vmov r1, s2 ; CHECK-FP-NEXT: vmov r0, s3 ; CHECK-FP-NEXT: vmov r3, s6 ; CHECK-FP-NEXT: vmov r2, s7 ; CHECK-FP-NEXT: adds.w lr, r1, r3 ; CHECK-FP-NEXT: vmov r3, s0 ; CHECK-FP-NEXT: vmov r1, s4 ; CHECK-FP-NEXT: adc.w r12, r0, r2 ; CHECK-FP-NEXT: vmov r2, s1 ; CHECK-FP-NEXT: vmov r0, s5 ; CHECK-FP-NEXT: adds r1, r1, r3 ; CHECK-FP-NEXT: vmov.32 q0[0], r1 ; CHECK-FP-NEXT: adcs r0, r2 ; CHECK-FP-NEXT: vmov.32 q0[1], r0 ; CHECK-FP-NEXT: vmov.32 q0[2], lr ; CHECK-FP-NEXT: vmov.32 q0[3], r12 ; CHECK-FP-NEXT: vmov r0, r1, d0 ; CHECK-FP-NEXT: vmov r2, r3, d1 ; CHECK-FP-NEXT: pop {r7, pc} entry: %sum = add <2 x i64> %lhs, %rhs ret <2 x i64> %sum } define <8 x half> @vector_add_f16(<8 x half> %lhs, <8 x half> %rhs) { ; CHECK-FP-LABEL: vector_add_f16: ; CHECK-FP: @ %bb.0: @ %entry ; CHECK-FP-NEXT: vmov d1, r2, r3 ; CHECK-FP-NEXT: vmov d0, r0, r1 ; CHECK-FP-NEXT: mov r0, sp ; CHECK-FP-NEXT: vldrw.u32 q1, [r0] ; CHECK-FP-NEXT: vadd.f16 q0, q0, q1 ; CHECK-FP-NEXT: vmov r0, r1, d0 ; CHECK-FP-NEXT: vmov r2, r3, d1 ; CHECK-FP-NEXT: bx lr entry: %sum = fadd <8 x half> %lhs, %rhs ret <8 x half> %sum } define <4 x float> @vector_add_f32(<4 x float> %lhs, <4 x float> %rhs) { ; CHECK-FP-LABEL: vector_add_f32: ; CHECK-FP: @ %bb.0: @ %entry ; CHECK-FP-NEXT: vmov d1, r2, r3 ; CHECK-FP-NEXT: vmov d0, r0, r1 ; CHECK-FP-NEXT: mov r0, sp ; CHECK-FP-NEXT: vldrw.u32 q1, [r0] ; CHECK-FP-NEXT: vadd.f32 q0, q0, q1 ; CHECK-FP-NEXT: vmov r0, r1, d0 ; CHECK-FP-NEXT: vmov r2, r3, d1 ; CHECK-FP-NEXT: bx lr entry: %sum = fadd <4 x float> %lhs, %rhs ret <4 x float> %sum } define <2 x double> @vector_add_f64(<2 x double> %lhs, <2 x double> %rhs) { ; CHECK-FP-LABEL: vector_add_f64: ; CHECK-FP: @ %bb.0: @ %entry ; CHECK-FP-NEXT: .save {r4, r5, r6, r7, lr} ; CHECK-FP-NEXT: push {r4, r5, r6, r7, lr} ; CHECK-FP-NEXT: .pad #4 ; CHECK-FP-NEXT: sub sp, #4 ; CHECK-FP-NEXT: .vsave {d8, d9} ; CHECK-FP-NEXT: vpush {d8, d9} ; CHECK-FP-NEXT: mov r5, r0 ; CHECK-FP-NEXT: add r0, sp, #40 ; CHECK-FP-NEXT: vldrw.u32 q4, [r0] ; CHECK-FP-NEXT: mov r4, r2 ; CHECK-FP-NEXT: mov r6, r3 ; CHECK-FP-NEXT: mov r7, r1 ; CHECK-FP-NEXT: vmov r2, r3, d9 ; CHECK-FP-NEXT: mov r0, r4 ; CHECK-FP-NEXT: mov r1, r6 ; CHECK-FP-NEXT: bl __aeabi_dadd ; CHECK-FP-NEXT: vmov r2, r3, d8 ; CHECK-FP-NEXT: vmov d9, r0, r1 ; CHECK-FP-NEXT: mov r0, r5 ; CHECK-FP-NEXT: mov r1, r7 ; CHECK-FP-NEXT: bl __aeabi_dadd ; CHECK-FP-NEXT: vmov d8, r0, r1 ; CHECK-FP-NEXT: vmov r2, r3, d9 ; CHECK-FP-NEXT: vmov r0, r1, d8 ; CHECK-FP-NEXT: vpop {d8, d9} ; CHECK-FP-NEXT: add sp, #4 ; CHECK-FP-NEXT: pop {r4, r5, r6, r7, pc} entry: %sum = fadd <2 x double> %lhs, %rhs ret <2 x double> %sum }
# Introduction This is the technical handbook for [Wazimap NG](https://openup.org.za/products/wazimap-ng) This is intended for * Profile administrators - how to configure profiles * Developers - how we work on this project. Profile administrators should see the [Profile Curation Guide](https://openup.gitbook.io/wazimap-ng/).
require 'rails_helper' RSpec.describe Storage, type: :model do fixtures :bots fixtures :users fixtures :storages let :storage do Storage.find(1) end describe '#bot' do it 'Presence' do expect(storage).to validate_presence_of(:bot) end end end
<?php namespace Easyutil\Utilities; class Status { /** const SUCCESS constante responsável pela resposta de Sucesso nas requisições */ const SUCCESS = 00; /** const UNAUTHORIZED constante responsável pela resposta de Inautorizado nas requisições */ const ERROR = 01; /** const ERROR_VALIDATION constante responsável pela resposta de Erro nas Validações das requisições */ const ERROR_VALIDATION = 02; /** const API_SUCCESS constante responsável pela resposta de Sucesso nas requisições */ const API_SUCCESS = 200; /** @var string CREATED constante para identificar sucesso/criado */ const API_CREATED = 201; /** const ERROR_VALIDATION constante responsável pela resposta de Erro nas Validações das requisições */ const API_ERROR_VALIDATION = 400; /** const UNAUTHORIZED constante responsável pela resposta de Inautorizado nas requisições */ const UNAUTHORIZED = 401; /** const NOT_FOUND constante responsável pela resposta de Inexistente nas requisições */ const NOT_FOUND = 404; /** @var string CONFLICT constante para identificar conflito de parâmetros */ const CONFLICT = 409; /** @var string UNPROCESSABLE_ENTITY constante para identificar falha na validação */ const UNPROCESSABLE_ENTITY = 422; /** const INTERNAL_ERROR constante responsável pela resposta de Erro Interno das requisições */ const INTERNAL_ERROR = 500; }
package com.akinci.recipelist.features.listing.di import com.akinci.recipelist.BuildConfig import com.akinci.recipelist.common.di.AppModule import com.akinci.recipelist.common.network.NetworkChecker import com.akinci.recipelist.features.listing.data.api.ContentService import com.akinci.recipelist.features.acommon.data.local.RecipeDAO import com.akinci.recipelist.features.acommon.data.local.RecipeMapper import com.akinci.recipelist.features.listing.repository.RecipeRepository import com.contentful.java.cda.CDAClient import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object ListingModule { @Provides @Singleton fun provideCDAClient( @AppModule.BaseURL baseUrl: String ): CDAClient = CDAClient.builder().apply { setSpace(BuildConfig.CDA_SPACE) setToken(BuildConfig.CDA_TOKEN) setEndpoint(baseUrl) }.build() @Provides @Singleton fun provideCDAService( client : CDAClient, recipeMapper: RecipeMapper ) = ContentService(client, recipeMapper) @Provides @Singleton fun provideRecipeRepository( localService: RecipeDAO, remoteService: ContentService, networkChecker: NetworkChecker ) = RecipeRepository(localService, remoteService, networkChecker) }
# PCB's ontwerpen ## **Voorkennis** heel weinig tot geen voorkennis de les was zeer theoretisch en soms moeilijk om te volgen soms ook langdraadig Tip: de les van AppInventor was zeer praktijk ingesteld en iedereen was makkelijk mee ##**Les** ![work]({{ site.baseurl }}/assets/work.png)
const len: u32 = 8; pub fn main() { calculate_passwords(245182, 790572); } fn calculate_passwords(min: u32, max: u32) { let mut valid_passwords = 0; for password in min..max+1 { if validate_password(password) { valid_passwords += 1 } } println!("valid passwords: {}", valid_passwords); } fn validate_password(password_int: u32) -> bool { let mut last_last_digit = 10; let mut last_digit = 10; let mut matching: bool = false; // Working backwards for i in 1..len-1 { let digit = (password_int % 10u32.pow(i)) / 10u32.pow(i-1); if last_digit == digit && last_last_digit != digit { matching = true; } if matching && last_last_digit == digit { matching = false } // Rule 2. Digits must increment in size. if last_digit < digit { return false } last_last_digit = last_digit; last_digit = digit; } matching } #[cfg(test)] mod tests { // Note this useful idiom: importing names from outer (for mod tests) scope. use super::*; #[test] fn test_ones() { assert_eq!(validate_password(111111), false); } #[test] fn test_not_decreasing() { assert_eq!(validate_password(223450), false); } #[test] fn test_nodouble() { assert_eq!(validate_password(123789), false); } #[test] fn test_pairs() { assert_eq!(validate_password(112233), true); } #[test] fn test_notriple() { assert_eq!(validate_password(123444), false); } #[test] fn test_one_double() { assert_eq!(validate_password(111122), true); } }
@{ Layout = "_Layout"; } @using HairSalon.Models; @model HairSalon.Models.Stylist; <h2>Stylist Details</h2> <br> <h3>@Html.DisplayNameFor(model => model.Name): @Html.DisplayFor(model => model.Name)</h3> @if(@Model.Clients.Count == 0) { <p>This stylist currently has no clients.</p> } @foreach (Client client in @Model.Clients) { <li>Client Name: @client.Name</li> } <p>@Html.ActionLink("Add a Client", "Create", "Clients")</p> <p>@Html.ActionLink("Return to Stylists", "Index")</p> <p>@Html.ActionLink("Return to HomePage", "Index", "Home")</p>
// Generate map pins : // medium.com/welldone-software/map-pins-using-svg-path-9fdfebb74501 // The pin is defined by 4 points : // - A is the tip of the pin // - C is the center of the circle (top part of the pin) // - B (left) and D (right) are the two points where the circle // connects with the straight lines going to A // The shape is A --> B ~~> D --> A // where --> is a straight line // and ~~> a circle arc revolving around C // dX is the horizontal delta between A and D (and negative for B) // dY is the vertical delta between A and B && A and D (negative for // both as SVG Y is growing downwards) export function pinPath(radius, height) { const alpha = Math.acos(radius / (height - radius)) const deltaX = radius * Math.sin(alpha) const deltaY = height * (height - radius * 2) / (height - radius) const Ax = 0, Ay = 0, Bx = -deltaX, By = -deltaY, Dx = deltaX, Dy = -deltaY return `M ${Ax},${Ay} L ${Bx},${By} A ${radius} ${radius} 1 1 1 ${Dx},${Dy} L ${Ax},${Ay} z` } export function pinViewBox(radius, height, strokeWidth = 0) { // strokeWidth += 1 // nice antialiased curves get out of range const boxWidth = radius * 2 + strokeWidth * 2 const boxHeight = height + strokeWidth * 2 const left = 0 - (radius + strokeWidth) const top = 0 - (height + strokeWidth) return `${left} ${top} ${boxWidth} ${boxHeight}` }
namespace Grimoire.Line.Api.Webhook.Event { public record UnFollowEvent : BaseEvent { } }
# ZPSnowing 本Demo主要介绍如何利用CADisplayLink定时器来实现下雪动画的。 视频路径:小马哥视频2015年(没加密版)——>03-UI进阶——>0617-Quartz2D——>视频——>10-定时器(雪花)_.mkv。
<?php namespace Drupal\commerce_order; use Drupal\commerce_order\Entity\OrderInterface; use Drupal\commerce_price\Calculator; use Drupal\commerce_price\Price; use Drupal\commerce_price\RounderInterface; use Drupal\Core\Entity\EntityTypeManagerInterface; class PriceSplitter implements PriceSplitterInterface { /** * The currency storage. * * @var \Drupal\Core\Entity\EntityStorageInterface */ protected $currencyStorage; /** * The rounder. * * @var \Drupal\commerce_price\RounderInterface */ protected $rounder; /** * Constructs a new PriceSplitter object. * * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager * The entity type manager. * @param \Drupal\commerce_price\RounderInterface $rounder * The rounder. */ public function __construct(EntityTypeManagerInterface $entity_type_manager, RounderInterface $rounder) { $this->currencyStorage = $entity_type_manager->getStorage('commerce_currency'); $this->rounder = $rounder; } /** * {@inheritdoc} */ public function split(OrderInterface $order, Price $amount, $percentage = NULL) { if (!$percentage) { // The percentage is intentionally not rounded, for maximum precision. $percentage = Calculator::divide($amount->getNumber(), $order->getSubtotalPrice()->getNumber()); } // Calculate the initial per-order-item amounts using the percentage. // Round down to ensure that their sum isn't larger than the full amount. $amounts = []; foreach ($order->getItems() as $order_item) { if (!$order_item->getTotalPrice()->isZero()) { $individual_amount = $order_item->getTotalPrice()->multiply($percentage); $individual_amount = $this->rounder->round($individual_amount, PHP_ROUND_HALF_DOWN); $amounts[$order_item->id()] = $individual_amount; $amount = $amount->subtract($individual_amount); } } // The individual amounts don't add up to the full amount, distribute // the reminder among them. if (!$amount->isZero()) { /** @var \Drupal\commerce_price\Entity\CurrencyInterface $currency */ $currency = $this->currencyStorage->load($amount->getCurrencyCode()); $precision = $currency->getFractionDigits(); // Use the smallest rounded currency amount (e.g. '0.01' for USD). $smallest_number = Calculator::divide('1', pow(10, $precision), $precision); $smallest_amount = new Price($smallest_number, $amount->getCurrencyCode()); while (!$amount->isZero()) { foreach ($amounts as $order_item_id => $individual_amount) { $amounts[$order_item_id] = $individual_amount->add($smallest_amount); $amount = $amount->subtract($smallest_amount); if ($amount->isZero()) { break 2; } } } } return $amounts; } }
""" This file not meant to be modified to configure a local nor a production instance. To configure the instance, please consider: - editing a ".env" file at the root of the "oxe-api" directory - passing the environment variables via "-e" flag if you use a docker container """ import os from dotenv import load_dotenv load_dotenv() def _getenv(key, default=None, mandatory=True): if mandatory: if key in os.environ or default is not None: return os.getenv(key, default) raise KeyError("environment variable '%s' not set" % key) return os.getenv(key, default) ENVIRONMENT = _getenv('ENVIRONMENT', default='dev') JWT_SECRET_KEY = _getenv('JWT_SECRET_KEY', mandatory=True) DB_CONFIG = { 'drivername': _getenv('DB_DRIVER', default='mysql+pymysql'), 'host': _getenv('DB_HOSTNAME', default='localhost'), 'port': _getenv('DB_PORT', default='3306'), 'database': _getenv('DB_NAME', default='OPENXECO'), 'username': _getenv('DB_USERNAME', default='openxeco'), 'password': _getenv('DB_PASSWORD', mandatory=True), 'query': {'charset': _getenv('DB_CHARSET', default='utf8mb4')}, } MAIL_SERVER = _getenv('MAIL_SERVER', mandatory=False) MAIL_PORT = _getenv('MAIL_PORT', mandatory=False) MAIL_USERNAME = _getenv('MAIL_USERNAME', mandatory=False) MAIL_PASSWORD = _getenv('MAIL_PASSWORD', mandatory=False) MAIL_USE_TLS = _getenv('MAIL_USE_TLS', default="True") MAIL_USE_SSL = _getenv('MAIL_USE_SSL', default="True") MAIL_DEFAULT_SENDER = _getenv('MAIL_DEFAULT_SENDER', mandatory=True) HTTP_PROXY = _getenv('HTTP_PROXY', mandatory=False) # if set the initial admin must issue a forgot password request # this implies mail delivery is properly configured INITIAL_ADMIN_EMAIL = _getenv('INITIAL_ADMIN_EMAIL', mandatory=False) IMAGE_FOLDER = _getenv('IMAGE_FOLDER', default="/openxeco_image") DOCUMENT_FOLDER = _getenv('DOCUMENT_FOLDER', default="/openxeco_document") CORS_DOMAINS = _getenv('CORS_DOMAINS', mandatory=ENVIRONMENT != "dev", default="localhost:\\d*" if ENVIRONMENT == "dev" else None) # remove extra spaces, remove empty items domains = filter(len, map(str.strip, CORS_DOMAINS.split(","))) # pylint: disable=unnecessary-lambda CORS_ORIGINS = list(map(lambda d: r'((http|https)://)?(.*\.)?{}'.format(d), domains))
package org.clulab.pdf2txt.preprocessor import org.clulab.pdf2txt.common.utils.{Test, TextRange} class ParagraphPreprocessorTest extends Test { val preprocessor = new ParagraphPreprocessor() behavior of "ParagraphPreprocessor" def test(inputText: String, expectedOutputText: String): Unit = { it should s"convert ${escape(inputText)}" in { val actualOutputText = preprocessor.preprocess(inputText).toString actualOutputText shouldBe expectedOutputText } } test("p1p2", "p1p2 .") test("p1 p2", "p1 p2 .") test("p1 p2", "p1 p2 .") test("p1\np2", "p1\np2 .") test("p1\n\np2", "p1 .\n\np2 .") test("p1\n\n\np2", "p1 .\n\n\np2 .") test("p1\n \np2", "p1\n \np2 .") test("p1\r\np2", "p1\r\np2 .") test("p1\r\n\r\np2", "p1 .\r\n\r\np2 .") test("p1\r\n\r\n\r\np2", "p1 .\r\n\r\n\r\np2 .") test("p1\r\n \r\np2", "p1\r\n \r\np2 .") test("p1\r\rp2", "p1\r\rp2 .") }
<?php namespace Pecee\Translation\Providers; interface ITranslationProvider { /** * Called when looking up single key * @param string $key * @return string */ public function lookup($key); /** * Init method * @param string $locale */ public function load($locale); }
#include "MFRCTagReader.h" bool MFRCTagReader::begin() { #ifdef MFRC_SIGNAL_PIN pinMode(MFRC_SIGNAL_PIN, OUTPUT); digitalWrite(MFRC_SIGNAL_PIN, LOW); #endif device->PCD_SoftPowerDown(); device->PCD_SoftPowerUp(); device->PCD_Reset(); device->PCD_Init(); const bool selfTestOk = device->PCD_PerformSelfTest(); Serial.printf("MFRC: RFID self-test: %s\n", selfTestOk ? "ok" : "failed"); device->PCD_Init(); if (!selfTestOk) return false; return true; } void MFRCTagReader::addOnConnectCallback(const std::function<void(byte *)> &callback) { this->onDetectCallbacks.push_back(callback); } void MFRCTagReader::onTagConnected(byte *uuid) { #ifdef MFRC_SIGNAL_PIN digitalWrite(MFRC_SIGNAL_PIN, HIGH); #endif for (auto &callback: onDetectCallbacks) callback(uuid); } void MFRCTagReader::addOnDisconnectCallback(const std::function<void(void)> &callback) { this->onDisconnectCallbacks.push_back(callback); } void MFRCTagReader::onTagDisconnected() { #ifdef MFRC_SIGNAL_PIN digitalWrite(MFRC_SIGNAL_PIN, LOW); #endif for (auto &callback: onDisconnectCallbacks) callback(); } bool MFRCTagReader::write(byte *data, int size) { resettingTagWriteSince = millis(); for (int i = 0; i < 5; i++) { rfid->unselectMifareTag(true); delay(50); if (rfid->detectTag()) { if (rfid->writeRaw(1, data, size) > 0) { return true; } } } logger->println("MFRC: Write failure!!! Cancelling reset, disconnecting"); resettingTagWriteSince = 0; tagConnectedPublic = false; tagConnected = false; onTagDisconnected(); return false; } bool MFRCTagReader::read(byte *byte, const int size) { resettingTagReadSince = millis(); for (int i = 0; i < 5; i++) { rfid->unselectMifareTag(true); delay(50); if (rfid->detectTag()) { const int readResult = rfid->readRaw(1, byte, size); // all data has to be read if (readResult == size) { return true; } } } logger->println("MFRC: Read failure!!! Cancelling reset, disconnecting"); resettingTagReadSince = 0; tagConnectedPublic = false; tagConnected = false; onTagDisconnected(); return false; } void MFRCTagReader::checkTagPresented() { const uint64_t now = millis(); if (resettingTagReadSince > 0 && now - resettingTagReadSince >= MFRC_RESET_TIMEOUT) { logger->println("MFRC: Read-resetting timeout, disconnecting"); resettingTagReadSince = 0; resettingTagWriteSince = 0; tagConnectedPublic = false; tagConnected = false; onTagDisconnected(); return; } if (resettingTagWriteSince > 0 && now - resettingTagWriteSince >= MFRC_RESET_TIMEOUT) { logger->println("MFRC: Write-resetting timeout, disconnecting"); resettingTagWriteSince = 0; resettingTagReadSince = 0; tagConnectedPublic = false; tagConnected = false; onTagDisconnected(); return; } if (!tagConnected) { if (device->PICC_IsNewCardPresent() && device->PICC_ReadCardSerial()) { tagConnected = true; tagConnectedPublic = true; std::copy(device->uid.uidByte, device->uid.uidByte + MFRC_UID_LENGTH, lastUID); if (resettingTagWriteSince > 0) { #ifdef MFRC_DEBUG logger->println("MFRC: Not connecting, tag being write-reset; tag reset done"); #endif resettingTagWriteSince = 0; } else { if (resettingTagReadSince > 0) { #ifdef MFRC_DEBUG logger->println("MFRC: Not connecting, tag being read-reset; tag reset done"); #endif resettingTagReadSince = 0; } else { #ifdef MFRC_DEBUG logger->println("MFRC: Connecting, not being reset"); #endif onTagConnected(device->uid.uidByte); } } } } if (tagConnected) { uint8_t control = 0x00; for (int i = 0; i < 3; i++) { if (!device->PICC_IsNewCardPresent()) { if (device->PICC_ReadCardSerial()) { control |= 0x16; } if (device->PICC_ReadCardSerial()) { control |= 0x16; } control += 0x1; } control += 0x4; } if (control == 13 || control == 14) { //card is still there return; } } if (tagConnected) { if (resettingTagWriteSince == 0) { if (resettingTagReadSince == 0) { tagConnectedPublic = false; #ifdef MFRC_DEBUG logger->println("MFRC: Disconnecting, not being reset"); #endif onTagDisconnected(); } else { #ifdef MFRC_DEBUG logger->println("MFRC: Not disconnecting, tag being read-reset; tag reset done"); #endif } } else { tagConnectedPublic = true; // don't admit the tag is reconnecting #ifdef MFRC_DEBUG logger->println("MFRC: Not disconnecting, tag being write-reset"); #endif } } tagConnected = false; device->PICC_HaltA(); device->PCD_StopCrypto1(); rfid->unselectMifareTag(true); }
package matcher func (m *Matcher) Package(input string) bool { return m.packageName.MatchString(input) }
learningruby ============ learningruby Revising and perfecting OOP
package main import ( "fmt" "os" "path/filepath" "strings" "github.com/mitchellh/cli" "github.com/shirou/gopsutil/process" ) type uninstallCommand struct{} func (i *uninstallCommand) Help() string { return "" } func (i *uninstallCommand) Synopsis() string { return "uninstalls kite" } func (i *uninstallCommand) Run(args []string) int { var ui cli.Ui ui = &cli.BasicUi{ Reader: os.Stdin, Writer: os.Stdout, ErrorWriter: os.Stderr, } prefix := "[uninstaller] " ui = &cli.PrefixedUi{ AskPrefix: prefix, AskSecretPrefix: prefix, OutputPrefix: prefix, InfoPrefix: prefix, ErrorPrefix: prefix, WarnPrefix: prefix, Ui: ui, } if err := uninstall(ui, false); err != nil { return 1 } return 0 } func uninstall(ui cli.Ui, rollback bool) error { localManager := newLocalManager() // first, try to shutdown kited via systemd service ui.Info("removing kite-autostart systemd service") _ = stopAndDisableAutostartService() // terminate kited and copilot before uninstalling // an error isn't critical here, continue with uninstall ui.Info("terminating kite processes") _ = terminateProcesses(localManager.basePath, "kite", "kited") // this isn't critical, continue with uninstall when an error occurred ui.Info("removing kite-updater systemd service") _ = stopAndDisableUpdaterService() err := removeBindataFiles(ui) if err != nil { ui.Error(fmt.Sprintf("failed to remove system files: %s", err.Error())) rollbarError("failed to remove system files", "uninstall", err) return err } if !exists(localManager.basePath) { if !rollback { ui.Info("kite is uninstalled. we'd love to hear your thoughts! give us some feedback@kite.com") } return nil } err = os.RemoveAll(localManager.basePath) if err != nil { if !rollback { ui.Error(fmt.Sprintf("error removing %s: %s", tildify(localManager.basePath), err.Error())) } rollbarError("failed to remove kited base path", "uninstall", err) } ui.Info(fmt.Sprintf("removed %s", tildify(localManager.basePath))) if !rollback { ui.Info("kite is uninstalled. we'd love to hear your thoughts! give us some feedback@kite.com") } return nil } func exists(path string) bool { _, err := os.Stat(path) if err == nil { return true } return os.IsExist(err) } func terminateProcesses(baseDir string, processNames ...string) error { executable, _ := os.Executable() executableName := filepath.Base(executable) processes, err := process.Processes() if err != nil { return err } // kill processes in the given order // we don't want to let Copilot spawn another instance of kited, for example for _, query := range processNames { for _, p := range processes { // e.g. "kite" or "kited" name, _ := p.Name() // e.g. /home/user/.local/share/kite/kite-v2.20190516.0/linux-unpacked/kite // or /home/user/.local/share/kite/kite-v2.20190516.0/kited exe, _ := p.Exe() // only terminate processes which match the given name // and have an executable stored in the base dir // take care not to terminate the current process, which is also stored in baseDir matchingName := name == query || filepath.Base(exe) == query isCurrent := strings.Contains(name, executableName) inBaseDir := strings.Index(exe, baseDir) == 0 if matchingName && !isCurrent && inBaseDir { _ = p.Terminate() } } } return nil }
/** * Person.js * * @description :: TODO: You might write a short summary of how this model works and what it represents here. * @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models */ module.exports = { schema: true, attributes: { // ADDRESS city : 'string', zipCode : 'string', locality : 'string', publicPlace : 'string', complement : 'string', // CHARACTERISTICS OF HOUSEHOLD characteristics : 'string', typeHousehold : 'string', typeWaterSupply : 'string', toiletBathroom : 'string', lightingUsed : 'string', // FAMILY familyType : 'string', //IDENTIFICATION OF THE PERSON fullName : 'string', gender : 'string', skinColor : 'string', motherName : 'string', fatherName : 'string', steganoImage : 'string', updateSteganoImage : 'string', keepImage : 'boolean' } };
package common; import static org.junit.jupiter.api.DynamicTest.dynamicTest; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; /** * Common test implementation for all type and field remove tests. * * @author olibroe * */ public abstract class CommonRemoveTest extends CommonTest { /** * Abstract definition of a remove test case. * Always needed: * - testname * - file to execute the remove on * - expected file * - typename: the type that is either removed or from which a field is removed * * @author olibroe * */ protected abstract class RemoveTestDefinition { private String testname; private String file; private String expectedFile; private String typename; RemoveTestDefinition(String testname, String file, String expectedFile, String typename) { this.testname = testname; this.file = file; this.expectedFile = expectedFile; this.typename = typename; } } /** * Define type remove test. * * @author olibroe * */ protected class RemoveTypeTestDefinition extends RemoveTestDefinition { public RemoveTypeTestDefinition(String testname, String file, String expectedFile, String typename) { super(testname, file, expectedFile, typename); } } /** * Define field remove test. * * @author olibroe * */ protected class RemoveFieldTestDefinition extends RemoveTestDefinition { private String fieldname; public RemoveFieldTestDefinition(String testname, String file, String expectedFile, String typename, String fieldname) { super(testname, file, expectedFile, typename); this.fieldname = fieldname; } } // holds test definitions protected List<RemoveTestDefinition> removeTestDefinitions = new ArrayList<>(); /** * Execute defined tests. * Only the arguments needed for field/type removal are set here, all others are set in executeCliTest(...). * * @return * @throws Exception */ @TestFactory Stream<DynamicTest> dynamicTests() throws Exception { return removeTestDefinitions.stream() .map(def -> dynamicTest(def.testname, () -> { List<String> args = new ArrayList<>(); args.add("-rm"); if (def instanceof RemoveFieldTestDefinition) { args.add("-f"); args.add(def.typename + "." + ((RemoveFieldTestDefinition) def).fieldname); } else { args.add("-t"); args.add(def.typename); } executeCliTest(def.file, def.expectedFile, args); })); } }