text
stringlengths 27
775k
|
---|
Given(/^I navigate to the email repeat demo page$/) do
click_link('email-repeat/demo')
end
Given(/^I have not filled out the email field$/) do
# Nothing to do
end
Then(/^I do not see an email repeat hint$/) do
assert_no_selector('.email-hint', :text => 'Please ensure your email address is displayed correctly below')
assert_no_selector('.email-hint', :text => @email)
end
Given(/^I have filled out the email field$/) do
@email = '[email protected]'
fill_in('email', :with => @email)
end
When(/^I observe the repeated email$/) do
# Nothing to do
end
Then(/^I see my email address as I typed it$/) do
assert_selector('.email-hint', :text => 'Please ensure your email address is displayed correctly below')
assert_selector('.email-hint', :text => @email)
end
When(/^I delete the email$/) do
fill_in('email', :with => '')
end
When(/^I fill out the email field with another email$/) do
@email = '[email protected]'
fill_in('email', :with => @email)
end
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Extract data from sqlite database, and convert into
dict, dataframe, ...
Tong Zhang <[email protected]>
2017-10-12 14:10:56 PM EDT
"""
from argparse import ArgumentParser
import os
import sqlite3
import sys
parser = ArgumentParser(prog=os.path.basename(sys.argv[0]),
description="Convert SQLite database into table.")
parser.add_argument("--format", dest="fmt", default='json',
help="Output file format, 'csv' or 'json'")
parser.add_argument("db", help="File name of SQLite database.")
parser.add_argument("outfile", help="File name of output table.")
parser.add_argument("--tab", action="append",
help="Table name from database")
if len(sys.argv) < 2:
parser.print_help()
sys.exit(1)
args = parser.parse_args(sys.argv[1:])
db, fmt, outfile = args.db, args.fmt, args.outfile
tab = ['function'] if args.tab is None else args.tab
conn = sqlite3.connect(db)
c = conn.cursor()
for t in tab:
c.execute("SELECT * FROM {}".format(t))
header = [desc[0] for desc in c.description]
if fmt == 'json':
d = []
for line in c:
d.append(dict(zip(header, line)))
import json
json.dump(d, open(outfile, 'wb'), indent=2, sort_keys=True)
if fmt == 'csv':
import csv
with open(outfile, 'wb') as f:
w = csv.writer(f)
w.writerow(header)
w.writerows(c.fetchall())
|
@JS('Leaflet.Util')
library leafletjs_dart.bind.Util;
import 'dart:js';
import 'package:js/js.dart';
@JS()
external int stamp(var obj);
String toJSON(JsObject obj) {
JsFunction cntx = context['JSON']['stringify'];
return cntx.apply([obj]);
}
JsObject toJs(var obj){
return new JsObject.jsify(obj);
} |
#!/bin/bash
export ROOT_HOME=/home/jooho/dev/Managed_Git/operator-projects #Update (For demo, use "/tmp")
export TMP_HOME=/tmp
# Set the release version for operator sdk
export SDK_RELEASE_VERSION=v1.4.0 #Update latest version v1.4.0
export KUSTOMIZE_VERSION=3.10.0
export OPM_VERSION=1.16.1
# Operator Info
export REPO_URL=github.com/jooho/isv-must-gather-operator
export NEW_OP_NAME=isv-must-gather-operator
export NEW_OP_HOME=${ROOT_HOME}/${NEW_OP_NAME}
export NAMESPACE=${NEW_OP_NAME}
# Images Info
export VERSION=0.2.0
export IMG_TAG=${VERSION}
export IMG=quay.io/jooholee/${NEW_OP_NAME}:${IMG_TAG}
export BUNDLE_TAG=0.2.0
export BUNDLE_IMG=quay.io/jooholee/${NEW_OP_NAME}-bundle:${BUNDLE_TAG}
export INDEX_TAG=0.2.0
export INDEX_IMG=quay.io/jooholee/${NEW_OP_NAME}-index:${INDEX_TAG}
export CHANNELS=alpha
export DEFAULT_CHANNEL=alpha
# CRD Info
export CRD_DOMAIN=operator.com
export CRD_GROUP=isv
export CRD_VERSION=v1alpha1
export CRD_KIND=MustGather
export SMOKE_MUST_GATHER_TAG=all |
import { StackNavigator } from 'react-navigation';
import MainTab from './MainTab';
import Preview from '../views/Preview';
const AppModal = StackNavigator({
app: MainTab,
preview: {
screen: Preview,
navigationOptions: {
gesturesEnabled: false,
},
},
}, {
mode: 'modal',
});
export default AppModal;
|
#!/usr/bin/perl
#
# Rootnode::Password
# Rootnode http://rootnode.net
#
# Copyright (C) 2009-2012 Marcin Hlybin
# All rights reserved.
#
package Rootnode::Password;
use warnings;
use strict;
use Exporter;
use Readonly;
our @ISA = qw(Exporter);
our @EXPORT = qw(apg);
Readonly my $MINLEN => 8;
Readonly my $MAXLEN => 20;
sub apg {
my $minlen = shift || $MINLEN;
my $maxlen = shift || $MAXLEN;
# generate pronunciation if third argument present
my $with_p = shift;
my $opts = defined $with_p ? '-t' : '';
# generate password
my $password_string = `apg -a 0 -n 1 -m $minlen -x $maxlen -M NCL $opts` or die 'Cannot run apg';
my ($password, $pronunciation) = split /\s/, $password_string;
return ( $password, $pronunciation ) if $with_p;
return $password;
}
1;
|
#ifndef BULLET_H
#define BULLET_H
#include <OgreException.h>
#include <OgreConfigFile.h>
#include <OgreSceneManager.h>
#include <OgreEntity.h>
#include <OgreMeshManager.h>
#include <OgreRoot.h>
#include "creep.h"
class bullet
{
public:
bullet(std::string id, Ogre::Vector3 destination, Ogre::SceneManager& sceneManager, Ogre::Vector3 pos);
virtual ~bullet();
bool Update(Ogre::SceneManager& sceneManager, Creep& creep);
protected:
private:
float speed;
Ogre::Vector3 direction;
std::string name;
Ogre::Vector3 pos;
//Ogre::Vector3 destinations;
Ogre::Vector3 dest;
Ogre::Real distance;
};
#endif // BULLET_H
|
import React, { useEffect, useState } from 'react';
import { useManageStatus } from '../../hooks';
import {
deriveStatus,
meetingStatus,
meetingStatusToClassName,
} from '../../util';
const { EXPIRED } = meetingStatus;
function SideBarEvent({
event,
forceRender,
setClickSelected,
showModal,
}) {
const { start, end, eventStatus: checkedIn } = event;
const [status, setStatus] = useState(deriveStatus({ start, end, checkedIn }));
useManageStatus({
checkedIn,
end,
setStatus,
start,
status,
});
useEffect(() => {
forceRender()
}, [status]);
return (
<div
onClick={() => {
showModal();
setClickSelected({ ...event });
}}
className={`${meetingStatusToClassName[status]} event`}
>
{status === EXPIRED
? (<h5>
{event.student} - <span className="no-show-span">no show</span>
</h5>
) : (<h5>{event.student}</h5>)
}
<p>
{event.mentor === ''.trim()
? 'No mentor has been assigned'
: `${event.title} with ${event.mentor}.`
}
</p>
</div>
);
}
export default SideBarEvent;
|
---
title: Microsoft.Windows.Kits.Hardware.DiagnosticSummary
description: Microsoft.Windows.Kits.Hardware.DiagnosticSummary
MSHAttr:
- 'PreferredSiteName:MSDN'
- 'PreferredLib:/library/windows/hardware'
ms.assetid: 252C2265-3173-4A16-8A60-FE07032B7C27
author: EliotSeattle
ms.author: eliotgra
ms.date: 10/15/2017
ms.topic: article
ms.prod: windows-hardware
ms.technology: windows-oem
---
# Microsoft.Windows.Kits.Hardware.DiagnosticSummary
- [BugcheckSummary Class](bugchecksummary-class.md)
- [DiagnosticSummaryLog Class](diagnosticsummarylog-class.md)
ย
ย
|
struct Invariant<'a> {
f: Box<dyn FnOnce(&mut &'a isize) + 'static>,
}
fn to_same_lifetime<'r>(b_isize: Invariant<'r>) {
let bj: Invariant<'r> = b_isize;
}
fn to_longer_lifetime<'r>(b_isize: Invariant<'r>) -> Invariant<'static> {
b_isize
//~^ ERROR lifetime may not live long enough
}
fn main() {
}
|
import * as React from 'react';
import keyboardManagerContext from './keyboard_manager_context';
interface Props {
/**
* Disables input. Used for visualization.
*/
disabled: boolean,
/**
* Value of intensity reading.
*/
intensity: number,
/**
* To be called by the component to update the intensity reading.
*/
setIntensity: Function
/**
* Constant speed for when the indicator jumps
*/
jump_speed: number
/**
* Acceleration constant. Speed is reduced by this number on every timestep.
*/
falling_constant: number,
/**
* Indicates how the intensity is input
*/
input: {
device: 'keyboard' | 'gamepad'
/**
* Increase intensity
*/
up: string
}
}
interface State {
speed: number
}
class OneDInterval extends React.Component<Props, State> {
static defaultProps = {
jump_speed: 1 / 10,
falling_constant: 5 / 600
}
// animation params
state: State = {
speed: 0
}
container = React.createRef<HTMLDivElement>()
indicator = React.createRef<HTMLDivElement>()
observer:ResizeObserver = null
containerHeight: number = 0
// animation req_id
reqId: number = null
componentDidMount() {
// start animation
this.reqId = requestAnimationFrame(this.animationRender)
// update the height of the container
this.observer = new ResizeObserver((entries) => {
this.containerHeight = entries[0].contentRect.height - 20
})
this.observer.observe(this.container.current)
// init intensity
this.props.setIntensity(0)
this.context.addEvents(this.keyboardEvents)
}
componentWillUnmount() {
this.context.removeEvents(this.keyboardEvents)
cancelAnimationFrame(this.reqId)
this.observer.disconnect()
}
keyboardEvents = {
'up': {
key: 'ArrowUp',
description: 'Increase',
handler: () => {
this.setState({
speed: this.props.jump_speed
})
}
}
}
update = (timestamp: any) => {
let delta_time = 1
let intensity = Math.max(0, Math.min(1, this.props.intensity + this.state.speed * delta_time))
let speed = this.state.speed - this.props.falling_constant * delta_time
this.setState({
speed: speed
})
this.props.setIntensity(intensity)
}
animationRender = (timestamp: any) => {
if(!this.props.disabled) this.update(timestamp)
this.reqId = requestAnimationFrame(this.animationRender);
}
render() {
const position = Math.round(this.props.intensity * this.containerHeight)
return <div ref={this.container} className='gui-vertical'>
<div ref={this.indicator} className='gui-indicator' style={{ bottom: position}}></div>
</div>
}
}
OneDInterval.contextType = keyboardManagerContext
export { OneDInterval } |
/*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.plugin.ij.core;
import com.intellij.openapi.module.Module;
import gw.plugin.ij.util.GosuModuleUtil;
import org.jetbrains.annotations.NotNull;
public class IJModuleNode extends UnidirectionalCyclicGraph.Node<Module> {
public IJModuleNode(@NotNull Module module) {
super(module.getName(), module);
for (Module dependency : GosuModuleUtil.getDependencies(module)) {
addLink(dependency.getName());
}
}
}
|
module Lexer where
lexer :: String -> String -> [String]
lexer [] stack = [reverse stack | not $ null stack]
lexer ('\"':xs) stack = lexStr xs $ '\"':stack
lexer (x:xs) stack
| x == ' ' || x == '\n' = if null stack
then lexer xs []
else reverse stack:lexer xs []
| otherwise = lexer xs $ x:stack
lexStr :: String -> String -> [String]
lexStr ('\"':xs) stack = lexer xs $ '\"':stack
lexStr (x:xs) stack = lexStr xs $ x:stack
lexStr [] stack = ["Nil"] |
(ns atom-geojson-viewer.helper)
(defn html-string->dom
[html]
(let [template (.createElement js/document "template")]
(set! (.-innerHTML template) html)
(.. template -content -firstChild)))
(defn export-module
[module]
(set! (.-exports js/module) module))
|
package com.reasec.certificatepinning.trustmanager
import com.reasec.certificatepinning.model.CertificatePinningSpec
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.catchThrowable
import org.junit.Test
import java.security.KeyStore
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager
class CertificatePinningTrustManagerTest {
@Test
fun checkClientTrusted() {
val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(null as KeyStore?)
val spec = CertificatePinningSpec.Builder().build()
val trustManager = CertificatePinningTrustManager(spec, trustManagerFactory.trustManagers)
val certificates = arrayOf<X509Certificate>()
val thrown = catchThrowable {
trustManager.checkClientTrusted(certificates, "")
}
assertThat(thrown).isInstanceOf(CertificateException::class.java)
assertThat(thrown).hasCauseExactlyInstanceOf(UnsupportedOperationException::class.java)
}
@Test
fun checkServerTrusted() {
}
@Test
fun pingCertificate() {
}
@Test
fun getAcceptedIssuers() {
val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(null as KeyStore?)
val spec = CertificatePinningSpec.Builder().build()
val trustManager = CertificatePinningTrustManager(spec, trustManagerFactory.trustManagers)
val acceptedIssuers = trustManager.acceptedIssuers
var total = 0
trustManagerFactory.trustManagers.forEach {
repeat((it as X509TrustManager).acceptedIssuers.count()) {
total++
}
}
assertThat(acceptedIssuers).hasSize(total)
}
} |
require 'spec_helper'
describe Spanx::Helper::Timing do
class TestClass
include Spanx::Helper::Timing
end
let(:tester) { TestClass.new }
describe '#period_marker' do
let(:time) { DateTime.parse('2001-02-02T21:03:26+00:00').to_time }
before { time.to_i.should == 981147806 }
it 'returns unix time floored to the nearest resolution block' do
Timecop.freeze time do
tester.period_marker(10).should == 981147800
tester.period_marker(300).should == 981147600
end
end
end
end
|
/// @copyright
/// Copyright (C) 2020 Assured Information Security, Inc.
///
/// @copyright
/// 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:
///
/// @copyright
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// @copyright
/// 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.
///
/// @file span.hpp
///
#ifndef BSL_SPAN_HPP
#define BSL_SPAN_HPP
#include "byte.hpp"
#include "char_type.hpp"
#include "contiguous_iterator.hpp"
#include "convert.hpp"
#include "debug.hpp"
#include "is_same.hpp"
#include "npos.hpp"
#include "reverse_iterator.hpp"
#include "safe_integral.hpp"
namespace bsl
{
/// @class bsl::span
///
/// <!-- description -->
/// @brief A bsl::span is a non-owning view of an array type. Unlike
/// a bsl::array, the bsl::span does not own the memory it accesses
/// and therefore cannot outlive whatever array you give it. The
/// bsl::span is also very similar to a gsl::span and a std::span
/// with some key differences.
/// - We do not provide the conversion constructors for array types as
/// they are not compliant with AUTOSAR. If you need an array, use
/// a bsl::array.
/// - We do not provide any of the accessor functions as defined by
/// the standard library. Instead we provide _if() versions which
/// return a pointer to the element being requested. If the element
/// does not exist, a nullptr is returned, providing a means to
/// check for logic errors without the need for exceptions or
/// failing fast which is not compliant with AUTOSAR.
/// - We provide the iter() function which is similar to begin() and
/// end(), but allowing you to get an iterator from any position in
/// the view.
/// - As noted in the documentation for the contiguous_iterator,
/// iterators are not allowed to go beyond their bounds which the
/// Standard Library does not ensure. It is still possible for an
/// iterator to be invalid as you cannot dereference end() (fixing
/// this would break compatiblity with existing APIs when AUTOSAR
/// compliance is disabled), but you can be rest assured that an
/// iterator's index is always within bounds or == end(). Note
/// that for invalid views, begin() and friends always return an
/// interator to end().
/// - We do not provide any of the as_byte helper functions as they
/// would all require a reinterpret_cast which is not allowed
/// by AUTOSAR.
/// - A bsl::span is always a dynamic_extent type. The reason the
/// dynamic_extent type exists in a std::span is to optimize away
/// the need to store the size of the array the span is viewing.
/// This is only useful for C-style arrays which are not supported
/// as they are not compliant with AUTOSAR. If you need a C-style
/// array, use a bsl::array, in which case you have no need for a
/// bsl::span. Instead, a bsl::span is useful when you have an
/// array in memory that is not in your control (for example, a
/// device's memory).
/// @include example_span_overview.hpp
///
/// <!-- template parameters -->
/// @tparam T the type of element being viewed.
///
template<typename T>
class span final // NOLINT
{
static_assert(!is_same<T, char_type>::value, "use bsl::string_view instead");
public:
/// @brief alias for: T
using value_type = T;
/// @brief alias for: safe_uintmax
using size_type = safe_uintmax;
/// @brief alias for: safe_uintmax
using difference_type = safe_uintmax;
/// @brief alias for: T &
using reference_type = T &;
/// @brief alias for: T &
using const_reference_type = T const &;
/// @brief alias for: T *
using pointer_type = T *;
/// @brief alias for: T const *
using const_pointer_type = T const *;
/// @brief alias for: contiguous_iterator<T>
using iterator_type = contiguous_iterator<T>;
/// @brief alias for: contiguous_iterator<T const>
using const_iterator_type = contiguous_iterator<T const>;
/// @brief alias for: reverse_iterator<iterator>
using reverse_iterator_type = reverse_iterator<iterator_type>;
/// @brief alias for: reverse_iterator<const_iterator>
using const_reverse_iterator_type = reverse_iterator<const_iterator_type>;
/// <!-- description -->
/// @brief Default constructor that creates a span with
/// data() == nullptr and size() == 0. All accessors
/// will return a nullptr if used. Note that like other view types
/// in the BSL, the bsl::span is a POD type. This
/// means that when declaring a global, default constructed
/// bsl::span, DO NOT include the {} for
/// initialization. Instead, remove the {} and the global
/// bsl::span will be included in the BSS section of
/// the executable, and initialized to 0 for you. All other
/// instantiations of a bsl::span (or any POD
/// type), should be initialized using {} to ensure the POD is
/// properly initialized. Using the above method for global
/// initialization ensures that global constructors are not
/// executed at runtime, which is required by AUTOSAR.
/// @include span/example_span_default_constructor.hpp
///
constexpr span() noexcept = default;
/// <!-- description -->
/// @brief Creates a span given a pointer to an array, and the
/// number of elements in the array. Note that the array must be
/// contiguous in memory and [ptr, ptr + count) must be a valid
/// range.
/// @include span/example_span_ptr_count_constructor.hpp
///
/// <!-- inputs/outputs -->
/// @param ptr a pointer to the array being spaned.
/// @param count the number of elements in the array being spaned.
///
constexpr span(pointer_type const ptr, size_type const &count) noexcept // --
: m_ptr{ptr}, m_count{count}
{
if ((nullptr == m_ptr) || m_count.is_zero()) {
bsl::alert() << "basic_string_view: invalid constructor args\n";
bsl::alert() << " - ptr: " << static_cast<void const *>(ptr) << bsl::endl;
bsl::alert() << " - count: " << m_count << bsl::endl;
*this = span{};
}
}
/// <!-- description -->
/// @brief Returns a pointer to the instance of T stored at index
/// "index". If the index is out of bounds, or the view is invalid,
/// this function returns a nullptr.
/// @include span/example_span_at_if.hpp
///
/// SUPPRESSION: PRQA 4024 - false positive
/// - We suppress this because A9-3-1 states that we should
/// not provide a non-const reference or pointer to private
/// member function, unless the class mimics a smart pointer or
/// a containter. This class mimics a container.
///
/// <!-- inputs/outputs -->
/// @param index the index of the instance to return
/// @return Returns a pointer to the instance of T stored at index
/// "index". If the index is out of bounds, or the view is invalid,
/// this function returns a nullptr.
///
[[nodiscard]] constexpr pointer_type
at_if(size_type const &index) noexcept
{
if ((!index) || (index >= m_count)) {
bsl::error() << "span: index out of range: " << index << '\n';
return nullptr;
}
return &m_ptr[index.get()]; // PRQA S 4024 // NOLINT
}
/// <!-- description -->
/// @brief Returns a pointer to the instance of T stored at index
/// "index". If the index is out of bounds, or the view is invalid,
/// this function returns a nullptr.
/// @include span/example_span_at_if.hpp
///
/// <!-- inputs/outputs -->
/// @param index the index of the instance to return
/// @return Returns a pointer to the instance of T stored at index
/// "index". If the index is out of bounds, or the view is invalid,
/// this function returns a nullptr.
///
[[nodiscard]] constexpr const_pointer_type
at_if(size_type const &index) const noexcept
{
if ((!index) || (index >= m_count)) {
bsl::error() << "span: index out of range: " << index << '\n';
return nullptr;
}
return &m_ptr[index.get()]; // NOLINT
}
/// <!-- description -->
/// @brief Returns a pointer to the instance of T stored at index
/// "0". If the index is out of bounds, or the view is invalid,
/// this function returns a nullptr.
/// @include span/example_span_front_if.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns a pointer to the instance of T stored at index
/// "0". If the index is out of bounds, or the view is invalid,
/// this function returns a nullptr.
///
[[nodiscard]] constexpr pointer_type
front_if() noexcept
{
return this->at_if(to_umax(0));
}
/// <!-- description -->
/// @brief Returns a pointer to the instance of T stored at index
/// "0". If the index is out of bounds, or the view is invalid,
/// this function returns a nullptr.
/// @include span/example_span_front_if.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns a pointer to the instance of T stored at index
/// "0". If the index is out of bounds, or the view is invalid,
/// this function returns a nullptr.
///
[[nodiscard]] constexpr const_pointer_type
front_if() const noexcept
{
return this->at_if(to_umax(0));
}
/// <!-- description -->
/// @brief Returns a pointer to the instance of T stored at index
/// "size() - 1". If the index is out of bounds, or the view is
/// invalid, this function returns a nullptr.
/// @include span/example_span_back_if.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns a pointer to the instance of T stored at index
/// "size() - 1". If the index is out of bounds, or the view is
/// invalid, this function returns a nullptr.
///
[[nodiscard]] constexpr pointer_type
back_if() noexcept
{
return this->at_if(m_count.is_pos() ? (m_count - to_umax(1)) : to_umax(0));
}
/// <!-- description -->
/// @brief Returns a pointer to the instance of T stored at index
/// "size() - 1". If the index is out of bounds, or the view is
/// invalid, this function returns a nullptr.
/// @include span/example_span_back_if.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns a pointer to the instance of T stored at index
/// "size() - 1". If the index is out of bounds, or the view is
/// invalid, this function returns a nullptr.
///
[[nodiscard]] constexpr const_pointer_type
back_if() const noexcept
{
return this->at_if(m_count.is_pos() ? (m_count - to_umax(1)) : to_umax(0));
}
/// <!-- description -->
/// @brief Returns a pointer to the array being viewed. If this is
/// a default constructed view, or the view was constructed in
/// error, this will return a nullptr.
/// @include span/example_span_data.hpp
///
/// SUPPRESSION: PRQA 4625 - false positive
/// - We suppress this because A9-3-1 states that we should
/// not provide a non-const reference or pointer to private
/// member function, unless the class mimics a smart pointer or
/// a containter. This class mimics a container.
///
/// <!-- inputs/outputs -->
/// @return Returns a pointer to the array being viewed. If this is
/// a default constructed view, or the view was constructed in
/// error, this will return a nullptr.
///
[[nodiscard]] constexpr pointer_type
data() noexcept
{
return m_ptr; // PRQA S 4625
}
/// <!-- description -->
/// @brief Returns a pointer to the array being viewed. If this is
/// a default constructed view, or the view was constructed in
/// error, this will return a nullptr.
/// @include span/example_span_data.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns a pointer to the array being viewed. If this is
/// a default constructed view, or the view was constructed in
/// error, this will return a nullptr.
///
[[nodiscard]] constexpr const_pointer_type
data() const noexcept
{
return m_ptr;
}
/// <!-- description -->
/// @brief Returns an iterator to the first element of the view.
/// @include span/example_span_begin.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns an iterator to the first element of the view.
///
[[nodiscard]] constexpr iterator_type
begin() noexcept
{
return iterator_type{m_ptr, m_count, to_umax(0)};
}
/// <!-- description -->
/// @brief Returns an iterator to the first element of the view.
/// @include span/example_span_begin.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns an iterator to the first element of the view.
///
[[nodiscard]] constexpr const_iterator_type
begin() const noexcept
{
return const_iterator_type{m_ptr, m_count, to_umax(0)};
}
/// <!-- description -->
/// @brief Returns an iterator to the first element of the view.
/// @include span/example_span_begin.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns an iterator to the first element of the view.
///
[[nodiscard]] constexpr const_iterator_type
cbegin() const noexcept
{
return const_iterator_type{m_ptr, m_count, to_umax(0)};
}
/// <!-- description -->
/// @brief Returns an iterator to the element "i" in the view.
/// @include span/example_span_iter.hpp
///
/// <!-- inputs/outputs -->
/// @param i the element in the array to return an iterator for.
/// @return Returns an iterator to the element "i" in the view.
///
[[nodiscard]] constexpr iterator_type
iter(size_type const &i) noexcept
{
return iterator_type{m_ptr, m_count, i};
}
/// <!-- description -->
/// @brief Returns an iterator to the element "i" in the view.
/// @include span/example_span_iter.hpp
///
/// <!-- inputs/outputs -->
/// @param i the element in the array to return an iterator for.
/// @return Returns an iterator to the element "i" in the view.
///
[[nodiscard]] constexpr const_iterator_type
iter(size_type const &i) const noexcept
{
return const_iterator_type{m_ptr, m_count, i};
}
/// <!-- description -->
/// @brief Returns an iterator to the element "i" in the view.
/// @include span/example_span_iter.hpp
///
/// <!-- inputs/outputs -->
/// @param i the element in the array to return an iterator for.
/// @return Returns an iterator to the element "i" in the view.
///
[[nodiscard]] constexpr const_iterator_type
citer(size_type const &i) const noexcept
{
return const_iterator_type{m_ptr, m_count, i};
}
/// <!-- description -->
/// @brief Returns an iterator to one past the last element of the
/// view. If you attempt to access this iterator, a nullptr will
/// always be returned.
/// @include span/example_span_end.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns an iterator to one past the last element of the
/// view. If you attempt to access this iterator, a nullptr will
/// always be returned.
///
[[nodiscard]] constexpr iterator_type
end() noexcept
{
return iterator_type{m_ptr, m_count, m_count};
}
/// <!-- description -->
/// @brief Returns an iterator to one past the last element of the
/// view. If you attempt to access this iterator, a nullptr will
/// always be returned.
/// @include span/example_span_end.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns an iterator to one past the last element of the
/// view. If you attempt to access this iterator, a nullptr will
/// always be returned.
///
[[nodiscard]] constexpr const_iterator_type
end() const noexcept
{
return const_iterator_type{m_ptr, m_count, m_count};
}
/// <!-- description -->
/// @brief Returns an iterator to one past the last element of the
/// view. If you attempt to access this iterator, a nullptr will
/// always be returned.
/// @include span/example_span_end.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns an iterator to one past the last element of the
/// view. If you attempt to access this iterator, a nullptr will
/// always be returned.
///
[[nodiscard]] constexpr const_iterator_type
cend() const noexcept
{
return const_iterator_type{m_ptr, m_count, m_count};
}
/// <!-- description -->
/// @brief Returns a reverse iterator to one past the last element
/// of the view. When accessing the iterator, the iterator will
/// always return the element T[internal index - 1], providing
/// access to the range [size() - 1, 0) while internally storing the
/// range [size(), 1) with element 0 representing the end(). For more
/// information, see the bsl::reverse_iterator documentation.
/// @include span/example_span_rbegin.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns a reverse iterator to the last element of the
/// view.
///
[[nodiscard]] constexpr reverse_iterator_type
rbegin() noexcept
{
return reverse_iterator_type{this->end()};
}
/// <!-- description -->
/// @brief Returns a reverse iterator to one past the last element
/// of the view. When accessing the iterator, the iterator will
/// always return the element T[internal index - 1], providing
/// access to the range [size() - 1, 0) while internally storing the
/// range [size(), 1) with element 0 representing the end(). For more
/// information, see the bsl::reverse_iterator documentation.
/// @include span/example_span_rbegin.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns a reverse iterator to the last element of the
/// view.
///
[[nodiscard]] constexpr const_reverse_iterator_type
rbegin() const noexcept
{
return const_reverse_iterator_type{this->end()};
}
/// <!-- description -->
/// @brief Returns a reverse iterator to one past the last element
/// of the view. When accessing the iterator, the iterator will
/// always return the element T[internal index - 1], providing
/// access to the range [size() - 1, 0) while internally storing the
/// range [size(), 1) with element 0 representing the end(). For more
/// information, see the bsl::reverse_iterator documentation.
/// @include span/example_span_rbegin.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns a reverse iterator to the last element of the
/// view.
///
[[nodiscard]] constexpr const_reverse_iterator_type
crbegin() const noexcept
{
return const_reverse_iterator_type{this->cend()};
}
/// <!-- description -->
/// @brief Returns a reverse iterator element "i" in the
/// view. When accessing the iterator, the iterator will
/// always return the element T[internal index - 1], providing
/// access to the range [size() - 1, 0) while internally storing the
/// range [size(), 1) with element 0 representing the end(). For more
/// information, see the bsl::reverse_iterator documentation.
/// @include span/example_span_riter.hpp
///
/// <!-- inputs/outputs -->
/// @param i the element in the array to return an iterator for.
/// @return Returns a reverse iterator element "i" in the
/// view.
///
[[nodiscard]] constexpr reverse_iterator_type
riter(size_type const &i) noexcept
{
if ((!!i) && (i >= m_count)) {
return reverse_iterator_type{this->iter(m_count)};
}
return reverse_iterator_type{this->iter(i + to_umax(1))};
}
/// <!-- description -->
/// @brief Returns a reverse iterator element "i" in the
/// view. When accessing the iterator, the iterator will
/// always return the element T[internal index - 1], providing
/// access to the range [size() - 1, 0) while internally storing the
/// range [size(), 1) with element 0 representing the end(). For more
/// information, see the bsl::reverse_iterator documentation.
/// @include span/example_span_riter.hpp
///
/// <!-- inputs/outputs -->
/// @param i the element in the array to return an iterator for.
/// @return Returns a reverse iterator element "i" in the
/// view.
///
[[nodiscard]] constexpr const_reverse_iterator_type
riter(size_type const &i) const noexcept
{
if ((!!i) && (i >= m_count)) {
return const_reverse_iterator_type{this->iter(m_count)};
}
return const_reverse_iterator_type{this->iter(i + to_umax(1))};
}
/// <!-- description -->
/// @brief Returns a reverse iterator element "i" in the
/// view. When accessing the iterator, the iterator will
/// always return the element T[internal index - 1], providing
/// access to the range [size() - 1, 0) while internally storing the
/// range [size(), 1) with element 0 representing the end(). For more
/// information, see the bsl::reverse_iterator documentation.
/// @include span/example_span_riter.hpp
///
/// <!-- inputs/outputs -->
/// @param i the element in the array to return an iterator for.
/// @return Returns a reverse iterator element "i" in the
/// view.
///
[[nodiscard]] constexpr const_reverse_iterator_type
criter(size_type const &i) const noexcept
{
if ((!!i) && (i >= m_count)) {
return const_reverse_iterator_type{this->citer(m_count)};
}
return const_reverse_iterator_type{this->citer(i + to_umax(1))};
}
/// <!-- description -->
/// @brief Returns a reverse iterator first element of the
/// view. When accessing the iterator, the iterator will
/// always return the element T[internal index - 1], providing
/// access to the range [size() - 1, 0) while internally storing the
/// range [size(), 1) with element 0 representing the end(). For more
/// information, see the bsl::reverse_iterator documentation.
/// @include span/example_span_rend.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns a reverse iterator first element of the
/// view.
///
[[nodiscard]] constexpr reverse_iterator_type
rend() noexcept
{
return reverse_iterator_type{this->begin()};
}
/// <!-- description -->
/// @brief Returns a reverse iterator first element of the
/// view. When accessing the iterator, the iterator will
/// always return the element T[internal index - 1], providing
/// access to the range [size() - 1, 0) while internally storing the
/// range [size(), 1) with element 0 representing the end(). For more
/// information, see the bsl::reverse_iterator documentation.
/// @include span/example_span_rend.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns a reverse iterator first element of the
/// view.
///
[[nodiscard]] constexpr const_reverse_iterator_type
rend() const noexcept
{
return const_reverse_iterator_type{this->begin()};
}
/// <!-- description -->
/// @brief Returns a reverse iterator first element of the
/// view. When accessing the iterator, the iterator will
/// always return the element T[internal index - 1], providing
/// access to the range [size() - 1, 0) while internally storing the
/// range [size(), 1) with element 0 representing the end(). For more
/// information, see the bsl::reverse_iterator documentation.
/// @include span/example_span_rend.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns a reverse iterator first element of the
/// view.
///
[[nodiscard]] constexpr const_reverse_iterator_type
crend() const noexcept
{
return const_reverse_iterator_type{this->cbegin()};
}
/// <!-- description -->
/// @brief Returns size() == 0
/// @include span/example_span_empty.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns size() == 0
///
[[nodiscard]] constexpr bool
empty() const noexcept
{
return m_count.is_zero();
}
/// <!-- description -->
/// @brief Returns !empty()
/// @include span/example_span_operator_bool.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns !empty()
///
[[nodiscard]] constexpr explicit operator bool() const noexcept
{
return !this->empty();
}
/// <!-- description -->
/// @brief Returns the number of elements in the array being
/// viewed. If this is a default constructed view, or the view
/// was constructed in error, this will return 0.
/// @include span/example_span_size.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns the number of elements in the array being
/// viewed. If this is a default constructed view, or the view
/// was constructed in error, this will return 0.
///
[[nodiscard]] constexpr size_type const &
size() const noexcept
{
return m_count;
}
/// <!-- description -->
/// @brief Returns the max number of elements the BSL supports.
/// @include span/example_span_max_size.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns the max number of elements the BSL supports.
///
[[nodiscard]] static constexpr size_type
max_size() noexcept
{
return size_type::max() / to_umax(sizeof(T));
}
/// <!-- description -->
/// @brief Returns size() * sizeof(T)
/// @include span/example_span_size_bytes.hpp
///
/// <!-- inputs/outputs -->
/// @return Returns size() * sizeof(T)
///
[[nodiscard]] constexpr size_type
size_bytes() const noexcept
{
return m_count * to_umax(sizeof(T));
}
/// <!-- description -->
/// @brief Returns subspan(0, count). If count is 0, an invalid
/// span is returned.
/// @include span/example_span_first.hpp
///
/// <!-- inputs/outputs -->
/// @param count the number of elements of the new subspan
/// @return Returns subspan(0, count). If count is 0, an invalid
/// span is returned.
///
[[nodiscard]] constexpr span<T>
first(size_type const &count = npos) const noexcept
{
return this->subspan(to_umax(0), count);
}
/// <!-- description -->
/// @brief Returns subspan(this->size() - count, count). If count
/// is greater than the size of the current span, a copy of the
/// current span is returned. If the count is 0, an invalid span
/// is returned.
/// @include span/example_span_last.hpp
///
/// <!-- inputs/outputs -->
/// @param count the number of elements of the new subspan
/// @return Returns subspan(this->size() - count, count). If count
/// is greater than the size of the current span, a copy of the
/// current span is returned. If the count is 0, an invalid span
/// is returned.
///
[[nodiscard]] constexpr span<T>
last(size_type const &count = npos) const noexcept
{
if (count > this->size()) {
return this->subspan(to_umax(0), count);
}
return this->subspan(this->size() - count, count);
}
/// <!-- description -->
/// @brief Returns span{at_if(pos), count.min(size() - pos)}. If
/// the provided "pos" is greater than or equal to the size of
/// the current span, an invalid span is returned.
/// @include span/example_span_subspan.hpp
///
/// <!-- inputs/outputs -->
/// @param pos the starting position of the new span
/// @param count the number of elements of the new subspan
/// @return Returns span{at_if(pos), count.min(size() - pos)}. If
/// the provided "pos" is greater than or equal to the size of
/// the current span, an invalid span is returned.
///
[[nodiscard]] constexpr span<T>
subspan(size_type const &pos, size_type const &count = npos) const noexcept
{
if ((!pos) || (!count) || (pos >= m_count)) {
return {};
}
return span<T>{&m_ptr[pos.get()], count.min(m_count - pos)}; // NOLINT
}
private:
/// @brief stores a pointer to the array being viewed
pointer_type m_ptr;
/// @brief stores the number of elements in the array being viewed
size_type m_count;
};
/// <!-- description -->
/// @brief Returns a span<byte const> given a pointer to an array
/// type and the total number of bytes
/// @include span/example_span_as_bytes.hpp
/// @related bsl::span
///
/// <!-- inputs/outputs -->
/// @param ptr a pointer to the array to create the span for
/// @param bytes the total number of bytes in the array
/// @return Returns a span<byte const> given a pointer to an array
/// type and the total number of bytes
///
[[nodiscard]] constexpr span<byte const>
as_bytes(void const *const ptr, safe_uintmax const &bytes) noexcept
{
return {static_cast<byte const *>(ptr), bytes};
}
/// <!-- description -->
/// @brief Returns a span<byte const> given an existing span<T>
/// @include span/example_span_as_bytes.hpp
/// @related bsl::span
///
/// <!-- inputs/outputs -->
/// @param spn the span<T> to convert into a span<byte const>
/// @return Returns a span<byte const> given an existing span<T>
///
template<typename T>
[[nodiscard]] constexpr span<byte const>
as_bytes(span<T> const spn) noexcept
{
return as_bytes(spn.data(), spn.size_bytes());
}
/// <!-- description -->
/// @brief Returns a span<byte> given a pointer to an array
/// type and the total number of bytes
/// @include span/example_span_as_writable_bytes.hpp
/// @related bsl::span
///
/// <!-- inputs/outputs -->
/// @param ptr a pointer to the array to create the span for
/// @param bytes the total number of bytes in the array
/// @return Returns a span<byte> given a pointer to an array
/// type and the total number of bytes
///
[[nodiscard]] constexpr span<byte>
as_writable_bytes(void *const ptr, safe_uintmax const &bytes) noexcept
{
return {static_cast<byte *>(ptr), bytes};
}
/// <!-- description -->
/// @brief Returns a span<byte> given an existing span<T>
/// @include span/example_span_as_writable_bytes.hpp
/// @related bsl::span
///
/// <!-- inputs/outputs -->
/// @param spn the span<T> to convert into a span<byte>
/// @return Returns a span<byte> given an existing span<T>
///
template<typename T>
[[nodiscard]] constexpr span<byte>
as_writable_bytes(span<T> spn) noexcept
{
return as_writable_bytes(spn.data(), spn.size_bytes());
}
/// <!-- description -->
/// @brief Returns true if two spans have the same size and contain
/// the same contents. Returns false otherwise.
/// @include span/example_span_equals.hpp
/// @related bsl::span
///
/// <!-- inputs/outputs -->
/// @tparam T the type of elements in the span
/// @param lhs the left hand side of the operation
/// @param rhs the right hand side of the operation
/// @return Returns true if two spans have the same size and contain
/// the same contents. Returns false otherwise.
///
template<typename T>
constexpr bool
operator==(span<T> const &lhs, span<T> const &rhs) noexcept
{
if (lhs.size() != rhs.size()) {
return false;
}
for (safe_uintmax i{}; i < lhs.size(); ++i) {
if (*lhs.at_if(i) != *rhs.at_if(i)) {
return false;
}
}
return true;
}
/// <!-- description -->
/// @brief Returns false if two spans have the same size and contain
/// the same contents. Returns true otherwise.
/// @include span/example_span_not_equals.hpp
/// @related bsl::span
///
/// <!-- inputs/outputs -->
/// @tparam T the type of elements in the span
/// @param lhs the left hand side of the operation
/// @param rhs the right hand side of the operation
/// @return Returns true if two spans have the same size and contain
/// the same contents. Returns false otherwise.
///
template<typename T>
constexpr bool
operator!=(span<T> const &lhs, span<T> const &rhs) noexcept
{
return !(lhs == rhs);
}
/// <!-- description -->
/// @brief Outputs the provided bsl::span to the provided
/// output type.
/// @related bsl::span
/// @include span/example_span_ostream.hpp
///
/// <!-- inputs/outputs -->
/// @tparam T1 the type of outputter provided
/// @tparam T2 the type of element being encapsulated.
/// @param o the instance of the outputter used to output the value.
/// @param val the span to output
/// @return return o
///
template<typename T1, typename T2>
[[maybe_unused]] constexpr out<T1>
operator<<(out<T1> const o, bsl::span<T2> const &val) noexcept
{
if constexpr (!o) {
return o;
}
if (val.empty()) {
return o << "[]";
}
for (safe_uintmax i{}; i < val.size(); ++i) {
o << (i.is_zero() ? "[" : ", ") << *val.at_if(i);
}
return o << ']';
}
}
#endif
|
! -*- Mode: Fortran; -*-
!
! (C) 2014 by Argonne National Laboratory.
! See COPYRIGHT in top-level directory.
!
subroutine PMPIR_Error_string_f08(errorcode, string, resultlen, ierror)
use, intrinsic :: iso_c_binding, only : c_int, c_char
use :: mpi_f08, only : MPI_MAX_ERROR_STRING
use :: mpi_f08, only : MPI_MAX_ERROR_STRING
use :: mpi_c_interface, only : MPIR_Error_string_c
use :: mpi_c_interface, only : MPIR_Fortran_string_c2f
implicit none
integer, intent(in) :: errorcode
character(len=MPI_MAX_ERROR_STRING), intent(out) :: string
integer, intent(out) :: resultlen
integer, optional, intent(out) :: ierror
integer(c_int) :: errorcode_c
character(kind=c_char) :: string_c(MPI_MAX_ERROR_STRING+1)
integer(c_int) :: resultlen_c
integer(c_int) :: ierror_c
if (c_int == kind(0)) then
ierror_c = MPIR_Error_string_c(errorcode, string_c, resultlen)
else
errorcode_c = errorcode
ierror_c = MPIR_Error_string_c(errorcode_c, string_c, resultlen_c)
resultlen = resultlen_c
end if
call MPIR_Fortran_string_c2f(string_c, string)
if (present(ierror)) ierror = ierror_c
end subroutine PMPIR_Error_string_f08
|
bits 64
mov rdx,[rax]
mov eax,[byte rsp+0x01]
mov eax,[byte rsp-0x01]
mov eax,[byte rsp+0xFF]
mov eax,[byte rsp-0xFF]
mov eax,[rsp+0x08]
mov eax,[rsp-0x01]
mov eax,[rsp+0xFF]
mov eax,[rsp-0xFF]
mov rax,[rsp+56]
mov [rsi],dl
mov byte [rsi],'-'
mov [rsi],al
mov byte [rsi],' '
|
using System.Collections.Generic;
using Entitas;
using UnityEngine;
public sealed class DestroySystem : ReactiveSystem<GameEntity>
{
public GameContext _gameContext;
private IGroup<GameEventEntity> _groupGameEvent;
public DestroySystem(Contexts contexts) : base(contexts.game){
_gameContext = contexts.game;
_groupGameEvent = contexts.gameEvent.GetGroup(Matcher<GameEventEntity>.AllOf(GameEventMatcher.StateEvent));
}
protected override bool Filter(GameEntity entity) {
return entity.isDestroyable;
}
protected override ICollector<GameEntity> GetTrigger(IContext<GameEntity> context) {
return context.CreateCollector(GameMatcher.Destroyable);
}
protected override void Execute(List<GameEntity> entities) {
foreach (GameEntity e in entities) {
if (e.hasView) {
e.view.gameObject.Unlink();
}
e.Destroy();
}
GameEventEntity gameEventEntity = null;
GameEventEntity[] gameEventEntities = _groupGameEvent.GetEntities();
if (gameEventEntities.Length != 0) {
gameEventEntity = gameEventEntities[0];
if (gameEventEntity.stateEvent.state == "Reload") {
gameEventEntity.ReplaceStateEvent("Reload Ready");
}
}
}
} |
using System.Linq;
using Model = Discord.API.AuditLog;
using EntryModel = Discord.API.AuditLogEntry;
namespace Discord.Rest
{
/// <summary>
/// Contains a piece of audit log data related to a webhook deletion.
/// </summary>
public class WebhookDeleteAuditLogData : IAuditLogData
{
private WebhookDeleteAuditLogData(ulong id, ulong channel, WebhookType type, string name, string avatar)
{
WebhookId = id;
ChannelId = channel;
Name = name;
Type = type;
Avatar = avatar;
}
internal static WebhookDeleteAuditLogData Create(BaseDiscordClient discord, Model log, EntryModel entry)
{
API.AuditLogChange[] changes = entry.Changes;
API.AuditLogChange channelIdModel = changes.FirstOrDefault(x => x.ChangedProperty == "channel_id");
API.AuditLogChange typeModel = changes.FirstOrDefault(x => x.ChangedProperty == "type");
API.AuditLogChange nameModel = changes.FirstOrDefault(x => x.ChangedProperty == "name");
API.AuditLogChange avatarHashModel = changes.FirstOrDefault(x => x.ChangedProperty == "avatar_hash");
ulong channelId = channelIdModel.OldValue.ToObject<ulong>(discord.ApiClient.Serializer);
WebhookType type = typeModel.OldValue.ToObject<WebhookType>(discord.ApiClient.Serializer);
string name = nameModel.OldValue.ToObject<string>(discord.ApiClient.Serializer);
string avatarHash = avatarHashModel?.OldValue?.ToObject<string>(discord.ApiClient.Serializer);
return new WebhookDeleteAuditLogData(entry.TargetId.Value, channelId, type, name, avatarHash);
}
/// <summary>
/// Gets the ID of the webhook that was deleted.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the snowflake identifier of the webhook that was deleted.
/// </returns>
public ulong WebhookId { get; }
/// <summary>
/// Gets the ID of the channel that the webhook could send to.
/// </summary>
/// <returns>
/// A <see cref="ulong"/> representing the snowflake identifier of the channel that the webhook could send
/// to.
/// </returns>
public ulong ChannelId { get; }
/// <summary>
/// Gets the type of the webhook that was deleted.
/// </summary>
/// <returns>
/// The type of webhook that was deleted.
/// </returns>
public WebhookType Type { get; }
/// <summary>
/// Gets the name of the webhook that was deleted.
/// </summary>
/// <returns>
/// A string containing the name of the webhook that was deleted.
/// </returns>
public string Name { get; }
/// <summary>
/// Gets the hash value of the webhook's avatar.
/// </summary>
/// <returns>
/// A string containing the hash of the webhook's avatar.
/// </returns>
public string Avatar { get; }
}
}
|
package io.ktor.metrics
import com.codahale.metrics.*
import com.codahale.metrics.jvm.*
import io.ktor.application.*
import io.ktor.pipeline.*
import io.ktor.routing.*
import io.ktor.util.*
import java.util.concurrent.*
class Metrics(val registry: MetricRegistry) {
val baseName: String = MetricRegistry.name("ktor.calls")
private val duration = registry.timer(MetricRegistry.name(baseName, "duration"))
private val active = registry.counter(MetricRegistry.name(baseName, "active"))
private val exceptions = registry.meter(MetricRegistry.name(baseName, "exceptions"))
private val httpStatus = ConcurrentHashMap<Int, Meter>()
class Configuration {
val registry = MetricRegistry()
}
companion object Feature : ApplicationFeature<Application, Configuration, Metrics> {
override val key = AttributeKey<Metrics>("metrics")
private class RoutingMetrics(val name: String, val context: Timer.Context)
private val routingMetricsKey = AttributeKey<RoutingMetrics>("metrics")
override fun install(pipeline: Application, configure: Configuration.() -> Unit): Metrics {
val configuration = Configuration().apply(configure)
val feature = Metrics(configuration.registry)
configuration.registry.register("jvm.memory", MemoryUsageGaugeSet())
configuration.registry.register("jvm.garbage", GarbageCollectorMetricSet())
configuration.registry.register("jvm.threads", ThreadStatesGaugeSet())
configuration.registry.register("jvm.files", FileDescriptorRatioGauge())
configuration.registry.register("jvm.attributes", JvmAttributeGaugeSet())
val phase = PipelinePhase("Metrics")
pipeline.insertPhaseBefore(ApplicationCallPipeline.Infrastructure, phase)
pipeline.intercept(phase) {
feature.before(call)
try {
proceed()
} catch (e: Exception) {
feature.exception(call, e)
throw e
} finally {
feature.after(call)
}
}
pipeline.environment.monitor.subscribe(Routing.RoutingCallStarted) { call ->
val name = call.route.toString()
val meter = feature.registry.meter(MetricRegistry.name(name, "meter"))
val timer = feature.registry.timer(MetricRegistry.name(name, "timer"))
meter.mark()
val context = timer.time()
call.attributes.put(routingMetricsKey, RoutingMetrics(name, context))
}
pipeline.environment.monitor.subscribe(Routing.RoutingCallFinished) { call ->
val routingMetrics = call.attributes.take(routingMetricsKey)
val status = call.response.status()?.value ?: 0
val statusMeter = feature.registry.meter(MetricRegistry.name(routingMetrics.name, status.toString()))
statusMeter.mark()
routingMetrics.context.stop()
}
return feature
}
}
private data class CallMeasure(val timer: Timer.Context)
private val measureKey = AttributeKey<CallMeasure>("metrics")
private fun before(call: ApplicationCall) {
active.inc()
call.attributes.put(measureKey, CallMeasure(duration.time()))
}
private fun after(call: ApplicationCall) {
active.dec()
val meter = httpStatus.computeIfAbsent(call.response.status()?.value ?: 0) {
registry.meter(MetricRegistry.name(baseName, "status", it.toString()))
}
meter.mark()
call.attributes.getOrNull(measureKey)?.apply {
timer.stop()
}
}
@Suppress("UNUSED_PARAMETER")
private fun exception(call: ApplicationCall, e: Throwable) {
exceptions.mark()
}
} |
<!--|This file generated by command(leetcode description); DO NOT EDIT. |-->
<!--+----------------------------------------------------------------------+-->
<!--|@author awesee <[email protected]> |-->
<!--|@link https://github.com/awesee |-->
<!--|@home https://github.com/awesee/leetcode |-->
<!--+----------------------------------------------------------------------+-->
[< Previous](../stone-game-iii "Stone Game III")
ใใใใใใใใใใใใใใใใ
[Next >](../string-matching-in-an-array "String Matching in an Array")
## [1407. Top Travellers (Easy)](https://leetcode.com/problems/top-travellers "ๆๅ้ ๅ็ๆ
่ก่
")
<p>Table: <code>Users</code></p>
<pre>
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| name | varchar |
+---------------+---------+
id is the primary key for this table.
name is the name of the user.
</pre>
<p>Table: <code>Rides</code></p>
<pre>
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| user_id | int |
| distance | int |
+---------------+---------+
id is the primary key for this table.
city_id is the id of the city who bought the product "product_name".
</pre>
Write an SQL query to report the distance travelled by each user.
Return the result table ordered by travelled_distance in descending order, if two or more users travelled the same distance, order them by their name in ascending order.
The query result format is in the following example.
<pre>
Users table:
+------+-----------+
| id | name |
+------+-----------+
| 1 | Alice |
| 2 | Bob |
| 3 | Alex |
| 4 | Donald |
| 7 | Lee |
| 13 | Jonathan |
| 19 | Elvis |
+------+-----------+
Rides table:
+------+----------+----------+
| id | user_id | distance |
+------+----------+----------+
| 1 | 1 | 120 |
| 2 | 2 | 317 |
| 3 | 3 | 222 |
| 4 | 7 | 100 |
| 5 | 13 | 312 |
| 6 | 19 | 50 |
| 7 | 7 | 120 |
| 8 | 19 | 400 |
| 9 | 7 | 230 |
+------+----------+----------+
Result table:
+----------+--------------------+
| name | travelled_distance |
+----------+--------------------+
| Elvis | 450 |
| Lee | 450 |
| Bob | 317 |
| Jonathan | 312 |
| Alex | 222 |
| Alice | 120 |
| Donald | 0 |
+----------+--------------------+
Elvis and Lee travelled 450 miles, Elvis is the top traveller as his name is alphabetically smaller than Lee.
Bob, Jonathan, Alex and Alice have only one ride and we just order them by the total distances of the ride.
Donald didn't have any rides, the distance travelled by him is 0.
</pre>
### Related Topics
[[Database](../../tag/database/README.md)]
|
class CounterCacheOnPostReshares < ActiveRecord::Migration
class Post < ActiveRecord::Base; end
def self.up
add_column :posts, :reshares_count, :integer, :default => 0
if postgres?
execute %{
UPDATE posts
SET reshares_count = (
SELECT COUNT(*)
FROM posts p2
WHERE
p2.type = 'Reshare'
AND p2.root_guid = posts.guid
)
}
else # mysql
execute "CREATE TEMPORARY TABLE posts_reshared SELECT * FROM posts WHERE type = 'Reshare'"
execute %{
UPDATE posts p1
SET reshares_count = (
SELECT COUNT(*)
FROM posts_reshared p2
WHERE p2.root_guid = p1.guid
)
}
end
end
def self.down
remove_column :posts, :reshares_count
end
end
|
import 'package:flutter/material.dart';
//import 'package:qrcode_reader/QRCode_Reader.dart';
import 'package:qrcode_reader/qrcode_reader.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
class HomeTab extends StatefulWidget {
@override
_HomeTabState createState() => _HomeTabState();
}
class _HomeTabState extends State<HomeTab> {
Future<String> _barcodeString;
Future<String> _api() async {
setState(() {
_barcodeString = new QRCodeReader()
.setAutoFocusIntervalInMs(200)
.setForceAutoFocus(true)
.setTorchEnabled(true)
.setHandlePermissions(true)
.setExecuteAfterPermissionGranted(true)
.scan();
});
}
Future<String> _api2(String url) async {
http.Response response = await http.get(url);
var jsonResponse = json.decode(response.body);
return jsonResponse["data"];
}
Future<String> _empty() async {
return 'Vocรช ainda nรฃo tem viagens!';
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder<String>(
future: _barcodeString,
builder: (BuildContext context, AsyncSnapshot<String> snap) {
return FutureBuilder<String>(
future: snap.data != null ? _api2(snap.data) : _empty(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot){
return new Text(snapshot.data != null ? snapshot.data : '');
},
);
})),
floatingActionButton: new FloatingActionButton(
onPressed: () {
_api();
},
tooltip: 'Reader the QRCode',
child: new Icon(Icons.attach_money),
),
);
}
}
|
import React from 'react';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableRow from '@material-ui/core/TableRow';
function TableBodyEmpty() {
return (
<TableBody>
<TableRow >
<TableCell component="th" scope="row" colSpan={12} align='center'>
Nenhum dado a ser exibido
</TableCell>
</TableRow>
</TableBody>
);
}
export default TableBodyEmpty; |
import React from 'react'
import PropTypes from 'prop-types'
import { NotFoundPageTemplate } from '../../templates/404-page'
const NotFoundPagePreview = ({ entry, getAsset }) => (
<NotFoundPageTemplate
title={entry.getIn(['data', 'title'])}
subtitle={entry.getIn(['data', 'subtitle'])}
photo={getAsset(entry.getIn(['data', 'photo']))}
/>
)
NotFoundPagePreview.propTypes = {
entry: PropTypes.shape({
getIn: PropTypes.func,
}),
getAsset: PropTypes.func,
}
export default NotFoundPagePreview
|
package de.htwg.se.SE_Chess_HTWG.model.gridComponent
import de.htwg.se.SE_Chess_HTWG.model.gridComponent.Turn.Turn
import de.htwg.se.SE_Chess_HTWG.model.pieceComponent.PieceColor
import play.api.libs.json.Json
case class TurnStatus(turn: Turn) {
def this() = this(Turn.IDLE)
def pieceColorMatchesTurnColor(square: Square): Boolean = Turn.pieceColorMatchesTurnColor(this.turn, square)
def nextTurn(): TurnStatus = TurnStatus(Turn.nextTurn(turn))
}
object TurnStatus {
def toOutputString(turnStatus: TurnStatus): String = {
turnStatus.turn match {
case Turn.P1 => "p1"
case Turn.P1PROMO => "p2"
case Turn.P2 => "p1prom"
case Turn.P2PROMO => "p2prom"
case _ => "idle"
}
}
def fromInputString(turn: String): TurnStatus = {
turn match {
case "p1" => TurnStatus(Turn.P1)
case "p2" => TurnStatus(Turn.P2)
case "p1prom" => TurnStatus(Turn.P1PROMO)
case "p2prom" => TurnStatus(Turn.P2PROMO)
case "idle" => TurnStatus(Turn.IDLE)
}
}
}
object Turn extends Enumeration {
type Turn = Value
val IDLE, P1, P2, P1PROMO, P2PROMO = Value
def pieceColorMatchesTurnColor(turnStatus: Turn, square: Square): Boolean = {
turnStatus match {
case P1 => square.isSet && square.value.get.color == PieceColor.WHITE
case P2 => square.isSet && square.value.get.color == PieceColor.BLACK
case _ => false
}
}
def nextTurn(turnStatus: Turn): Turn = {
turnStatus match {
case P1 => P2
case P1PROMO => P2
case P2 => P1
case P2PROMO => P1
case IDLE => P1
case _ => IDLE
}
}
}
|
// Package stockstore defines a datastore for storing stock(-chart) data.
package stockstore
import (
"errors"
"stock-service/config"
)
// StockStore saves the stock and chart data fir each route,
type StockStore struct {
config.StockStore
gainers, losers, mostActive []config.StockInfo
gainersChart, losersChart, mostActiveChart map[string][]config.StockChartNode
}
// New returns a newinstace of the StockStore with the cao representing the
// maximum amount of stocks that can be saved for each route.
func New(cap int) (*StockStore, error) {
if cap < 1 {
return nil, errors.New("The capacity cannot be smaller than 1")
}
ss := new(StockStore)
ss.gainers = make([]config.StockInfo, 0, cap)
ss.losers = make([]config.StockInfo, 0, cap)
ss.mostActive = make([]config.StockInfo, 0, cap)
ss.gainersChart = make(map[string][]config.StockChartNode, cap)
ss.losersChart = make(map[string][]config.StockChartNode, cap)
ss.mostActiveChart = make(map[string][]config.StockChartNode, cap)
return ss, nil
}
// SetOpt replaces the data for the route specified in opt to values in shs.
func (ss *StockStore) SetOpt(opt config.ShareOpt, shs []config.StockInfo) {
switch opt {
case config.Gainers:
ss.gainers = shs
break
case config.Losers:
ss.losers = shs
break
case config.MostActive:
ss.mostActive = shs
break
}
}
// SetOptChart replaces the chart data for a symol in the route specified in opt to the values in scns.
func (ss *StockStore) SetOptChart(opt config.ShareOpt, symbol string, scns []config.StockChartNode) {
switch opt {
case config.Gainers:
ss.gainersChart[symbol] = scns
break
case config.Losers:
ss.losersChart[symbol] = scns
break
case config.MostActive:
ss.mostActiveChart[symbol] = scns
break
}
}
// Gainers returns the gainers saved in the stock store
func (ss *StockStore) Gainers() []config.StockInfo {
return ss.gainers
}
// Losers returns the losers saved in the stock store
func (ss *StockStore) Losers() []config.StockInfo {
return ss.losers
}
// MostActive returns the most active stocks saved in the stock store
func (ss *StockStore) MostActive() []config.StockInfo {
return ss.mostActive
}
// GainersChart returns the chart data belonging to the gainers in the stock store
func (ss *StockStore) GainersChart() map[string][]config.StockChartNode {
return ss.gainersChart
}
// LosersChart returns the chart data belonging to the losers in the stock store
func (ss *StockStore) LosersChart() map[string][]config.StockChartNode {
return ss.losersChart
}
// MostActiveChart returns the chart data belonging to the most active stocks in the stock store
func (ss *StockStore) MostActiveChart() map[string][]config.StockChartNode {
return ss.mostActiveChart
}
|
{-# Language Safe #-}
{-|
Module : Intcode.Parse
Description : Intcode source file parser
Copyright : (c) Eric Mertens, 2019
License : ISC
Maintainer : [email protected]
This module implements a parser for the simple comma, separated format
used in the Advent of Code input files.
-}
module Intcode.Parse (parseInts) where
-- | Parse a list of comma separated integers.
--
-- >>> parseInts "1, - 2, 3,-4"
-- Just [1,-2,3,-4]
--
-- >>> parseInts " "
-- Just []
--
-- >>> parseInts "1,2,3,x"
-- Nothing
parseInts ::
String {- ^ parser input -} ->
Maybe [Int] {- ^ parsed integers -}
parseInts str
| [(i,str1)] <- reads str = parseInts' [i] str1
| [("","")] <- lex str = Just []
| otherwise = Nothing
-- | Helper function for 'parseInts'
parseInts' ::
[Int] {- ^ reversed accumulator -} ->
String {- ^ parser input -} ->
Maybe [Int] {- ^ parsed integers -}
parseInts' xs str =
case lex str of
[(",",str1)] | [(x,str2)] <- reads str1 -> parseInts' (x:xs) str2
[("","")] -> Just (reverse xs)
_ -> Nothing
|
๏ปฟusing System.Windows;
namespace GitHelper.UIExtension
{
public static class Utility
{
public static bool? ShowDialog(Window window)
{
window.Owner = Application.Current.MainWindow;
return window.ShowDialog();
}
}
}
|
/*-
* #%L
* anchor-core
* %%
* Copyright (C) 2010 - 2020 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche
* %%
* 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.
* #L%
*/
package org.anchoranalysis.inference.concurrency;
import java.util.Optional;
import java.util.concurrent.PriorityBlockingQueue;
import org.anchoranalysis.core.functional.FunctionalIterate;
import org.anchoranalysis.core.functional.checked.CheckedFunction;
import org.anchoranalysis.core.log.Logger;
import org.anchoranalysis.inference.InferenceModel;
/**
* Keeps concurrent copies of a model to be used by different threads.
*
* <p>The copies van variously use GPU and CPU for execution, with GPU always being given priority.
*
* @author Owen Feehan
* @param <T> model-type
*/
public class ConcurrentModelPool<T extends InferenceModel> implements AutoCloseable {
/**
* A queue that prioritizes if {@code hasPriority==true} and blocks if {@link
* PriorityBlockingQueue#take} is called but no elements are available.
*/
private PriorityBlockingQueue<WithPriority<ConcurrentModel<T>>> queue;
/** Function to create a model. */
private final CreateModelForPool<T> createModel;
/**
* Creates with a particular plan and function to create models.
*
* @param plan a plan determining how many CPUs and GPUs to use for inference.
* @param createModel called to create a new model, as needed.
* @param logger where feedback is written about how many GPUs or CPUs were selected.
* @throws CreateModelFailedException if a model cannot be created.
*/
public ConcurrentModelPool(
ConcurrencyPlan plan, CreateModelForPool<T> createModel, Logger logger)
throws CreateModelFailedException {
this.createModel = createModel;
this.queue = new PriorityBlockingQueue<>();
int gpusAdded = addNumberModels(plan.numberGPUs(), true, createModel);
GPUMessageLogger.maybeLog(plan.numberGPUs(), gpusAdded, logger.messageLogger());
// TODO is it necessary to always keep a CPU in reserve, in case the GPU fails?
addNumberModels(plan.numberCPUs() - gpusAdded, false, createModel);
}
/**
* Execute on the next available model (or wait until one becomes available).
*
* <p>If an exception is thrown while executing on a GPU, the GPU processor is no longer used,
* and instead an additional CPU node is added. The failed job is tried again.
*
* @param functionToExecute function to execute on a given model, possibly throwing an
* exception.
* @param <S> return type
* @return the value returned by {@code functionToExecute} after it is executed.
* @throws Throwable if thrown from {@code functionToExecute} while executing on a CPU. It is
* suppressed if thrown on a GPU.
*/
public <S> S executeOrWait(
CheckedFunction<ConcurrentModel<T>, S, ConcurrentModelException> functionToExecute)
throws Throwable { // NOSONAR
while (true) {
WithPriority<ConcurrentModel<T>> model = getOrWait();
try {
S returnValue = functionToExecute.apply(model.get());
// When finished executing without error we return the model to the pool
giveBack(model);
return returnValue;
} catch (ConcurrentModelException e) {
if (model.isGPU()) {
// Add extra CPU model, and try to execute the function again
addNumberModels(1, false, createModel);
} else {
// Rethrow if error occurred on a CPU
throw e.getCause();
}
}
}
}
/**
* Close all models, to indicate they are no longer in use, and to perform tidy-up.
*
* @throws Exception if a model cannot be successfully closed.
*/
@Override
public void close() throws Exception {
for (WithPriority<ConcurrentModel<T>> model : queue) {
model.get().getModel().close();
}
}
/**
* Gets an instantiated model to be used.
*
* <p>After usage, {@link #giveBack} should be called to return the model to the pool.
*
* @return the model to be used concurrently, with an associated priority.
* @throws InterruptedException
*/
private WithPriority<ConcurrentModel<T>> getOrWait() throws InterruptedException {
return queue.take();
}
/**
* Returns the model to the pool.
*
* @param model the model to return
*/
private void giveBack(WithPriority<ConcurrentModel<T>> model) {
queue.put(model);
}
private int addNumberModels(int numberModels, boolean useGPU, CreateModelForPool<T> createModel)
throws CreateModelFailedException {
return FunctionalIterate.repeatCountSuccessful(
numberModels, () -> addModelCatchGPUException(useGPU, createModel));
}
/** Creates a model, return a boolean indicating whether it was successful or not. */
private boolean addModelCatchGPUException(boolean useGPU, CreateModelForPool<T> createModel)
throws CreateModelFailedException {
if (useGPU) {
try {
return createAdd(true, createModel);
} catch (CreateModelFailedException e) {
// TODO Should this be logged somewhere, to give more information?
return false;
}
} else {
return createAdd(false, createModel);
}
}
private boolean createAdd(boolean useGPU, CreateModelForPool<T> createModel)
throws CreateModelFailedException {
Optional<ConcurrentModel<T>> model = createModel.create(useGPU);
if (model.isPresent()) {
WithPriority<ConcurrentModel<T>> priority = new WithPriority<>(model.get(), useGPU);
queue.add(priority);
return true;
} else {
return false;
}
}
}
|
๏ปฟusing UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class MagicLoadSceneOnClick : MonoBehaviour
{
public void LoadSceneProjectiles()
{
SceneManager.LoadScene("magic_projectiles");
}
public void LoadSceneSprays()
{
SceneManager.LoadScene("magic_sprays");
}
public void LoadSceneAura()
{
SceneManager.LoadScene("magic_aura");
}
public void LoadSceneModular()
{
SceneManager.LoadScene("magic_modular");
}
public void LoadSceneShields2()
{
SceneManager.LoadScene("magic_domes");
}
public void LoadSceneShields()
{
SceneManager.LoadScene("magic_shields");
}
public void LoadSceneSphereBlast()
{
SceneManager.LoadScene("magic_sphereblast");
}
public void LoadSceneEnchant()
{
SceneManager.LoadScene("magic_enchant");
}
public void LoadSceneSlash()
{
SceneManager.LoadScene("magic_slash");
}
public void LoadSceneCharge()
{
SceneManager.LoadScene("magic_charge");
}
public void LoadSceneCleave()
{
SceneManager.LoadScene("magic_cleave");
}
public void LoadSceneAura2()
{
SceneManager.LoadScene("magic_aura2");
}
public void LoadSceneWalls()
{
SceneManager.LoadScene("magic_walls");
}
public void LoadSceneBeams()
{
SceneManager.LoadScene("magic_beams");
}
public void LoadSceneMeshGlow()
{
SceneManager.LoadScene("magic_meshglow");
}
public void LoadScenePillarBlast()
{
SceneManager.LoadScene("magic_pillarblast");
}
} |
Pour rรฉaliser Bruce, vous aurez besoin de :
- Fourniture de base pour la couture
- Environ 1 m d'un tissu adaptรฉ ([voir Options de tissu](/docs/patterns/bruce/fabric/))
- Un รฉlastique assez large (3cm ou plus)
- Unu surjeteuse, bien que vous puissiez survivre sans
|
#!usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Blockchain module.
"""
__author__ = 'Ziang Lu'
import json
import random
from multiprocessing import Process, Queue
from string import ascii_letters, digits
from block import Block
from mining import Miner
class BlockChain:
"""
Blockchain class.
"""
__slots__ = ['_chain', '_miners']
_DIFFICULTY = 4
# By setting difficulty = 4, we get around 1~2 seconds between generating
# two valid blocks.
@staticmethod
def _gen_transaction() -> str:
"""
Private static helper method to randomly generates a transaction.
:return: str
"""
transaction = {
'sender': ''.join(random.sample(ascii_letters + digits, 8)),
'recipient': ''.join(random.sample(ascii_letters + digits, 8)),
'amount': random.randint(100, 1000)
}
return json.dumps(transaction)
def __init__(self):
"""
Default constructor.
"""
self._chain = []
self.gen_block(genesis=True)
# Set 6 miners
self._miners = [Miner() for _ in range(6)]
def gen_block(self, genesis=False) -> None:
"""
Generates the next block and adds it to the chain.
:param genesis: bool
:return: None
"""
if genesis:
genesis_block = Block(prev_hash='0', data=[])
genesis_block.hash_block(nonce=random.randint(0, 99999))
self._chain.append(genesis_block)
return
prev_hash = self._chain[-1].hash
transaction = self._gen_transaction()
# Let the miners start mining
processes = []
result_q = Queue()
for miner in self._miners:
th = Process(
target=miner.mine,
args=(
prev_hash, [transaction], self._DIFFICULTY, result_q
)
)
processes.append(th)
for p in processes:
p.start()
for p in processes:
p.join()
new_block = result_q.get(block=False)
self._chain.append(new_block)
new_block.print_block()
if __name__ == '__main__':
block_chain = BlockChain()
for _ in range(10):
block_chain.gen_block()
|
---
lastname: Hjalmarsson
name: anna-hjalmarsson
title: Anna Hjalmarsson
---
|
// Package ansiparser is a package for parsing strings with ANSI or VT-100 control codes.
//
package ansiparser
const bel = 7
const st = "\u001B\\"
//go:generate stringer -type=TokenType
// TokenType represents the type of a parsed token.
type TokenType int
const (
// String represents a token containing a plain string.
String TokenType = 0
// EscapeCode represents an escape code.
EscapeCode TokenType = 1
)
// AnsiToken represents a substring parsed from a string containing ANSI escape
// codes.
type AnsiToken struct {
// Type is the type of this token.
Type TokenType
// Content is a slice of the original string which represents the content of
// this token.
Content string
// The foreground color of the text represented by this token, as ANSI codes
// (e.g. "31" for red, or "38;2;255;20;20" for an RGB color), or an empty
// string if this is uncolored. If Type is EscapeCode and this clears the
// current foreground color, this will be "39".
FG string
// The background color of the text represented by this token, as ANSI codes
// (e.g. "31" for red, or "38;2;255;20;20" for an RGB color), or an empty
// string if this is uncolored. If Type is EscapeCode and this clears the
// current foreground color, this will be "49".
BG string
// IsASCII is true if this string only contains ASCII characters.
IsASCII bool
}
// Parse parses a string containing ANSI escape codes into a slice of one or more
// AnsiTokens.
func Parse(str string) []AnsiToken {
tokens := make([]AnsiToken, 0, 1)
tokenizer := NewStringTokenizer(str)
for tokenizer.Next() {
tokens = append(tokens, tokenizer.Token())
}
return tokens
}
|
๏ปฟ// Copyright (c) 2013, Dijji, and released under Ms-PL. This, with other relevant licenses, can be found in the root of this distribution.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows;
using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;
using System.Runtime.InteropServices;
namespace TestDriver
{
public class ExportImport1 : Test
{
public override string Name { get { return "Export 1 property, import to different file"; } }
public override bool RunBody(State state)
{
RequirePropertyHandlerRegistered();
RequireContextHandlerRegistered();
RequireExtHasHandler();
const string cval = "exp-imp";
string propertyName = "System.Comment";
//Create a temp file to put metadata on
string fileName = CreateFreshFile(1);
// Use API Code Pack to set the value
IShellProperty prop = ShellObject.FromParsingName(fileName).Properties.GetProperty(propertyName);
(prop as ShellProperty<string>).Value = cval;
// Set up ContextHandler and tell it about the target file
var handler = new CContextMenuHandler();
var dobj = new DataObject();
dobj.SetFileDropList(new StringCollection{fileName});
handler.Initialize(new IntPtr(0), dobj, 0);
handler.QueryContextMenu(0, 0, 0, 0, 0); // This fails, but that's ok
//export the metadata
CMINVOKECOMMANDINFOEX cmd = new CMINVOKECOMMANDINFOEX();
cmd.lpVerb = new IntPtr((int)ContextMenuVerbs.Export);
var cw = new CommandWrapper(cmd);
handler.InvokeCommand(cw.Ptr);
// Create a 2nd temp file for import
string fileName2 = CreateFreshFile(2);
Marshal.ReleaseComObject(handler); // preempt GC for CCW
// rename metadata file
RenameWithDelete(MetadataFileName(fileName), MetadataFileName(fileName2));
// Get a new handler and import
handler = new CContextMenuHandler();
dobj = new DataObject();
dobj.SetFileDropList(new StringCollection { fileName2 });
handler.Initialize(new IntPtr(0), dobj, 0);
handler.QueryContextMenu(0, 0, 0, 0, 0); // This fails, but that's ok
cmd = new CMINVOKECOMMANDINFOEX();
cmd.lpVerb = new IntPtr((int)ContextMenuVerbs.Import);
cw = new CommandWrapper(cmd);
handler.InvokeCommand(cw.Ptr);
Marshal.ReleaseComObject(handler); // preempt GC for CCW
// Use API Code Pack to read the value
prop = ShellObject.FromParsingName(fileName2).Properties.GetProperty(propertyName);
object oval = prop.ValueAsObject;
// Clean up files - checks if they have been released, too
File.Delete(fileName);
File.Delete(fileName2);
File.Delete(MetadataFileName(fileName2));
// good if original value has made it round
return cval == (string)oval;
}
}
public class ExportImport2 : Test
{
public override string Name { get { return "Export non-Latin properties, import to different file"; } }
public override bool RunBody(State state)
{
RequirePropertyHandlerRegistered();
RequireContextHandlerRegistered();
RequireExtHasHandler();
string cval1 = "ํ ๋ง์์ด";
string[] cval2 = { "hello", "ะัะธะฒะตัััะฒะธั" };
string cval3 = "title";
string propertyName1 = "System.Comment";
string propertyName2 = "System.Category";
string propertyName3 = "System.Title";
//Create a temp file to put metadata on
string fileName = CreateFreshFile(1);
// Use API Code Pack to set the values
IShellProperty prop1 = ShellObject.FromParsingName(fileName).Properties.GetProperty(propertyName1);
(prop1 as ShellProperty<string>).Value = cval1;
IShellProperty prop2 = ShellObject.FromParsingName(fileName).Properties.GetProperty(propertyName2);
(prop2 as ShellProperty<string[]>).Value = cval2;
IShellProperty prop3 = ShellObject.FromParsingName(fileName).Properties.GetProperty(propertyName3);
(prop3 as ShellProperty<string>).Value = cval3;
// Set up ContextHandler and tell it about the target file
var handler = new CContextMenuHandler();
var dobj = new DataObject();
dobj.SetFileDropList(new StringCollection { fileName });
handler.Initialize(new IntPtr(0), dobj, 0);
handler.QueryContextMenu(0, 0, 0, 0, 0); // This fails, but that's ok
//export the metadata
CMINVOKECOMMANDINFOEX cmd = new CMINVOKECOMMANDINFOEX();
cmd.lpVerb = new IntPtr((int)ContextMenuVerbs.Export);
var cw = new CommandWrapper(cmd);
handler.InvokeCommand(cw.Ptr);
// Create a 2nd temp file for import
string fileName2 = CreateFreshFile(2);
Marshal.ReleaseComObject(handler); // preempt GC for CCW
// rename metadata file
RenameWithDelete(MetadataFileName(fileName), MetadataFileName(fileName2));
// Get a new handler and import
handler = new CContextMenuHandler();
dobj = new DataObject();
dobj.SetFileDropList(new StringCollection { fileName2 });
handler.Initialize(new IntPtr(0), dobj, 0);
handler.QueryContextMenu(0, 0, 0, 0, 0); // This fails, but that's ok
cmd = new CMINVOKECOMMANDINFOEX();
cmd.lpVerb = new IntPtr((int)ContextMenuVerbs.Import);
cw = new CommandWrapper(cmd);
handler.InvokeCommand(cw.Ptr);
Marshal.ReleaseComObject(handler); // preempt GC for CCW
// Use API Code Pack to read the values
prop1 = ShellObject.FromParsingName(fileName2).Properties.GetProperty(propertyName1);
string result1 = (string)prop1.ValueAsObject;
prop2 = ShellObject.FromParsingName(fileName2).Properties.GetProperty(propertyName2);
string[] result2 = (string[]) prop2.ValueAsObject;
prop3 = ShellObject.FromParsingName(fileName2).Properties.GetProperty(propertyName3);
string result3 = (string)prop3.ValueAsObject;
// Clean up files - checks if they have been released, too
File.Delete(fileName);
File.Delete(fileName2);
File.Delete(MetadataFileName(fileName2));
// good if original value has made it round
return cval1 == result1 && result2.Length == 2 && cval2[0] == result2[0] && cval2[1] == result2[1] && cval3 == result3;
}
}
}
|
# simp-core additions to deps-namespaced targets
#
# This is a playground for tasks that may eventually be moved to
# simp-rake-helpers or simp-build-helpers
#
require_relative 'simp_core_deps_helper'
include Simp::SimpCoreDepsHelper
namespace :deps do
desc <<-EOM
Remove all checked-out dependency repos
Uses specified Puppetfile to identify the checked-out repos.
Arguments:
* :suffix => The Puppetfile suffix to use (Default => 'tracking')
* :remove_cache => Whether to remove the R10K cache after removing the
checked-out repos (Default => false)
EOM
task :clean, [:suffix,:remove_cache] do |t,args|
args.with_defaults(:suffix => 'tracking')
args.with_defaults(:remove_cache => false)
base_dir = File.dirname(File.dirname(__FILE__))
r10k_helper = R10KHelper.new("Puppetfile.#{args[:suffix]}")
Parallel.map(
Array(r10k_helper.modules),
:in_processes => get_cpu_limit,
:progress => 'Dependency Removal'
) do |mod|
Dir.chdir(base_dir) do
FileUtils.rm_rf(mod[:path])
end
end
if args[:remove_cache]
cache_dir = File.join(base_dir, '.r10k_cache')
FileUtils.rm_rf(cache_dir)
end
end
desc <<-EOM
EXPERIMENTAL: Generate a list of SIMP changes since a previous simp-core tag.
- Output logged to the console
- Output includes:
- simp-core changes noted in its git logs
- simp.spec %changelog changes
- Individual SIMP component changes noted both in its git logs and its
CHANGELOG file or %changelog section of its build/<component>.spec file.
- The changes are from the version listed in the tag's Puppetfile
to the version specified in the current Puppetfile
- Output does **not** include any changes of non-SIMP components
EXAMPLE USAGE:
bundle exec rake deps:changes_since[6.5.0-1]
CAUTION:
Executes `deps:clean` followed by a `deps:checkout`.
This means you will lose any local changes made to checked out
component repositories.
FAILS:
- The simp-core tag specified is not available locally.
- The specified Puppetfile at the simp-core tag is not available.
Arguments:
* :prev_tag => simp-core previous version tag
* :prev_suffix => The Puppetfile suffix to use from the previous simp-core tag;
DEFAULT: 'pinned'
* :curr_suffix => The Puppetfile suffix to use from this simp-core checkout
DEFAULT: 'pinned'
* :brief => Only show 1 line git log summaries; DEFAULT: false
* :debug => Log status gathering actions; DEFAULT: false
EOM
task :changes_since, [:prev_tag,:prev_suffix,:curr_suffix,:brief,:debug] do |t,args|
args.with_defaults(:prev_suffix => 'pinned')
args.with_defaults(:curr_suffix => 'pinned')
args.with_defaults(:brief => 'false')
args.with_defaults(:debug => 'false')
# ensure starting with a clean deps checkout
Rake::Task['deps:clean'].invoke(args[:current_suffix])
Rake::Task['deps:checkout'].invoke(args[:current_suffix])
base_dir = File.dirname(File.dirname(__FILE__))
opts = args.to_hash
opts[:brief] = (opts[:brief] == 'true') ? true : false
opts[:debug] = (opts[:debug] == 'true') ? true : false
changes = gather_changes(base_dir, opts)
log_changes(changes, args[:prev_tag])
end
end
|
package knf.kuma.tv.exoplayer
import android.annotation.TargetApi
import android.content.Context
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.leanback.app.VideoSupportFragment
import androidx.leanback.app.VideoSupportFragmentGlueHost
import com.google.android.exoplayer2.DefaultRenderersFactory
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.trackselection.TrackSelector
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory
import com.google.android.exoplayer2.util.Util
class PlaybackFragment : VideoSupportFragment() {
private var mPlayerGlue: VideoPlayerGlue? = null
private var mPlayerAdapter: LeanbackPlayerAdapter? = null
private var mPlayer: SimpleExoPlayer? = null
private var mTrackSelector: TrackSelector? = null
private var mVideo: Video? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mVideo = Video(activity?.intent?.extras)
}
override fun onStart() {
super.onStart()
if (Util.SDK_INT > 23) {
initializePlayer()
}
}
override fun onResume() {
super.onResume()
if (Util.SDK_INT <= 23 || mPlayer ==
null) {
initializePlayer()
}
}
/**
* Pauses the exoPlayer.
*/
@TargetApi(Build.VERSION_CODES.N)
override fun onPause() {
super.onPause()
if (mPlayerGlue?.isPlaying == true)
mPlayerGlue?.pause()
if (Util.SDK_INT <= 23) {
releasePlayer()
}
}
override fun onStop() {
super.onStop()
if (Util.SDK_INT > 23) {
releasePlayer()
}
}
private fun initializePlayer() {
val bandwidthMeter = DefaultBandwidthMeter.Builder(requireContext()).build()
val videoTrackSelectionFactory = AdaptiveTrackSelection.Factory()
mTrackSelector = DefaultTrackSelector(requireContext(),videoTrackSelectionFactory)
mPlayer = SimpleExoPlayer.Builder(requireContext(),DefaultRenderersFactory(requireContext())).build()
mPlayerAdapter = LeanbackPlayerAdapter(activity as Context, mPlayer as SimpleExoPlayer, UPDATE_DELAY)
mPlayerGlue = VideoPlayerGlue(activity as Context, mPlayerAdapter as LeanbackPlayerAdapter)
mPlayerGlue?.host = VideoSupportFragmentGlueHost(this)
mPlayerGlue?.playWhenPrepared()
play(mVideo)
}
private fun releasePlayer() {
mPlayer?.release()
mPlayer = null
mTrackSelector = null
mPlayerGlue = null
mPlayerAdapter = null
}
private fun play(video: Video?) {
mPlayerGlue?.title = video?.title
mPlayerGlue?.subtitle = video?.chapter
prepareMediaForPlaying(video?.uri ?: Uri.EMPTY, video?.headers)
mPlayerGlue?.play()
}
private fun prepareMediaForPlaying(mediaSourceUri: Uri, headers: HashMap<String, String>?) {
activity?.let {
val userAgent = Util.getUserAgent(it, "UKIKU")
val mediaSource = ProgressiveMediaSource.Factory(
DefaultHttpDataSourceFactory(userAgent, null, 10000, 10000, true).apply {
headers?.forEach { header ->
defaultRequestProperties.set(header.key, header.value)
}
})
.createMediaSource(mediaSourceUri)
mPlayer?.prepare(mediaSource)
}
}
fun skipToNext() {
mPlayerGlue?.next()
}
fun skipToPrevious() {
mPlayerGlue?.previous()
}
fun rewind() {
mPlayerGlue?.rewind()
}
fun fastForward() {
mPlayerGlue?.fastForward()
}
companion object {
private const val UPDATE_DELAY = 16
operator fun get(bundle: Bundle?): PlaybackFragment {
val fragment = PlaybackFragment()
fragment.arguments = bundle
return fragment
}
}
}
|
# bosch-heatpump-canbus
A small project using a Raspberry Pi and PiCan to read canbus messages from a Bosch Compress 6000 heat pump
Heat pump controller: rego1000
|
import React, { useCallback, useState } from "react";
import { FaChevronDown, FaChevronRight, FaCube, FaRegSquare } from "react-icons/fa";
import { ObjectsAction } from "../../utils/Types";
import { ObjectTree, SceneObject, SceneObject2D } from "../../utils/SceneObject";
import "./Explorer.scss";
interface Props {
objects: ObjectTree;
objectsDispatch: React.Dispatch<ObjectsAction>;
total: number;
selected: SceneObject | undefined;
select: (obj: SceneObject) => void;
}
export default function Explorer(props: Props) {
const { objects, objectsDispatch, total, selected, select } = props;
const [expandedObjNames, setExpandedObjNames] = useState<Array<string>>([]);
const [draggedObj, setDraggedObj] = useState<SceneObject>();
const { startDrag, dragging, mouseX, mouseY } = useMouseDrag();
function listItemMouseDown(obj: SceneObject, evt: React.MouseEvent<HTMLLIElement, MouseEvent>) {
setDraggedObj(obj);
startDrag(evt);
document.addEventListener("mousemove", dragging);
document.addEventListener("mouseup", documentMouseUp);
}
function listItemMouseUp(obj: SceneObject, evt: React.MouseEvent<HTMLLIElement, MouseEvent>) {
if (draggedObj && draggedObj.name !== obj.name) {
objectsDispatch({ type: "moveInto", parentName: obj.name, newChild: draggedObj });
setExpandedObjNames([...expandedObjNames, obj.name]);
}
document.removeEventListener("mousemove", dragging);
document.removeEventListener("mouseup", documentMouseUp);
setDraggedObj(undefined);
evt.stopPropagation();
}
function objectListMouseUp(evt: React.MouseEvent<HTMLDivElement, MouseEvent>) {
if (draggedObj) {
objectsDispatch({ type: "moveInto", newChild: draggedObj });
document.removeEventListener("mousemove", dragging);
document.removeEventListener("mouseup", documentMouseUp);
setDraggedObj(undefined);
evt.stopPropagation();
}
}
const documentMouseUp = useCallback(() => {
document.removeEventListener("mousemove", dragging);
document.removeEventListener("mouseup", documentMouseUp);
setDraggedObj(undefined);
}, [dragging]);
//#region RENDER FUNCTIONS
function renderHeader(): JSX.Element {
return (
<div className="flex-column">
<div className="flex-row align-center justify-space-between">
<p>
{total} object{total !== 1 ? "s" : ""} in total
</p>
<button
onClick={() => {
objectsDispatch({ type: "addRnd" });
}}
>
Add +
</button>
</div>
<div className="flex-row align-center justify-space-between">
<button
onClick={() => {
let newExpanded = [];
for (const obj of objects.preOrderTraversal()) {
newExpanded.push(obj.name);
}
setExpandedObjNames(newExpanded);
}}
>
Expand all
</button>
<button
onClick={() => {
setExpandedObjNames([]);
}}
>
Collapse all
</button>
</div>
</div>
);
}
function renderObjectListItem(obj: SceneObject): JSX.Element {
let className: string;
let expanded: boolean = expandedObjNames.includes(obj.name);
if (selected && obj.name === selected.name) className = "object-list-item object-list-item-selected";
else className = "object-list-item";
return (
<React.Fragment key={`list-item-container-${obj.name}`}>
<li
key={`list-item-${obj.name}`}
className={className}
onClick={() => select(obj)}
onMouseDown={(evt) => listItemMouseDown(obj, evt)}
onMouseUp={(evt) => listItemMouseUp(obj, evt)}
>
{obj.children.length > 0 ? (
renderExpander(obj.name, expanded)
) : (
<div className="object-list-spacer" />
)}
{renderObjectIcon(obj instanceof SceneObject2D)}
{obj.name}
</li>
{renderListItemChildren(expanded, obj)}
</React.Fragment>
);
}
function renderListItemChildren(expanded: boolean, obj: SceneObject) {
if (expanded) {
return (
<ul key={`sub-list-item-${obj.name}`} className="sub-object-list">
{obj.children.map((child, index) => renderObjectListItem(child))}
</ul>
);
}
}
function renderObjectIcon(is2D: boolean) {
return is2D ? <FaRegSquare className="object-list-icon" /> : <FaCube className="object-list-icon" />;
}
function renderExpander(objName: string, expanded: boolean) {
if (expanded) {
return (
<FaChevronDown
className="object-list-expander"
onClick={(evt) => {
evt.stopPropagation();
var index = expandedObjNames.indexOf(objName);
if (index !== -1) {
setExpandedObjNames([
...expandedObjNames.slice(0, index),
...expandedObjNames.slice(index + 1),
]);
}
}}
/>
);
} else {
return (
<FaChevronRight
className="object-list-expander"
onClick={(evt) => {
evt.stopPropagation();
setExpandedObjNames([...expandedObjNames, objName]);
}}
/>
);
}
}
function renderDraggedObjGhost() {
if (draggedObj)
return (
<div className="dragged-object-ghost" style={{ top: mouseY, left: mouseX + 20 }}>
{draggedObj.name}
</div>
);
}
//#endregion
return (
<div className="flex-column explorer">
<h3>Explorer</h3>
{renderHeader()}
<div className="object-list-container" onMouseUp={objectListMouseUp}>
<ul className="object-list">{objects.getObjectList().map((obj) => renderObjectListItem(obj))}</ul>
</div>
{renderDraggedObjGhost()}
</div>
);
}
function useMouseDrag() {
const [mouseX, setMouseX] = useState<number>(-1);
const [mouseY, setMouseY] = useState<number>(-1);
const dragging = useCallback((evt: MouseEvent) => {
setMouseX(evt.clientX);
setMouseY(evt.clientY);
}, []);
const startDrag = useCallback((evt: React.MouseEvent<HTMLLIElement, MouseEvent>) => {
setMouseX(evt.clientX);
setMouseY(evt.clientY);
}, []);
return { startDrag, dragging, mouseX, mouseY };
}
|
DROP database if exists MMRS_Data;
create database if not exists MMRS_Data;
use MMRS_Data;
create table CUSTOMER
(Username varchar(20) primary key,
Fname varchar(10),
Lname varchar(10),
Address varchar(20),
Phone_No varchar(10),
Password varchar(16)
);
create table ADMIN
(Admin_Id int primary key AUTO_INCREMENT,
Admin_Name varchar(20),
Age int,
Sex char(1),
Email varchar(30),
Password varchar(16)
);
CREATE TRIGGER age_less_than_18 BEFORE INSERT ON admin
FOR EACH ROW
BEGIN
IF NEW.Age < 18 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = "Admins must be 18+";
END IF;
END;
create table SMARTCARD
(Card_No varchar(10) primary key,
Balance decimal,
Card_Status varchar(15) NOT NULL DEFAULT 'Pending',
Username varchar(20),
Admin_Id int,
foreign key(Username) references CUSTOMER(Username) on delete cascade,
foreign key(Admin_Id) references ADMIN(Admin_Id)
);
create table ROUTE
(Route_Id int primary key,
Route_Name varchar(200)
);
create table STATION
(Station_Name varchar(25),
Route_Id int,
primary key(Station_Name,Route_Id)
);
create table TRAIN
(Train_Id int primary key AUTO_INCREMENT,
Admin_Id int,
Route_Id int,
foreign key(Admin_Id) references ADMIN(Admin_Id),
foreign key(Route_Id) references ROUTE(Route_Id) on delete cascade
);
create table COMPLAINT
(Comp_Id int primary key AUTO_INCREMENT,
Comp_Subject varchar(50),
Comp_Desc varchar(500),
Comp_Status varchar(20) NOT NULL DEFAULT 'Not_Replied',
Username varchar(20),
foreign key(Username) references CUSTOMER(Username)
);
create table EMAIL
(Username varchar(200),
Email varchar(200),
primary key(Username,Email),
foreign key(Username) references CUSTOMER(Username) on delete cascade
);
create table DISPLAY_STATUS
(From_Station varchar(25),
To_Station varchar(25),
Arrival time,
Departure time,
Train_id int,
primary key(From_Station,To_Station,Train_Id),
foreign key(From_Station) references STATION(Station_Name) on delete cascade,
foreign key(To_Station) references STATION(Station_Name) ,
foreign key(Train_Id) references TRAIN(Train_Id) on delete cascade
);
|
/*
* Hackas - HACK Assembler
* HACK Assembly Instructions
*/
package co.mrzzy.nand2tetris.p1.project6;
import Symbols.SymbolPattern;
import Symbols.BuiltinSymbols;
import javax.naming.NameAlreadyBoundException
/** Represents a HACK Assembly Instruction.
*
* Can either represent a real Hack Assembly assemable to HACK Machine Language Instruction
* or a Virtual Instruction.
*/
sealed trait Instruction {
/** Convert this Assembly [[Instruction]] to its binary Hack Machine Language representation
*
* Resolves symbols in the instruction and assembles it into its binary equavilent.
*
* Note:
* Since Virtual Instructions have no binary representation this method will
* return empty string for Virtual instructions.
*
* @param symTable to use to resolve symbols used in the instuction.f
* @return The binary HACK Machine Language representation of this instruction
*/
def toBinary(symTable: Symbols.SymbolTable): String
/** Whether this [[Instruction]] is a Virtual Instruction
*
* Virtual Instruction: Has no binary representation as it does not actually
* exist in HACK Machine Language.
*/
def isVirtual: Boolean
}
/** Represents a A-Kind HACK instruction in the format @ADDRESS
*
* The A instruction assigns the given address to the A register.
* ADDRESS must be an non empty numeric or symbolic addresss.
*
* @throws IllegalArgumentException if addr given is not a valid numeric or symbolic address
* @throws OutOfMemoryError if given a numeric address that overflows
* the instruction's 15-bit address field
*/
// TODO(mrzzy): merge addr and address fields
case class AInstruction(private val addr: String) extends Instruction {
// check that address is symbolic or numeric (made of digits)
val address = if (!(SymbolPattern.matches(addr) || addr.forall(_.isDigit))) {
throw new IllegalArgumentException(
s"A Instruction expected symbol or numeric addresss but got: @$addr"
)
} else if (addr.forall(_.isDigit) && addr.toInt.toBinaryString.length > 15) {
// numeric address: check address fits in 16 bits
throw new OutOfMemoryError(
s"Numeric address given overflows 15-bit address field: $addr"
)
} else addr
def toBinary(symTable: Symbols.SymbolTable): String = {
// resolve label symbol if address used is symbolic
val numAddr = if (SymbolPattern.matches(address)) {
symTable(address)
} else address.toInt
// rewrite A instruction as binary: [op] [15-bit address]
val binAddr = numAddr.toBinaryString
val zeroPad = "0" * (15 - binAddr.length)
// A instruction is signified by op = 0
"0" + zeroPad + binAddr
}
override def toString = s"@$address"
override def isVirtual: Boolean = false
}
/** Represents a C-Kind HACK instruction in the format DEST=COMPUTE;JUMP
*
* COMPUTE defines the computation to be done and must be one of the
* predefined computations in the compute truth table.
*
* The JUMP directive optionally jumps the instruction addressed by
* the A register and must be one of jump directives in the jump truth table.
*
* DEST optionally defines the destination registers (A, M and/or D) to store
* result of COMPUTE. DEST is position invariant ie specifying 'AD' is equavilent
* to specifying 'DA'.
*
* @throws UnsupportedOperationException if CInstruction constructed is unsupported
*/
// TODO(mrzzy): merge short and long fields (ie dest and destination)
case class CInstruction(
private val dest: String,
private val comp: String,
private val jmp: String
) extends Instruction {
// check that destination is supported
val destination = if ((dest.toSet &~ "ADM".toSet).size > 0) {
throw new UnsupportedOperationException(
s"C Instruction only supports A,M and/or D as destination(s), got: ${dest}"
)
} else dest
// check that the compute operation are supported
val computeTable = CInstruction.ComputeTruthTable
val compute = if (!computeTable.contains(comp)) {
val supportedOps = computeTable.keySet.mkString(", ")
throw new UnsupportedOperationException(
s"Given compute operation in C instruction is unsupported: ${comp}" +
s".\n Supported computations: ${supportedOps}"
)
} else comp
// check that the compute operation
val jumpTable = CInstruction.JumpTruthTable
val jump = if (!jumpTable.contains(jmp)) {
val supportedJumps = jumpTable.keySet.mkString(", ")
throw new UnsupportedOperationException(
s"Unsupported jump directive in C instruction used: ${jmp}" +
s".\n Supported jump directives: ${supportedJumps}"
)
} else jmp
def toBinary(symTable: Symbols.SymbolTable): String = {
// convert destinations to binary by setting bits for each destination
val binDest = "ADM".map {
case dest if destination.contains(dest) => "1"
case _ => "0"
}.mkString
// convert compute & jump to binary using truth table
val binCompute = CInstruction.ComputeTruthTable(compute)
val binJump = CInstruction.JumpTruthTable(jump)
// form binary C instruction in the form: 1 1 1 [compute] [dest] [jump]
"111" + binCompute + binDest + binJump
}
override def toString = {
(if (destination.length > 0) s"$destination=" else "") + compute +
(if (jump.length > 0) s";$jump" else "")
}
override def isVirtual: Boolean = false
}
/* [[CInstruction]] companion object */
object CInstruction {
/** Compute bit truth table mapping compute operation to HACK Machine Language
*
* Maps compute operation to binary bits in the format: a c1 c2 c3 c4 c5 c6
*/
private val computeTruthTable = Map(
"0" -> "0101010",
"1" -> "0111111",
"-1" -> "0111010",
"D" -> "0001100",
"A" -> "0110000",
"!D" -> "0001101",
"!A" -> "0110001",
"-D" -> "0011111",
"-A" -> "0110011",
"D+1" -> "0011111",
"A+1" -> "0110111",
"D-1" -> "0001110",
"A-1" -> "0110010",
"D+A" -> "0000010",
"D-A" -> "0010011",
"A-D" -> "0000111",
"D&A" -> "0000000",
"D|A" -> "0010101"
)
// expand compute truth table with 'a' bit to use M instead of A register
val ComputeTruthTable = computeTruthTable ++ (
computeTruthTable
.filter(_._1.contains('A'))
.map { case (op, bin) => (op.replace('A', 'M'), "1" + bin.tail) }
)
/* Compute bit truth table mapping jump instruction to HACK Machine Language
*
* Maps jump instruction to binary bits in the format: j1 j2 j3
*/
val JumpTruthTable = Map(
"" -> "000",
"JGT" -> "001",
"JEQ" -> "010",
"JGE" -> "011",
"JLT" -> "100",
"JNE" -> "101",
"JLE" -> "110",
"JMP" -> "111"
)
}
/** Represents a Label Declaration virtual HACK instruction in form (LABEL)
*
* Labels the real HACK instruction with LABEL. LABEL must be a valid symbol
* that does not collide with any of the builtin symbols
*
* @throws IllegalArgumentException if label given is not a valid symbol
* @throws NameAlreadyBoundException if label given collides with builtin symbol
*/
case class LabelDeclaration(val label: String) extends Instruction {
// check that label is valid symbol
if (!SymbolPattern.matches(label)) {
throw new IllegalArgumentException(
s"Cannot declare label with invalid symbol: $label"
)
}
// check that label dofest not collide with builtin symbols
if (BuiltinSymbols.keySet.contains(label)) {
val builtinNames = BuiltinSymbols.keySet.mkString(", ")
throw new NameAlreadyBoundException(
s"Declared label collides with builtin symbol: $label" +
s"Builtin symbols cannot be used as label names: $builtinNames"
)
}
override def isVirtual: Boolean = true
override def toString = s"($label)"
// Virtua instruction: no binary representation
override def toBinary(symTable: Symbols.SymbolTable): String = ""
}
|
using System;
using FantasyCritic.Lib.Domain;
using NodaTime;
namespace FantasyCritic.Web.Models.Responses
{
public class QueuedGameViewModel
{
public QueuedGameViewModel(QueuedGame queuedGame, IClock clock)
{
MasterGame = new MasterGameViewModel(queuedGame.MasterGame, clock);
Rank = queuedGame.Rank;
}
public MasterGameViewModel MasterGame { get; }
public int Rank { get; }
}
}
|
# cache2k 1.3.2.Alpha
This is a preview release for evaluation purposes and should not be used in production.
## New and Noteworthy
- Synchronous execution of expiry listener
## Possible Breakages
`Cache2kBuilder.addListener` will execute an `EntryExpiredLister` synchronously. In version
1.2 an expiry listener was always executed synchronously. This is an potentially incompatible
change, in case expiry listeners are uses. Review the existing client code and
make sure that addAsyncListeners is used for an `EntryExpiredLister`.
## API Changes
None
## Fixes and Improvements
- fix missing expiry listener call after a created listener call, in case expiry during the insert
- `expiry`, `expireAfterWrite`, `refresAhead`: Fix race condition of a `Cache.put` and the
termination of the probation period after a refresh. |
/** Abstract, high-level layouts. */
import { Component, h } from 'preact';
import { Link } from './primitives';
/** A helper base for components with semantic children. */
class PickyParentComponent extends Component {
/** Return the child of the given type. */
_getChild(cType, optional=false) {
let existing = this.props.children.filter(c => c && c.nodeName == cType);
if (optional && existing.length == 0) return null;
if (existing.length != 1) throw new Error('Missing required child');
return existing[0].children;
}
}
class PageErrorLayout extends Component {
render({ title, children }) { return (
<div id="error-page" class="al-c ts">
<h1 class="pad-vb">{ title }</h1>
<div class="hpad-v">{ children }</div>
<div class="hpad-vt">
<Link label="Back to site" href="/"/>
</div>
</div>
); }
}
// Exports.
export { PageErrorLayout }; |
#!/usr/bin/env bash
DOCKER_PORT="8082"
DOCKER_HOST="$(ip route | awk '/default/ { print $3 }')"
export TZ="${TZ:-America/New_York}"
export HOSTNAME="${HOSTNAME:-casjaysdev-ympd}"
[ -n "${TZ}" ] && echo "${TZ}" >/etc/timezone
[ -n "${HOSTNAME}" ] && echo "${HOSTNAME}" >/etc/hostname
[ -n "${HOSTNAME}" ] && echo "127.0.0.1 $HOSTNAME localhost" >/etc/hosts
[ -f "/usr/share/zoneinfo/${TZ}" ] && ln -sf "/usr/share/zoneinfo/${TZ}" "/etc/localtime"
[ -d "/config/mympd" ] || mkdir -p "/config/mympd"
if [ ! -f "/config/mympd/.env" ]; then
cat <<EOF >"/config/mympd/.env"
# See https://jcorporation.github.io/myMPD/configuration/ for more information
export MPD_HOST=$DOCKER_HOST
export MPD_PORT=6600
export MYMPD_HTTP_HOST="${MYMPD_HTTP_HOST:-0.0.0.0}"
export MYMPD_HTTP_PORT="${MYMPD_HTTP_PORT:-$DOCKER_PORT}"
export MYMPD_LOGLEVEL="${MYMPD_LOGLEVEL:-5}"
export MYMPD_SSL="${MYMPD_SSL:-false}"
export MYMPD_SSL_PORT="${MYMPD_SSL_PORT:-$DOCKER_PORT}"
export MYMPD_SSL_KEY="${MYMPD_SSL_KEY:-/config/certs/mympd.key}"
export MYMPD_SSL_CERT="${MYMPD_SSL_CERT:-/config/certs/mympd.crt}"
#export MYMPD_ACL="${MYMPD_ACL:-}"
#export MYMPD_SSL_SAN="${MYMPD_SSL_SAN:-}"
#export MYMPD_LUALIBS="${MYMPD_LUALIBS:-}"
#export MYMPD_SCRIPTACL="${MYMPD_SCRIPTACL:-}"
#export MYMPD_CUSTOM_CERT="${MYMPD_CUSTOM_CERT:-}"
EOF
fi
[ -f "/config/mympd/.env" ] && . "/config/mympd/.env"
[ -f "/config/mympd/ssl" ] || printf '%s' "$MYMPD_SSL" >"/config/mympd/ssl"
[ -f "/config/mympd/http_host" ] || printf '%s' "$MYMPD_HTTP_HOST" >"/config/mympd/http_host"
[ -f "/config/mympd/http_port" ] || printf '%s' "$MYMPD_HTTP_PORT" >"/config/mympd/http_port"
[ -f "/config/pulse-client.conf" ] && cp -Rf "/config/pulse-client.conf" "/etc/pulse/client.conf" ||
cp -Rf "/etc/pulse/client.conf" "/config/pulse-client.conf"
[ -f "/config/mpd.conf" ] && cp -Rf "/config/mpd.conf" "/etc/mpd.conf" ||
cp -Rf "/etc/mpd.conf" "/config/mpd.conf"
[ -d "/config/mympd" ] && cp -Rf "/config/mympd/." "/var/lib/mympd/config/" ||
cp -Rf "/var/lib/mympd/config/." "/config/mympd/"
export MYMPD_USER="--user ${MYMPD_USER:-mympd}"
export MYMPD_DIR="--workdir ${MYMPD_DIR:-/var/lib/mympd}"
export MYMPD_CACHE="--cache ${MYMPD_CACHE:-/var/cache/mympd}"
case "$1" in
healthcheck)
shift 1
if curl -q -LSs --fail "localhost:$DOCKER_PORT"; then
echo '{"status": "ok" }'
exit 0
else
echo '{"status": "fail" }'
exit 1
fi
;;
bash | sh | shell)
shift 1
exec bash -l "$@"
;;
*)
echo "Setting ympd options to: ${CMDOPTS:-none}"
if [[ $# = 0 ]]; then
echo "listening on http://$DOCKER_HOST:$DOCKER_PORT"
pacat -vvvv /dev/urandom
mpd --no-daemon /etc/mpd.conf
mympd $MYMPD_USER $MYMPD_DIR $MYMPD_CACHE $CMDOPTS
else
CMDOPTS="$*"
mympd $MYMPD_USER $MYMPD_DIR $MYMPD_CACHE $CMDOPTS
pacat -vvvv /dev/urandom
mpd --no-daemon /etc/mpd.conf
fi
;;
esac
|
class DurationModel {
String distanceDesc;
String durationDesc;
int distance;
int duration;
DurationModel(
this.distanceDesc, this.durationDesc, this.distance, this.duration);
static List<DurationModel> fromJson(Map<String, dynamic> json) {
print("parsing data");
List<DurationModel> rs = List();
var results = json['rows'] as List;
for (var item in results) {
print(item['elements'][0]['distance']['text']);
var p = DurationModel(
item['elements'][0]['distance']['text'],
item['elements'][0]['duration']['text'],
item['elements'][0]['distance']['value'],
item['elements'][0]['duration']['value'],
);
rs.add(p);
}
return rs;
}
}
|
#!/usr/bin/env bash
rm bower_components.tar.gz >&/dev/null
tar -czvf bower_components.tar.gz ./bower_components |
//
// TileModel.cpp
// CGFLib-1
//
// Created by Josรฉ Ricardo de Sousa Coutinho on 28/11/13.
// Copyright (c) 2013 me. All rights reserved.
//
#include "TileModel.h"
bool TileModel::initialized = false;
Appearance* TileModel::blank = NULL;
Appearance* TileModel::selected = NULL;
Appearance* TileModel::possible = NULL;
TileModel::TileModel()
{
if (!initialized)
{
GLfloat a[4] = {0,0,0,1};
GLfloat b[4] = {0,1,0,1};
GLfloat c[4] = {1,1,0,1};
blank = new Appearance(a);
selected = new Appearance(b);
possible = new Appearance(c);
initialized = true;
GLfloat xy0[2] = {0,0};
GLfloat xy[2] = {TILE_SIZE,TILE_SIZE};
model = new Rectangle(xy0,xy);
app = blank;
}
}
void TileModel::draw(GLint color)
{
glPushMatrix();
switch (color)
{
case 0:
app = blank;
break;
case 1:
app = selected;
break;
case 2:
app = possible;
break;
default:
break;
}
app->apply();
glTranslated(0, 0, TILE_SIZE);
glRotated(-90, 1, 0, 0);
model->draw();
glPopMatrix();
} |
"""
Compose to Image Reparameterizations
apply_gam_to_gam(gamnew::Array, gam::Array)
:param gamnew: 3-D Array describing new gamma
:param gam:: 3-D Array describing current gamma
"""
function apply_gam_to_gam(gamnew::Array, gam::Array)
# gam \circ gam0
m, n, D = size(gam);
md = 8;
mt = md*m;
nt = md*n;
U = LinRange(0,1,m);
V = LinRange(0,1,n);
Ut = LinRange(0,1,mt);
Vt = LinRange(0,1,nt);
gam_tmp = zeros(mt, nt, D);
gam_new_tmp = zeros(mt, nt, D);
for i = 1:D
spl = Spline2D(U,V,gam[:,:,i],kx=1,ky=1);
gam_tmp[:,:,i] = evalgrid(spl,Ut,Vt);
spl = Spline2D(U,V,gamnew[:,:,i],kx=1,ky=1);
gam_new_tmp[:,:,i] = evalgrid(spl,Ut,Vt);
end
gam_cum_tmp = zeros(mt,nt,D);
for i = 1:D
spl = Spline2D(Ut,Vt,gam_new_tmp[:,:,i],kx=1,ky=1);
for j = 1:mt
gam_cum_tmp[j,:,i] = spl(vec(gam_tmp[j,:,2]), vec(gam_tmp[j,:,1]));
end
end
gam_cum = zeros(m,n,D);
for i = 1:D
spl = Spline2D(Ut,Vt,gam_cum_tmp[:,:,i],kx=1,ky=1);
gam_cum[:,:,i] = evalgrid(spl,U,V);
end
return gam_cum
end
"""
Warp img by gam
apply_gam_to_imag(img::Array, gam::Array)
:param img: 2-D or 3-D Array
:param gam: 3-D Array
"""
function apply_gam_to_imag(img::Array, gam::Array)
if ndims(img) == 3
m,n,d = size(img);
img_new = zeros(m,n,d);
elseif ndims(img) == 2
m,n = size(img);
d = 1;
img_new = zeros(m,n);
end
U = LinRange(0,1,m);
V = LinRange(0,1,n);
if d == 1
spl = Spline2D(U,V,img);
for j = 1:m
img_new[j,:] = spl(vec(gam[j,:,2]),vec(gam[j,:,1]));
end
else
for i = 1:d
spl = Spline2D(U,V,img[:,:,i]);
for j = 1:m
img_new[j,:,i] = spl(vec(gam[j,:,2]),vec(gam[j,:,1]));
end
end
end
return img_new
end
"""
Compose Image Reparameterization with Identity
apply_gam_gamid(gamid::Array,gaminc::Array)
:param gamid: 3-D Array
:param gaminc: 3-D Array
"""
function apply_gam_gamid(gamid::Array,gaminc::Array)
m,n,d = size(gamid);
U = LinRange(0,1,m);
V = LinRange(0,1,n);
gam_cum = zeros(m,n,d);
for j = 1:d
spl = Spline2D(U,V,gamid[:,:,j]);
for i = 1:m
gam_cum[i,:,j] = spl(vec(gaminc[i,:,2]),vec(gaminc[i,:,1]));
end
end
return gam_cum
end
"""
Find 2-D gradient
compgrad2D(f::Array)
:param f: Array
:return dfdu: Array
:return dfdv: Array
"""
function compgrad2D(f::Array)
dims = ndims(f);
if dims < 3
n,t = size(f);
d = 1;
dfdu = zeros(n,t);
dfdv = zeros(n,t);
else
n,t,d = size(f);
dfdu = zeros(n,t,d);
dfdv = zeros(n,t,d);
end
@cxx findgrad2D(dfdu, dfdv, f, n, t, d)
return dfdu, dfdv
end
"""
Compute Gram Schmidt of basis using c library gradient
gram_schmidt_c(b)
:param b: basis
"""
function gram_schmidt_c(b)
m,n,tmp,N = size(b);
ds = 1./((m-1)*(n-1));
cnt = 1;
G = zeros(m,n,tmp,N);
G[:,:,:,cnt] = b[:,:,:,cnt];
dvx, dvy = compgrad2D(G[:,:,:,cnt]);
l = vec(dvx)'*vec(dvx)*ds + vec(dvy)'*vec(dvy)*ds;
for i = 2:N
G[:,:,:,i] = b[:,:,:,i];
dv1x, dv1y = compgrad2D(G[:,:,:,i]);
for j = 1:i-1
dv2x, dv2y = compgrad2D(G[:,:,:,j]);
t = vec(dv1x)'*vec(dv2x)*ds + vec(dv1y)'*vec(dv2y)*ds;
G[:,:,:,i] = G[:,:,:,i]-t.*G[:,:,:,j];
end
v = G[:,:,:,i];
l = vec(v)'*vec(v)*ds;
l = l[1];
if l>0
cnt += 1;
G[:,:,:,cnt] = G[:,:,:,cnt]./sqrt(l);
end
end
return G
end
"""
Find jacobian of image F
jacob_imag(F::Array)
:param F: Array
"""
function jacob_imag(F::Array)
m,n,d = size(F);
dfdu, dfdv = compgrad2D(F);
mult_factor = zeros(m,n);
if (d==2)
mult_factor = dfdu[:,:,1]*dfdv[:,:,2] - dfdu[:,:,2]*dfdv[:,:,1];
mult_factor = abs(mult_factor);
elseif (d==3)
mult_factor = (dfdu[:,:,2]*dfdv[:,:,3] - dfdu[:,:,3]*dfdv[:,:,2]).^2
+ (dfdu[:,:,1]*dfdv[:,:,3] - dfdu[:,:,3]*dfdv[:,:,1]).^2
+ (dfdu[:,:,1]*dfdv[:,:,2] - dfdu[:,:,2]*dfdv[:,:,1]).^2;
mult_factor = sqrt(mult_factor);
end
return mult_factor
end
"""
Form identity image warping
makediffeoid(nrow::Integer,ncol::Integer)
:param nrow: number of rows
:param ncol: number of columns
"""
function makediffeoid(nrow::Integer,ncol::Integer)
D = 2;
gamid = zeros(nrow,ncol,D);
U, V = meshgrid(LinRange(0,1,ncol),LinRange(0,1,nrow));
gamid[:,:,1] = U;
gamid[:,:,2] = V;
return gamid
end
"""
Convert image to q-map
imag_to_q(F::Array)
:param F: Array of Image
"""
function imag_to_q(F::Array)
dims = ndims(F);
if dims < 3
error("Data dimension is wrong!")
end
d = size(F,3);
if d < 2
error("Data dimension is wrong!")
end
q = copy(F);
sqrtmultfact = sqrt(jacob_imag(F));
for i = 1:d
q[:,:,i] = sqrtmultfact.*F[:,:,i];
end
return q
end
"""
Compute distance between to q-maps
comp_dist(q1::Array, q2::Array)
:param q1: q-map1
:param q2: q-map2
"""
function comp_dist(q1::Array, q2::Array)
m = size(q1,1);
n = size(q1,2);
ds = 1./((m-1)*(n-1));
tmp = q1-q2;
H = sum(sqrt(vec(tmp).*vec(tmp))*ds);
return H
end
"""
Compute energy of gradient
comp_energy(q1::Array,q2::Array)
:param q1: q-map1
:param q2: q-map2
"""
function comp_energy(q1::Array,q2::Array)
m,n,d = size(q1);
ds = 1./(m-1)/(n-1);
tmp = q1-q2;
H = vec(tmp)'*vec(tmp)*ds;
H = H[1];
return H
end
"""
Update warping function
update_gam(qt, qm, b)
"""
function update_gam(qt, qm, b)
v = qt - qm;
w = findphistar(qt,b);
gamupdate, innp = findupdategam(v,w,b);
return gamupdate
end
"""
Find phi*
findphistar(q,b)
"""
function findphistar(q, b)
n,t,d = size(q);
K = size(b,4);
w = zeros(n,t,d,K);
@cpp ccall((:findphistar, libfdaqmap), Void, (Ptr{Float64}, Ptr{Float64},
Ptr{Float64}, Int32, Int32, Int32, Int32), w, q, b, n, t, d, K);
return w
end
"""
Find updated warping function
findupdategam(v, w, b)
"""
function findupdategam(v, w, b)
m,n,D,K = size(b);
ds = 1./((m-1)*(n-1));
innp = zeros(K);
gamupdate = zeros(m,n,D);
for k = 1:K
vt = w[:,:,:,k];
tmp = vec(v)'*vec(vt)*ds;
innp[k] = tmp[1];
gamupdate = gamupdate + innp[k].*b[:,:,:,k];
end
return gamupdate, innp
end
"""
Check if warping function is a diffeo
check_crossing(F)
"""
function check_crossing(f)
n,t,D = size(f);
if D!=2
error("Third dimension of first argument expected to be 2")
end
diffeo = @cpp ccall((:check_crossing, libfdaqmap), Int32, (Ptr{Float64},
Int32, Int32, Int32), f, n, t, D);
if diffeo == 0
is_diffeo = false;
elseif diffeo == 1
is_diffeo = true;
else
error("check_crossing error")
end
return is_diffeo
end
"""
Compute Basis Tid
formbasisTid(M,m,n;basis_type="tso")
:param M: number of basis elements
:param m:
:param n:
:param basis_type: type of basis (options are "t","s","o","i")
"""
function formbasisTid(M,m,n;basis_type="t")
U, V = meshgrid(LinRange(0,1,n), LinRange(0,1,m));
idx = 1;
if basis_type=="t"
b = zeros(m,n,2,2*M);
for s = 1:M
c = sqrt(2)*pi*s;
sPI2 = 2*pi*s;
b[:,:,1,idx] = zeros(m,n);
b[:,:,2,idx] = (cos(sPI2*V)-1)/c;
b[:,:,1,idx+1] = (cos(sPI2*U)-1)/c;
b[:,:,2,idx+1] = zeros(m,n);
idx += 2;
end
end
if basis_type == "s"
b = zeros(m,n,2,2*M);
for s = 1:M
c = sqrt(2)*pi*s;
sPI2 = 2*pi*2;
b[:,:,1,idx] = zeros(m,n);
b[:,:,2,idx] = sin(sPI2*U)/c;
b[:,:,1,idx+1] = sin(sPI2*U)/c;
b[:,:,2,idx+1] = zero(m,n);
idx += 2;
end
end
if basis_type == "i"
b = zeros(m,n,2,M*M*8);
for s1 = 1:M
s1PI2 = 2*pi*s1;
for s2 = 1:M
s2PI2 = 2*pi*s2;
c = pi * sqrt(s1^2+3*s2^2);
b[:,:,1,idx] = (cos(s1PI2*U)-1).*(cos(s2PI2*V))/c;
b[:,:,2,idx] = zeros(m,n);
b[:,:,1,idx+2] = ((cos(s1PI2*U)-1).*sin(s2PI2*V))/c;
b[:,:,2,idx+2] = zeros(m,n);
c = pi*sqrt(s1^2+s2^2);
b[:,:,1,idx+4] = sin(s1PI2*U).*(cos(s2PI2*V))/c;
b[:,:,2,idx+4] = zeros(m,n);
b[:,:,1,idx+6] = (sin(s1PI2*U).*sin(s2PI2*V))/c;
b[:,:,2,idx+6] = zeros(m,n);
c = pi*sqrt(s1^2+3*s2^2);
b[:,:,1,idx+1] = zeros(m,n);
b[:,:,2,idx+1] = (cos(s1PI2*V)-1).*(cos(s2PI2*U))/c;
b[:,:,1,idx+3] = zeros(m,n);
b[:,:,2,idx+3] = ((cos(s1PI2*V)-1).*sin(s2PI2*U))/c;
c = pi*sqrt(s1^2+s2^2);
b[:,:,1,idx+5] = zeros(m,n);
b[:,:,2,idx+5] = sin(s1PI2*V).*(cos(s2PI2*U))/c;
b[:,:,1,idx+7] = zeros(m,n);
b[:,:,2,idx+7] = (sin(s1PI2*V).*sin(s2PI2*U))/c;
idx += 8;
end
end
end
if basis_type == "o"
b = zeros(m,n,2,M*4);
for s = 1:M
c = sqrt((4*pi^2*s^2+9)/6);
sPI2 = 2*pi*s;
b[:,:,1,idx] = (cos(sPI2*U)-1)*V/c;
b[:,:,2,idx] = zeros(m,n);
b[:,:,2,idx+1] = (cos(sPI2*V)-1).*U/c;
b[:,:,1,idx+1] = zeros(m,n);
b[:,:,1,idx+2] = sin(sPI2*U).*V/c;
b[:,:,2,idx+2] = zeros(m,n);
b[:,:,2,idx+3] = sin(sPI2*V).*U/c;
b[:,:,1,idx+3] = zeros(m,n);
idx += 4;
end
end
return b, U, V
end
"""
Generate basis elements on T_id(\gamma)
run_basis(Ft, M=10, basis_type="t", is_orthon=true)
:param Ft: Image Array
:param M: number of basis elements
:param basis_type: type of basis (option "t", "s", "i", "o")
:param is_orthon: make basis orthonormal
:return b: basis elements
:retrun gamid: identity diffeo
"""
function run_basis(Ft, M=10, basis_type="t", is_orthon=true)
m = size(Ft,1);
n = size(Ft,2);
gamid = makediffeoid(m,n);
b, U, V = formbasisTid(M, m, n, basis_type=basis_type);
if is_orthon
b = gram_schmidt_c(b);
end
return b, gamid
end
|
require 'juke/api'
World(Juke::API)
When /^(?:|I )get ([^\s]+)$/ do |url|
get(url)
end
When /^(?:|I )post ([^\s]+)$/ do |url|
post(url)
end
When /^(?:|I )put ([^\s]+)$/ do |url|
put(url)
end
When /^(?:|I )delete ([^\s]+)$/ do |url|
delete(url)
end
When /^(?:|I )get (.+) with:$/ do |url,name_value_pairs|
get(url, name_value_pairs.rows_hash)
end
When /^(?:|I )post (.+) with:$/ do |url,name_value_pairs|
post(url, name_value_pairs.rows_hash)
end
When /^(?:|I )put (.+) with:$/ do |url,name_value_pairs|
put(url, name_value_pairs.rows_hash)
end
When /^(?:|I )delete (.+) with:$/ do |url,name_value_pairs|
delete(url, name_value_pairs.rows_hash)
end
Then /^(?:|response )should equal (.+)$/ do |object|
response_body.should == eval(object)
end
Then /^(?:|response )should have (.+)$/ do |obj|
response_body.should include obj
end
Then /^(?:|response )should include hash:$/ do |name_value_pairs|
name_value_pairs.rows_hash.each do |key, value|
response_body.should have_key(key)
response_body[key].should == value
end
end
Then /^status should be (\d{3})$/ do |status|
response_status.should == status.to_i
end
|
---
title: Grid ็ฝๆ ผ
---
# ็ฝๆ ผ
### ๅบ็ก็จๆณ
<br/>
<ClientOnly>
<grid-demo/>
</ClientOnly>
```vue
<a-row class="demo-row">
<a-col span="8">
<div class="demo-col"></div>
</a-col>
<a-col span="8">
<div class="demo-col"></div>
</a-col>
<a-col span="8">
<div class="demo-col"></div>
</a-col>
</a-row>
<a-row class="demo-row">
<a-col span="6">
<div class="demo-col"></div>
</a-col>
<a-col span="6">
<div class="demo-col"></div>
</a-col>
<a-col span="6">
<div class="demo-col"></div>
</a-col>
<a-col span="6">
<div class="demo-col"></div>
</a-col>
</a-row>
<a-row class="demo-row">
<a-col span="4">
<div class="demo-col"></div>
</a-col>
<a-col span="4">
<div class="demo-col"></div>
</a-col>
<a-col span="4">
<div class="demo-col"></div>
</a-col>
<a-col span="4">
<div class="demo-col"></div>
</a-col>
<a-col span="4">
<div class="demo-col"></div>
</a-col>
<a-col span="4">
<div class="demo-col"></div>
</a-col>
</a-row>
<a-row class="demo-row">
<a-col span="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2">
<div class="demo-col"></div>
</a-col>
</a-row>
<style lang="scss">
.demo-row {
margin-bottom: 5px;
.demo-col {
height: 50px;
border: 1px solid #000;
background: #99a9bf;
}
}
</style>
```
### ้ด้็ฝๆ ผ
<br/>
<ClientOnly>
<grid-demo2/>
</ClientOnly>
```vue
<a-row class="demo-row" gutter="5">
<a-col span="8">
<div class="demo-col"></div>
</a-col>
<a-col span="8">
<div class="demo-col"></div>
</a-col>
<a-col span="8">
<div class="demo-col"></div>
</a-col>
</a-row>
<a-row class="demo-row" gutter="3">
<a-col span="6">
<div class="demo-col"></div>
</a-col>
<a-col span="6">
<div class="demo-col"></div>
</a-col>
<a-col span="6">
<div class="demo-col"></div>
</a-col>
<a-col span="6">
<div class="demo-col"></div>
</a-col>
</a-row>
<style lang="scss">
* {
box-sizing: border-box;
}
.demo-row {
margin-bottom: 5px;
.demo-col {
height: 50px;
background: #99a9bf;
}
}
</style>
```
### ็ฉบ้็ฝๆ ผ
<br/>
<ClientOnly>
<grid-demo3/>
</ClientOnly>
```vue
<a-row class="demo-row">
<a-col span="8">
<div class="demo-col"></div>
</a-col>
<a-col span="8" offset="8">
<div class="demo-col"></div>
</a-col>
</a-row>
<a-row class="demo-row">
<a-col span="6" offset="6">
<div class="demo-col"></div>
</a-col>
<a-col span="6" offset="6">
<div class="demo-col"></div>
</a-col>
</a-row>
<a-row class="demo-row">
<a-col span="4">
<div class="demo-col"></div>
</a-col>
<a-col span="4" offset="4">
<div class="demo-col"></div>
</a-col>
<a-col span="4" offset="8">
<div class="demo-col"></div>
</a-col>
</a-row>
<a-row class="demo-row">
<a-col span="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2" offset="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2" offset="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2" offset="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2">
<div class="demo-col"></div>
</a-col>
<a-col span="2" offset="2">
<div class="demo-col"></div>
</a-col>
</a-row>
<style lang="scss">
* {
box-sizing: border-box;
}
.demo-row {
margin-bottom: 5px;
.demo-col {
height: 50px;
background: #99a9bf;
}
}
</style>
```
### Row Attributes
|ๅๆฐ|่ฏดๆ|็ฑปๅ|ๅฏ้ๅผ|้ป่ฎคๅผ|
|----|----|----|----|----|
|gutter|็ฉบ้|string / number|-|-|
|align|ๆๅญๅฏน้ฝ็ถๆ|string|left / right / center|-|
### Col Attributes
|ๅๆฐ|่ฏดๆ|็ฑปๅ|ๅฏ้ๅผ|้ป่ฎคๅผ|
|----|----|----|----|----|
|span|ๅ ็จไปฝ้ข๏ผ้ป่ฎค1row = 24span|string / number|-|-|
|offset|ๅ็งป้|string / number|-|-| |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from six.moves import range
from pants.build_graph.build_file_aliases import BuildFileAliases
from pants.base.exceptions import TaskError
from pants.util.contextutil import temporary_dir
from pants.util.dirutil import touch
from pants_test.tasks.task_test_base import TaskTestBase
from squarepants.plugins.compile_prep_command.targets.compile_prep_command import CompilePrepCommand
from squarepants.plugins.compile_prep_command.tasks.run_compile_prep_command import RunCompilePrepCommand
class RunCompilePrepTest(TaskTestBase):
@classmethod
def task_type(cls):
return RunCompilePrepCommand
@property
def alias_groups(self):
return BuildFileAliases(
targets={
'compile_prep_command': CompilePrepCommand,
},
)
def test_prep_order(self):
with temporary_dir() as workdir:
with temporary_dir() as tmp:
files = [os.path.join(tmp, 'file%s' % i) for i in range(3)]
touch(files[0])
a = self.make_target('a', dependencies=[], target_type=CompilePrepCommand,
executable='mv', args=[files[0], files[1]])
b = self.make_target('b', dependencies=[a], target_type=CompilePrepCommand,
executable='mv', args=[files[1], files[2]])
context = self.context(target_roots=[b])
task = self.create_task(context=context, workdir=workdir)
task.execute()
self.assertTrue(os.path.exists(files[2]))
def test_prep_environ(self):
with temporary_dir() as workdir:
a = self.make_target('a', dependencies=[], target_type=CompilePrepCommand,
executable='echo',
args=['-n', 'test_prep_env_var=fleem'],
environ=True)
context = self.context(target_roots=[a])
task = self.create_task(context=context, workdir=workdir)
task.execute()
self.assertEquals('fleem', os.environ['test_prep_env_var'])
def test_prep_no_command(self):
with self.assertRaises(TaskError):
a = self.make_target('a', dependencies=[], target_type=CompilePrepCommand,
executable='no_such_executable!$^!$&!$#^$#%!%@!', args=[])
context = self.context(target_roots=[a])
task = self.create_task(context=context, workdir='')
task.execute()
def test_prep_command_fails(self):
with self.assertRaises(TaskError):
a = self.make_target('a', dependencies=[], target_type=CompilePrepCommand,
executable='mv', args=['/non/existent/file/name',
'/bogus/destination/place'])
context = self.context(target_roots=[a])
task = self.create_task(context=context, workdir='')
task.execute()
|
; === utils.asm
; Utility subroutines from SRAM2.
; Mostly functions related to text processing and user input.
; Given a music pointer array in HL, play the music there.
_PlayMusicFromRAM:
ld bc, $0008
ld de, $C006
call CopyData
ld a, $00
ld bc, $0004
ld hl, $C016
call FillMemory
ld a, $01
ld bc, $0004
ld hl, $C0B6
call FillMemory
ld a, $e0
ld bc, $0004
ld hl, $C026
jp FillMemory
; Wait until the A button is fully pressed and fully released.
_WaitAPress:
push af
.waitA_release
ldh a, [$f5]
bit 0, a
jr nz, .waitA_release
.waitA_press
ldh a, [$f5]
bit 0, a
jr z, .waitA_press
pop af
ret
; Set all sprite animation counters to 00.
SpriteClearAnimCounters:
ld hl, $c107
ld bc, $0010 - 1
.loop
xor a
ldi [hl], a
ld [hl], a
add hl, bc
ld a, l
cp $f7
jr nz, .loop
ret
; UpdateSprites, but it preserves all of the registers.
; It also keeps all sprite animation counters at 00.
UpdateSpritesSafeguarded:
push af
push bc
push de
push hl
call SpriteClearAnimCounters
call UpdateSprites
call SpriteClearAnimCounters
pop hl
pop de
pop bc
pop af
ret
; Utility sound routines, used in the user input menus.
PlayOptionChangeSound:
push af
ld a, $13
call PlaySound
pop af
ret
PlayOptionSelectSound:
push af
ld a, $90
call PlaySound
pop af
ret
; Wait until any button is pressed.
WaitNonzeroInput:
ldh a, [$f5]
and a
jr nz, WaitNonzeroInput
.nonzero
ldh a, [$f5]
and a
jr z, .nonzero
ret
; Place vanilla text on the screen, terminated by $50.
; Lines are separated with $4F.
; Data is read from the caller's SRAM bank.
_PutString:
push bc
push hl
ld bc, 20
.printchr
ld a, [de]
push hl
ld h, d
ld l, e
call ReadFromSavedSRAM
pop hl
inc de
cp $50
jr z, .finished
cp $4f
jr z, .nextline
ld [hli], a
jr .printchr
.nextline
pop hl
add hl, bc
push hl
jr .printchr
.finished
pop hl
pop bc
ret
; Same as PutString, but data is read from the current SRAM bank instead,
; as opposed to the parent one.
PutStringSameBank:
ld a, [SavedSRAMBank]
push af
ld a, [CurrentSRAMBank]
ld [SavedSRAMBank], a
call _PutString
pop af
ld [SavedSRAMBank], a
ret
; Functions that aid in creating option choice menus.
include "engine/choice_menu.asm"
; Functions that aid in creating text input menus.
include "engine/input_menu.asm"
; Execute a command from a list of predefined commands.
_PredefCmd:
; Again, clever self modifying code is used to make a dynamic
; subroutine call while preserving all registers
push af
push hl
push bc
ld hl, PredefCmdPointers
add a
ld c, a
ld b, 0
add hl, bc
ld a, [hli]
ld h, [hl]
ld [PredefCmdCall+1], a
ld a, h
ld [PredefCmdCall+2], a
pop bc
pop hl
pop af
PredefCmdCall:
jp $1234
PredefCmdPointers:
dw PutStringSameBank
dw CharsetEnhancedToStandard
dw CharsetStandardToEnhanced
dw ReplaceTextPointer
dw StringLen
dw HandleCrackMe
dw ShowMapOfGlitchland
dw PreserveMusicRegisters
dw RestoreMusicRegisters
; Convert the 'enhanced charset' (used by this game's text engine)
; to the 'standard charset' (used by the stock game).
CharsetEnhancedToStandard:
ld de, CharsetEnhanced
ld bc, CharsetStandard
ld a, $f6
ld [ConvertCharsetsTerminator+1], a
ld a, $50
ld [ConvertCharsetsFinish+1], a
jr ConvertCharsetsInPlace
; Same conversion, but in reverse.
CharsetStandardToEnhanced:
ld de, CharsetStandard
ld bc, CharsetEnhanced
ld a, $50
ld [ConvertCharsetsTerminator+1], a
ld a, $f6
ld [ConvertCharsetsFinish+1], a
; Fall through to ConvertCharsetsInPlace
; Perform the actual charset conversion.
; Conversion is done in place.
; de -> source charset
; bc -> target charset
; hl -> converted string
ConvertCharsetsInPlace:
ld a, [hl]
ConvertCharsetsTerminator:
cp $50
jr z, ConvertCharsetsFinish
push hl
push bc
push de
ld h, d
ld l, e
call CharsetSearch
ld a, b
pop de
pop bc
pop hl
push hl
push bc
ld h, b
ld l, c
ld b, 0
ld c, a
add hl, bc
ld a, [hl]
pop bc
pop hl
ld [hli], a
jr ConvertCharsetsInPlace
ConvertCharsetsFinish:
ld [hl], $50
ret
; Find the value A in an $FF terminated array and return the index in C.
CharsetSearch:
ld c, a
ld b, -1
.loop
inc b
ld a, [hli]
cp c
jr nz, .loop
.finish
ret
CharsetEnhanced:
db $01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12
db $13,$14,$15,$16,$17,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24
db $25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f,$30,$31,$32,$33,$34,$35,$36
db $37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47,$48
db $49,$4a,$4b,$4c
CharsetStandard:
db $80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f,$90,$91
db $92,$93,$94,$95,$96,$97,$98,$99,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7,$a8,$a9
db $aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$e7,$f4
db $e6,$00,$e3,$e8,$9c,$9a,$9b,$7f,$01,$f0,$e0,$f3,$f6,$f7,$f8,$f9,$fa,$fb
db $fc,$fd,$fe,$ff
; A utility function to make an interactive serial transfer.
; That is, send out a packet while displaying the 'Transmitting' message
; and allow cancelling the transmission with the B Button.
_SerialInteractiveTransfer:
call ShowTransmitMessage
ld c, $20
ld a, $a3
call PlayMusic
ld c, 8
call DelayFrames
.attemptConnect
ldh a, [$f5]
and $02
jr nz, .connectionFailed
xor a
ld [SerialIsInteractive], a
ld hl, StandardSerialBuffer
ld de, StandardSerialBuffer
call SerialTransmitBlock
jr c, .connectionFailed
xor a
ld [SerialIsInteractive], a
ld a, 1
ret
.connectionFailed
ld a, $fe
ld [PreservedMapMusicBank], a
xor a
ld [SerialIsInteractive], a
ret
; Replace the textbox ID in register C with a new pointer in HL.
; Since this is supposed to be called from map scripts, all writes
; are made to the caller's SRAM bank.
ReplaceTextPointer:
push hl
ld hl, $d36b
ld e, [hl]
inc hl
ld d, [hl]
ld h, d
ld l, e
ld a, c
dec a
add a
ld c, a
ld b, 0
add hl, bc
pop de
ld a, e
call WriteToSavedSRAM
inc hl
ld a, d
jp WriteToSavedSRAM
; Given a standard charset string in HL, calculate its length.
; Result is returned in C.
StringLen:
push hl
ld c, 0
.loop
ld a, [hli]
cp $50
jr z, .finish
inc c
jr .loop
.finish
pop hl
ret
; A theoretical function that was supposed to show a map of Glitchland.
; During early development, there was an idea that a full map of the
; world should be viewable in-game, like a Town Map.
; However, the approaching deadline forced me to scrap the idea.
; And all that remained of the idea... is a single return instruction.
ShowMapOfGlitchland:
ret
; Save the sound RAM ($C000-$C100) to $CAD0. Used to preserve music
; between maps.
PreserveMusicRegisters:
push hl
push de
push bc
; We want to make sure the sound data doesn't update while we're
; copying it. So interrupts are disabled during the operation.
di
ld hl, $c000
ld de, $cad0
ld bc, 256
call CopyData
ei
pop bc
pop de
pop hl
ret
; Restore the sound RAM, as saved by PreserveMusicRegisters.
RestoreMusicRegisters:
push hl
push de
push bc
di
ld hl, $cad0
ld de, $c000
ld bc, 256
call CopyData
ei
pop bc
pop de
pop hl
ret
|
# ๆๆๅ่กจ
## MD่ฏญๆณ
[MD่ฏญๆณ](/essay/MD่ฏญๆณ.md)
## ๆๅ
React็ปไปถๅบๅนถไธไผ npm
[ๆๅ
React็ปไปถๅบๅนถไธไผ npm](/essay/ๆๅ
React็ปไปถๅบๅนถไธไผ npm.md) |
#--
# Ruby Whois
#
# An intelligent pure Ruby WHOIS client and parser.
#
# Copyright (c) 2009-2011 Simone Carletti <[email protected]>
#++
require 'whois/record/parser/base_afilias'
module Whois
class Record
class Parser
# Parser for the whois.publicinternetregistry.net server.
class WhoisPublicinterestregistryNet < BaseAfilias
# Checks whether the response has been throttled.
#
# @return [Boolean]
#
# @example
# WHOIS LIMIT EXCEEDED - SEE WWW.PIR.ORG/WHOIS FOR DETAILS
#
def response_throttled?
!!node("response:throttled")
end
private
def decompose_registrar(value)
if value =~ /(.+?) \((.+?)\)/
[$2, $1]
end
end
end
end
end
end |
// Copyright (c) 2015, the Dartino project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE.md file.
library dartino_compiler.verbs.options;
import '../diagnostic.dart' show
DiagnosticKind,
throwFatalError;
const bool isBatchMode = const bool.fromEnvironment("dartino-batch-mode");
typedef R ArgumentParser<R>(String argument);
enum OptionKind {
help,
verbose,
version,
define,
analyzeOnly,
fatalIncrementalFailures,
terminateDebugger,
debuggingMode,
noWait,
/// Not an option
none,
}
const List<Option> supportedOptions = const <Option>[
const Option(OptionKind.help, const ['h', '?'], const ['help', 'usage']),
const Option(OptionKind.verbose, 'v', 'verbose'),
const Option(OptionKind.version, null, 'version'),
const Option(OptionKind.analyzeOnly, null, 'analyze-only'),
const Option(
OptionKind.fatalIncrementalFailures, null, 'fatal-incremental-failures'),
const Option(
OptionKind.terminateDebugger, null, 'terminate-debugger'),
const Option(
OptionKind.debuggingMode, null, 'debugging-mode'),
const Option(
OptionKind.noWait, null, 'no-wait'),
];
final Map<String, Option> shortOptions = computeShortOptions();
final Map<String, Option> longOptions = computeLongOptions();
const String StringOrList =
"Type of annotation object is either String or List<String>";
class Option {
final OptionKind kind;
@StringOrList final shortName;
@StringOrList final longName;
final ArgumentParser<dynamic> parseArgument;
const Option(
this.kind,
this.shortName,
this.longName,
{this.parseArgument});
String toString() {
return "Option($kind, $shortName, $longName";
}
}
List<String> parseCommaSeparatedList(String argument) {
argument = argument.trim();
if (argument.isEmpty) return <String>[];
return argument.split(',').map((String e) => e.trim()).toList();
}
Map<String, Option> computeShortOptions() {
Map<String, Option> result = <String, Option>{};
for (Option option in supportedOptions) {
var shortName = option.shortName;
if (shortName == null) {
continue;
} else if (shortName is String) {
result[shortName] = option;
} else {
List<String> shortNames = shortName;
for (String name in shortNames) {
result[name] = option;
}
}
}
return result;
}
Map<String, Option> computeLongOptions() {
Map<String, Option> result = <String, Option>{};
for (Option option in supportedOptions) {
var longName = option.longName;
if (longName == null) {
continue;
} else if (longName is String) {
result[longName] = option;
} else {
List<String> longNames = longName;
for (String name in longNames) {
result[name] = option;
}
}
}
return result;
}
class Options {
final bool help;
final bool verbose;
final bool version;
final Map<String, String> defines;
final List<String> nonOptionArguments;
final bool analyzeOnly;
final bool fatalIncrementalFailures;
final bool terminateDebugger;
final bool debuggingMode;
final bool noWait;
Options(
this.help,
this.verbose,
this.version,
this.defines,
this.nonOptionArguments,
this.analyzeOnly,
this.fatalIncrementalFailures,
this.terminateDebugger,
this.debuggingMode,
this.noWait);
/// Parse [options] which is a list of command-line arguments, such as those
/// passed to `main`.
static Options parse(Iterable<String> options) {
bool help = false;
bool verbose = false;
bool version = false;
Map<String, String> defines = <String, String>{};
List<String> nonOptionArguments = <String>[];
bool analyzeOnly = false;
bool fatalIncrementalFailures = false;
bool terminateDebugger = isBatchMode;
bool debuggingMode = false;
bool noWait = false;
Iterator<String> iterator = options.iterator;
while (iterator.moveNext()) {
String optionString = iterator.current;
OptionKind kind;
var parsedArgument;
if (optionString.startsWith("-D")) {
// Define.
kind = OptionKind.define;
parsedArgument = optionString.split('=');
if (parsedArgument.length > 2) {
throwFatalError(DiagnosticKind.illegalDefine,
userInput: optionString,
additionalUserInput:
parsedArgument.sublist(1).join('='));
} else if (parsedArgument.length == 1) {
// If the user does not provide a value, we use `null`.
parsedArgument.add(null);
}
} else if (optionString.startsWith("-")) {
String name;
Option option;
String argument;
if (optionString.startsWith("--")) {
// Long option.
int equalIndex = optionString.indexOf("=", 2);
if (equalIndex != -1) {
argument = optionString.substring(equalIndex + 1);
name = optionString.substring(2, equalIndex);
} else {
name = optionString.substring(2);
}
option = longOptions[name];
} else {
// Short option.
name = optionString.substring(1);
option = shortOptions[name];
}
if (option == null) {
throwFatalError(
DiagnosticKind.unknownOption, userInput: optionString);
} else if (argument != null) {
// TODO(ahe): Pass what should be removed as additionalUserInput, for
// example, if saying `--help=fisk`, [userInput] should be `help`,
// and [additionalUserInput] should be `=fisk`.
throwFatalError(DiagnosticKind.unexpectedArgument, userInput: name);
}
kind = option.kind;
} else {
nonOptionArguments.add(optionString);
kind = OptionKind.none;
}
switch (kind) {
case OptionKind.help:
help = true;
break;
case OptionKind.verbose:
verbose = true;
break;
case OptionKind.version:
version = true;
break;
case OptionKind.define:
defines[parsedArgument[0]] = parsedArgument[1];
break;
case OptionKind.analyzeOnly:
analyzeOnly = true;
break;
case OptionKind.fatalIncrementalFailures:
fatalIncrementalFailures = true;
break;
case OptionKind.terminateDebugger:
terminateDebugger = true;
break;
case OptionKind.debuggingMode:
debuggingMode = true;
break;
case OptionKind.noWait:
noWait = true;
break;
case OptionKind.none:
break;
}
}
return new Options(
help, verbose, version, defines,
nonOptionArguments, analyzeOnly, fatalIncrementalFailures,
terminateDebugger, debuggingMode, noWait);
}
}
|
{-# OPTIONS_GHC -Wall #-}
module CycleRecentWS where
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
import XMonad.Actions.CycleRecentWS (unView)
import XMonad.StackSet (view, greedyView, mapLayout)
import Instances
import Utils (tags)
spec :: Spec
spec = do
prop "prop_unView" prop_unView
prop_unView :: T -> Property
prop_unView ss = conjoin
[ counterexample desc (unView ss (state (v t ss)) === state ss)
| t <- tags ss
, (desc, v) <- [("view " <> show t, view), ("greedyView " <> show t, greedyView)] ]
where
state = mapLayout succ
|
require 'spec_helper'
RSpec.describe Examples::ArrayDefinitions, type: :integration do
it_behaves_like 'a builder' do
let(:expected_json) do
{
type: :array,
definitions: {
positiveInt: {
type: :integer,
minimum: 0,
exclusiveMinimum: true
}
},
items: {
:$ref => '#/definitions/positiveInt'
}
}
end
end
end
|
#ifndef TSESSION_H
#define TSESSION_H
#include "TObject.h"
class TBuffer;
class TInterface;
struct TSessionData;
class TSession : public TObject {
T_OBJECT(TSession)
public:
TSession();
~TSession();
protected:
TSession(TSessionData* data);
public:
TBuffer* in();
TBuffer* out();
public:
template<typename T>
T* create() {
T* res = new T(this);
registerObject(res);
return res;
}
protected:
void registerObject(TInterface* obj);
};
#endif // TSESSION_H
|
import { HORIZONTAL_GRIP, VERTICAL_GRIP } from './base64';
import styleListeners from './styleListeners';
export default (
leftPane,
topPane,
rightPane,
bottomPane,
verticalDivider,
horizontalDivider
) => {
const leftThreshold = 30, rightThreshold = 70;
verticalDivider.sdrag(function(el, pageX, startX, pageY, startY, resize) {
resize.skipX = true;
if (pageX < window.innerWidth * leftThreshold / 100) {
pageX = window.innerWidth * leftThreshold / 100;
resize.pageX = pageX;
}
if (pageX > window.innerWidth * rightThreshold / 100) {
pageX = window.innerWidth * rightThreshold / 100;
resize.pageX = pageX;
}
let cur = pageX / window.innerWidth * 100;
if (cur < 0) {
cur = 0;
}
if (cur > window.innerWidth) {
cur = window.innerWidth;
}
const right = 100 - cur - .5;
leftPane.style.width = cur + "%";
rightPane.style.width = right + "%";
}, null, "horizontal");
horizontalDivider.sdrag(function(el, pageX, startX, pageY, startY, resize) {
resize.skipY = true;
if (pageY < window.innerHeight * leftThreshold / 100) {
pageY = window.innerHeight * leftThreshold / 100;
resize.pageY = pageY;
}
if (pageY > window.innerHeight * rightThreshold / 100) {
pageY = window.innerHeight * rightThreshold / 100;
resize.pageY = pageY;
}
let cur = pageY / window.innerHeight * 100;
if (cur < 0) {
cur = 0;
}
if (cur > window.innerHeight) {
cur = window.innerHeight;
}
const bottom = 100 - cur - 1;
topPane.style.height = cur + "%";
bottomPane.style.height = bottom + "%";
}, null, "vertical");
// initialize grip styles:
horizontalDivider.style.backgroundImage = HORIZONTAL_GRIP;
verticalDivider.style.backgroundImage = VERTICAL_GRIP;
styleListeners(horizontalDivider, verticalDivider);
};
|
import NvDropmenu from './main'
import NvDropmenuItem from './item'
NvDropmenu.install = Vue => Vue.component(NvDropmenu.name, NvDropmenu)
NvDropmenuItem.install = Vue => Vue.component(NvDropmenuItem.name, NvDropmenuItem)
export default {
NvDropmenu,
NvDropmenuItem
} |
/**
* Copyright (c) 2021, Veepee
*
* Permission to use, copy, modify, and/or distribute this software for any purpose
* with or without fee is hereby granted, provided that the above copyright notice
* and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
* THIS SOFTWARE.
*/
package com.veepee.vpcore.route.fragment
import com.veepee.vpcore.route.fragment.feature.TestFragmentA
import com.veepee.vpcore.route.fragment.feature.TestFragmentB
import com.veepee.vpcore.route.fragment.feature.TestFragmentNameMapper
import com.veepee.vpcore.route.fragment.route.TestFragmentALink
import com.veepee.vpcore.route.fragment.route.TestFragmentBLink
import com.veepee.vpcore.route.fragment.route.TestFragmentBParameter
import com.veepee.vpcore.route.link.fragment.FragmentLinkRouterImpl
import com.veepee.vpcore.route.link.fragment.FragmentName
import com.veepee.vpcore.route.link.fragment.FragmentNameMapper
import com.veepee.vpcore.route.link.fragment.NoFragmentNameMapperException
import com.veepee.vpcore.route.requireLinkParameter
import org.junit.Assert
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class FragmentLinkRouterTest {
private val mappers: Set<FragmentNameMapper<out FragmentName>> = setOf(TestFragmentNameMapper)
private val testFragmentBParameter = TestFragmentBParameter("id")
@Test
fun `should return fragment for registered FragmentNameMapper`() {
val router = FragmentLinkRouterImpl(mappers)
val fragmentA = router.fragmentFor(TestFragmentALink)
assertEquals(fragmentA::class.java, TestFragmentA::class.java)
val fragmentB = router.fragmentFor(TestFragmentBLink(testFragmentBParameter))
assertEquals(fragmentB::class.java, TestFragmentB::class.java)
}
@Test
fun `should retrieve parameter from Fragment`() {
val router = FragmentLinkRouterImpl(mappers)
val fragment = router.fragmentFor(TestFragmentBLink(testFragmentBParameter))
assertEquals(
fragment.requireLinkParameter<TestFragmentBParameter>(),
testFragmentBParameter
)
}
@Test
fun `should raise an error when the there is no mapper for a given ActivityLink`() {
val router = FragmentLinkRouterImpl(emptySet())
Assert.assertThrows(NoFragmentNameMapperException::class.java) {
router.fragmentFor(TestFragmentALink)
}
}
}
|
2020ๅนด10ๆ03ๆฅ06ๆถๆฐๆฎ
Status: 200
1.ๆ่ฃๆตฉ ไธๆฏๅซๅญๆฏๆญๆๆจไธ็ณ
ๅพฎๅ็ญๅบฆ:449890
2.ๅฝญๆฏๅคซๅฆๆฐๅ ๆฃๆต้ดๆง
ๅพฎๅ็ญๅบฆ:319686
3.้ญ็ขงๅฉท็ๅฅณ
ๅพฎๅ็ญๅบฆ:244995
4.ๅฐๅฝฉๆๆ็ดซไธๆไธๅปๆ
ๅพฎๅ็ญๅบฆ:243870
5.้ปๆ็ง็ๅๆๅ็ไฟกๆฏ
ๅพฎๅ็ญๅบฆ:140442
6.ๆ็ปๅคซๅฆๆฐๅ ๆฃๆตๅ้ดๆง
ๅพฎๅ็ญๅบฆ:131008
7.ๅจๅจๅธฎๆญป่
ๆถๅป็ฎ่
ๅพฎๅ็ญๅบฆ:91257
8.ๅฎๆ้ฃ้ธๅๆ
ๅพฎๅ็ญๅบฆ:91238
9.ๅคฉๆดฅๅฅณๆๅคบๅ
ๅพฎๅ็ญๅบฆ:91208
10.ๆผๅ่ฏทๅฐฑไฝ
ๅพฎๅ็ญๅบฆ:91143
11.ๆๅๆ็ๅฎถไนก็ฅจๆฟ็ ด5ไบฟ
ๅพฎๅ็ญๅบฆ:91132
12.ๅช่นๆด้ฉฌ่ๆธฉๅณฅๅตๅฑ
็ถๆฏB็บง
ๅพฎๅ็ญๅบฆ:91076
13.ๆ7ๆฌ็ซ่ฝฆ้ฉพ็
ง็ๅธๆบ่ขซ็ง็ฎไบ้พไฝไบ
ๅพฎๅ็ญๅบฆ:91028
14.ๅจไธ่ตท็ป่
ๅพฎๅ็ญๅบฆ:90981
15.ๆณฐๅฝๅๆป็ไปไฟก็กฎ่ฏๆๆๆฐๅ
ๅพฎๅ็ญๅบฆ:90942
16.ไธๅปบ่ฎฎ่บบๅบไธ็ฉๆๆบ็ๅๅ
ๅพฎๅ็ญๅบฆ:90899
17.ๅ
จๅฎถๅบๅจไธบๅ ตๅจ่ทฏไธ็ไบบ้้ฃ
ๅพฎๅ็ญๅบฆ:90881
18.ๅพฎไฟกไธ็บฟ้ๅฐๅนดๆจกๅผ
ๅพฎๅ็ญๅบฆ:90807
19.ๅคฉๆดฅๅคงๅญฆ125ๅจๅนดๆ กๅบ
ๅพฎๅ็ญๅบฆ:90768
20.้นฟๆๅธๆ่ฝๅธฎๅดไบฆๅก่ตขไธๆฏ่ต
ๅพฎๅ็ญๅบฆ:90763
21.GAI ้ชๆ็ไบบๆๅพๅค
ๅพฎๅ็ญๅบฆ:90740
22.็พ็ฐๅฝนๅไบบ่ชๆๅขๅคๆไธๆฐๅ ๆๅ
ณ
ๅพฎๅ็ญๅบฆ:75759
23.้ฃ็ฌๅฐๅนด็ๅคฉ็ฉบ
ๅพฎๅ็ญๅบฆ:74912
24.ๅป็็งฐ็นๆๆฎๅคซๅฆ่บซไฝ็ถๅต่ฏๅฅฝ
ๅพฎๅ็ญๅบฆ:70137
25.ๆๅไปฃๆฒๆๅคๅคง
ๅพฎๅ็ญๅบฆ:69955
26.ไปปๆๅธๅบ่ฏ็บง็ฌฌไธ
ๅพฎๅ็ญๅบฆ:69946
27.ๅฝญๆฑ็
ๅญๆ
ๅพฎๅ็ญๅบฆ:69915
28.500ๅๅญฆ็็จ่ดชๅ่ๆๅบไธญๅฝๅฐๅพ
ๅพฎๅ็ญๅบฆ:62942
29.็พ่ก
ๅพฎๅ็ญๅบฆ:62188
30.ไธญ้คๅ
ๅพฎๅ็ญๅบฆ:62055
31.ๅผ ๆฐๆๆตทๆถๅๅฑๆ็พ็ๅคช้ณ
ๅพฎๅ็ญๅบฆ:61926
32.ๅฐ็ฝๆทๆฑฐๅดไบฆๅกๅฝๅฝ
ๅพฎๅ็ญๅบฆ:57688
33.ๆๅคด็ๅฅณ็ๆไปไน็ฆๆผ
ๅพฎๅ็ญๅบฆ:53270
34.่ฅฟ่่พน้ฒๆๅฃซๆๆ็ป็พๆ็ฉบ
ๅพฎๅ็ญๅบฆ:50512
35.็บณๆจ้ๆฏๅบๅๅบๆธธๅฎขไนฐ็ฅจ่ขซไพฎ่พฑ
ๅพฎๅ็ญๅบฆ:48808
36.ๅจ้ๅ้ป่ฒ่พไธๅ
ๆญ
ๅพฎๅ็ญๅบฆ:48784
37.้ ็ฟผ้ญๅๅๅๅ
ณ่ตต็
ๅพฎๅ็ญๅบฆ:48395
38.ๅงๅญ็ๅฝฉ่
ๅพฎๅ็ญๅบฆ:44558
39.ไธญๅฝๆฐ่ฏดๅฑ
ๅพฎๅ็ญๅบฆ:43076
40.ๆ็ป
ๅพฎๅ็ญๅบฆ:40123
41.้ปๆๆๆ้บฆๆถ็ๅๅบ
ๅพฎๅ็ญๅบฆ:40115
42.่ไนฆๆฌฃๆฏๆๅฝคๆๆๆ้งๅบฆ
ๅพฎๅ็ญๅบฆ:40077
43.ไธญๅฝๅฅฝๅฃฐ้ณ
ๅพฎๅ็ญๅบฆ:39761
44.ๅ
ณๅฐๅๆฟๆๆ้จๅซ้ฑ
ๅพฎๅ็ญๅบฆ:38250
45.ๆตทไธ็ๆๆๆฏไปไนๆ่ง
ๅพฎๅ็ญๅบฆ:37058
46.ๅฐๅคงๅคซ
ๅพฎๅ็ญๅบฆ:34581
47.ๅงๅญ็็ฅจๆฟ็ ด6ไบฟ
ๅพฎๅ็ญๅบฆ:34190
48.110ๅฐๅงๅงๆธฉๆๅๅฏผ่ฝป็ๅฅณๅญฉ
ๅพฎๅ็ญๅบฆ:30548
49.ๆฌ็ฐ้ๅบF1
ๅพฎๅ็ญๅบฆ:30249
50.ๆๅป็ฝๅง็็ๅฎๅๅ
ๅพฎๅ็ญๅบฆ:30066
|
//! A data downloader to download the flatfile historical tick archives hosted by FXCM
#![feature(rustc_attrs, conservative_impl_trait, associated_consts, custom_derive, slice_patterns)]
extern crate uuid;
extern crate libflate;
extern crate hyper;
extern crate chrono;
extern crate tickgrinder_util;
#[macro_use]
extern crate lazy_static;
extern crate tempdir;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
use std::env;
use std::thread;
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use std::path::Path;
use std::io::{Read, Write};
use std::fmt::Debug;
use std::fs::File;
use uuid::Uuid;
use chrono::{Datelike, NaiveDate, NaiveDateTime};
use hyper::client::Client;
use libflate::gzip::Decoder;
use tempdir::TempDir;
use tickgrinder_util::instance::PlatformInstance;
use tickgrinder_util::transport::commands::{Command, Response, Instance, HistTickDst, RunningDownload};
use tickgrinder_util::transport::command_server::CommandServer;
use tickgrinder_util::transport::data::transfer_data;
use tickgrinder_util::conf::CONF;
const NAME: &'static str = "FXCM Flatfile Data Downloader";
/// List of all currency pairs that can be downloaded using this tool
const SUPPORTED_PAIRS: &'static [&'static str] = &[
"AUDCAD", "AUDCHF", "AUDJPY",
"AUDNZD", "CADCHF", "EURAUD",
"EURCHF", "EURGBP", "EURJPY",
"EURUSD", "GBPCHF", "GBPJPY",
"GBPNZD", "GBPUSD", "NZDCAD",
"NZDCHF", "NZDJPY", "NZDUSD",
"USDCAD", "USDCHF", "USDJPY",
];
/// the earliest supported start data of historical data
lazy_static!{
static ref DATA_START: NaiveDateTime = NaiveDate::from_ymd(2015, 01, 04).and_hms(00, 00, 00);
}
/// debug-formats anything and returns the resulting `String`
fn debug<T: Debug>(x: T) -> String {
format!("{:?}", x)
}
/// Returns the download link to a piece of compressed tick data for a given symbol and a given month.
fn get_data_url(symbol: &str, year: i32, month: u32) -> String {
format!("https://tickdata.fxcorporate.com/{}/{}/{}.csv.gz", symbol, year, month)
}
#[derive(Clone)]
struct Downloader {
us: Instance, // our internal representation as an instance
cs: CommandServer,
running_downloads: Arc<Mutex<HashMap<Uuid, RunningDownload>>>,
http_client: Arc<Client>,
}
/// Converts a given year and week of the year into nanoseconds.
fn ym_to_ns(year: i32, week: u32) -> u64 {
let mut dt: NaiveDateTime = NaiveDate::from_ymd(year, 1, 1).and_hms(1, 1, 1);
dt = dt.with_ordinal0((week - 1) * 7).expect("Unable to create `NaiveDate` from weeks");
let cur_secs: i64 = dt.timestamp();
(cur_secs as u64) * 1000 * 1000 * 1000
}
impl PlatformInstance for Downloader {
fn handle_command(&mut self, cmd: Command) -> Option<Response> {
match cmd {
Command::Ping => Some(Response::Pong{ args: vec![self.us.uuid.hyphenated().to_string()] }),
Command::Type => Some(Response::Info{ info: String::from(NAME) }),
Command::Kill => {
thread::spawn(|| {
thread::sleep(std::time::Duration::from_secs(3));
println!("the End is near...");
std::process::exit(0);
});
Some(Response::Info{info: format!("{} will terminate in 3 seconds.", NAME)})
},
Command::DownloadTicks{start_time, end_time, symbol, dst} => {
Some(self.init_download(start_time, end_time, symbol, dst))
},
Command::GetDownloadProgress{id} => {
let running_downloads = self.running_downloads.lock().unwrap();
match running_downloads.get(&id) {
Some(download) => {
Some(Response::DownloadProgress {
download: download.clone(),
})
},
None => Some(Response::Error {
status: format!("No such data download running with that id: {}", id),
}),
}
},
Command::CancelDataDownload{download_id: _} => {
Some(Response::Error{status: String::from("The FXCM Flatfile Downloader does not support cancelling downloads.")})
},
Command::ListRunningDownloads => {
// convert the internal `HashMap` of `RunningDownload`s into a `Vec` of them and return that
let downloads_vec: Vec<RunningDownload> = self.running_downloads.lock().unwrap().values().map(|d| d.clone() ).collect();
Some(Response::RunningDownloads{ downloads: downloads_vec })
},
Command::TransferHistData{src, dst} => {
transfer_data(src, dst, self.cs.clone());
Some(Response::Ok)
},
_ => None,
}
}
}
impl Downloader {
pub fn new(uuid: Uuid) -> Downloader {
let cs = CommandServer::new(uuid, NAME);
Downloader {
us: Instance {
instance_type: String::from(NAME),
uuid: uuid,
},
cs: cs,
running_downloads: Arc::new(Mutex::new(HashMap::new())),
http_client: Arc::new(Client::new()),
}
}
/// Starts a download of historical ticks
pub fn init_download(&mut self, start_time: u64, end_time: u64, symbol: String, dst: HistTickDst) -> Response {
let download_id = Uuid::new_v4();
let symbol: String = symbol.trim().to_uppercase().replace("/", "");
if !SUPPORTED_PAIRS.contains(&symbol.as_str()) {
return Response::Error{status: format!("The FXCM Flatfile Data Downloader does not support the symbol {}", symbol)};
}
// get the starting month and year of the data download
let secs = ((start_time / 1000) / 1000) / 1000; // convert ns into seconds
let mut naive = NaiveDateTime::from_timestamp(secs as i64, 0);
if naive < *DATA_START {
naive = *DATA_START;
}
let mut year = naive.year();
let mut week = (naive.day() / 7) + 1; // gets current week of the year starting at 1
// make copies to remember where we started at
let mut start_year = year;
let mut start_week = week;
// start the data download in another thread
let mut clone = self.clone();
thread::spawn(move || {
let dst_dir = TempDir::new(&symbol).expect("Unable to create temporary directory");
loop {
let download_url = get_data_url(&symbol, year, week);
let dst_path = &dst_dir.path().join(&format!("{}_{}.csv", year, week));
match download_chunk(&*clone.http_client, &download_url, dst_path) {
Ok(true) => {
if week < 52 { week += 1; } else {
week = 1;
year += 1;
}
// update the entry in the running downloads list
let mut downloads = clone.running_downloads.lock().unwrap();
// TODO: Fix
// let entry = downloads.get_mut(&download_id).expect("Unable to get running download entry");
// entry.cur_year = year;
// entry.cur_week = week;
},
Ok(false) => { // download is complete
// transfer the data from the temporary .csv files into the `HistTickDst`
loop {
let filename = String::from(dst_dir.path().join(&format!("{}_{}.csv", start_year, start_week))
.to_str().expect("Unable to convert path to `str`"));
transfer_data(HistTickDst::Flatfile{filename: filename}, dst.clone(), clone.cs.clone());
if start_year == year && start_week == week {
break;
}
if start_week < 52 { start_week += 1; } else {
start_week = 1;
start_year += 1;
}
}
// send `DownloadComplete` message to the platform and remove the download from the list of running downloads
let mut downloads = clone.running_downloads.lock().unwrap();
let finished_download = downloads.remove(&download_id).expect("Old download not found in running downloads `HashMap`!");
let cmd = Command::DownloadComplete {
download: finished_download,
};
clone.cs.send_forget(&cmd, CONF.redis_control_channel);
break;
},
Err(err) => {
clone.cs.error(Some("HTTP"), &format!("Error during HTTP request to download {}: {}", download_url, err));
break;
}
}
}
});
Response::Ok
}
}
/// Downloads a file using HTTP, decompresses it using GZIP, and saves it to the supplied path. The return value of the boolean
/// is true if the download was successful and false if it was a 404 error.
fn download_chunk(http_client: &Client, url: &str, dst: &Path) -> Result<bool, String> {
// make the HTTP request and make sure it was successful
let res = http_client.get(url).send().expect(&format!("Error while sending HTTP request to {}", url));
if res.status == hyper::NotFound {
return Ok(false);
} else if res.status != hyper::Ok {
return Err(format!("Unexpected response type from HTTP request: {:?}", res.status));
}
// create a new Gzip decoder to decompress the data from the HTTP response
let mut decoder = try!(Decoder::new(res).map_err(debug));
// allocate a 1MB buffer for the data from the unzipped data
let mut buf = Box::new([0u8; 1024 * 1024]);
// create the output file
let mut dst_file = File::create(dst).map_err(debug)?;
// keep reading chunks of data out of the decoder until it's empty and writing them to file
loop {
let bytes_read = decoder.read(buf.as_mut()).map_err(debug)?;
// we're done if we read 0 bytes
if bytes_read == 0 {
break;
}
// write the read bytes into the destination file
dst_file.write(&buf.as_ref()[0..bytes_read]).map_err(debug)?;
}
dst_file.sync_all().map_err(|_| format!("Unable to sync file to disc: {:?}", dst_file))?;
Ok(true)
}
fn main() {
let args = env::args().collect::<Vec<String>>();
let uuid: Uuid;
match *args.as_slice() {
[_, ref uuid_str] => {
uuid = Uuid::parse_str(uuid_str.as_str())
.expect("Unable to parse Uuid from supplied argument");
},
_ => panic!("Wrong number of arguments provided! Usage: ./tick_processor [uuid] [symbol]"),
}
let downloader = Downloader::new(uuid);
let mut csc = downloader.cs.clone();
downloader.listen(uuid, &mut csc);
}
/// Make sure that our day-of-year to week-of-year conversion works correctly
#[test]
fn day_to_week() {
// TODO: Implement
// let mut year = 2014;
// let mut month = 3;
// let mut dom = 12;
// assert_eq!((naive.day() / 7) + 1, 2);
}
|
package doandkeep.com.practice.ablum.ui;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.paging.PagedList;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import doandkeep.com.practice.R;
import doandkeep.com.practice.ablum.repository.NetworkState;
import doandkeep.com.practice.ablum.repository.RetryCallback;
import doandkeep.com.practice.ablum.repository.Status;
import doandkeep.com.practice.ablum.vo.AlbumItem;
public class AlbumActivity extends AppCompatActivity {
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView recyclerView;
private AlbumAdapter adapter;
private AlbumViewModel model;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_album);
swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
recyclerView = findViewById(R.id.recycler_view);
model = ViewModelProviders.of(this).get(AlbumViewModel.class);
initAdapter();
initSwipeToRefresh();
}
private void initAdapter() {
adapter = new AlbumAdapter(new RetryCallback() {
@Override
public void retry() {
model.retry();
}
});
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (adapter.getItemViewType(position) == R.layout.album_picture_item) {
return 1;
}
return 3;
}
});
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setAdapter(adapter);
model.getAlbums().observe(this, new Observer<PagedList<AlbumItem>>() {
@Override
public void onChanged(@Nullable PagedList<AlbumItem> albums) {
adapter.submitList(albums);
}
});
model.getNetworkState().observe(this, new Observer<NetworkState>() {
@Override
public void onChanged(@Nullable NetworkState networkState) {
adapter.setNetworkState(networkState);
}
});
}
private void initSwipeToRefresh() {
model.getRefreshState().observe(this, new Observer<NetworkState>() {
@Override
public void onChanged(NetworkState networkState) {
if (networkState.getStatus() != Status.RUNNING) {
swipeRefreshLayout.setRefreshing(false);
}
// swipeRefreshLayout.setRefreshing(networkState.getStatus() == Status.RUNNING);
}
});
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
model.refresh();
}
});
}
}
|
(cl:in-package drive_ros_msgs-msg)
(cl:export '(HEADER-VAL
HEADER
SYSID-VAL
SYSID
COMPID-VAL
COMPID
TIME_DELTA-VAL
TIME_DELTA
DIST_DELTA-VAL
DIST_DELTA
DIST_ABS-VAL
DIST_ABS
VELOCITY-VAL
VELOCITY
QUALITY-VAL
QUALITY
)) |
/*
* simple ReadWriteLock, implemented by using mutex's
*
* by Albert Zeyer, code under LGPL
*/
#ifndef READWRITELOCK_H
#define READWRITELOCK_H
#include <SDL.h>
#include "ThreadPool.h"
#include "Debug.h"
class ReadWriteLock {
private:
SDL_mutex* mutex;
unsigned int readCounter;
unsigned short writerWaitingFlag;
public:
ReadWriteLock() {
readCounter = 0;
writerWaitingFlag = 0;
mutex = SDL_CreateMutex();
}
~ReadWriteLock() {
if(readCounter)
warnings("destroying ReadWriteLock with positive readCounter!\n");
SDL_DestroyMutex(mutex);
}
void startReadAccess() {
SDL_mutexP(mutex);
// wait for any writer in the queue
while(writerWaitingFlag) {
SDL_mutexV(mutex);
SDL_Delay(1);
SDL_mutexP(mutex);
}
readCounter++;
SDL_mutexV(mutex);
}
void endReadAccess() {
SDL_mutexP(mutex);
readCounter--;
SDL_mutexV(mutex);
}
void startWriteAccess() {
SDL_mutexP(mutex);
// wait for other writers
while(writerWaitingFlag) {
SDL_mutexV(mutex);
SDL_Delay(1);
SDL_mutexP(mutex);
}
writerWaitingFlag = 1;
// wait for other readers
while(readCounter) {
SDL_mutexV(mutex);
SDL_Delay(1);
SDL_mutexP(mutex);
}
}
void endWriteAccess() {
writerWaitingFlag = 0;
SDL_mutexV(mutex);
}
};
// General scoped lock for SDL_Mutex
class ScopedLock {
private:
SDL_mutex* data_mutex;
// Non-copyable
ScopedLock( const ScopedLock & ) : data_mutex(NULL) { assert(false); };
ScopedLock & operator= ( const ScopedLock & ) { assert(false); return *this; };
public:
ScopedLock( SDL_mutex* mutex ): data_mutex(mutex) {
SDL_mutexP(data_mutex);
// It is safe to call SDL_mutexP()/SDL_mutexV() on a mutex several times
// HINT to the comment: it's not only safe, it's the meaning of it; in the case it is called twice,
// it locks until there is a SDL_mutexV. But *always* call SDL_mutexV from the same thread which has
// called SDL_mutexP before (else you get serious trouble). Also never call SDL_mutexV when there
// was no SDL_mutexP before.
}
~ScopedLock() {
SDL_mutexV(data_mutex);
}
SDL_mutex* getMutex() { return data_mutex; }; // For usage with SDL_CondWait(), DON'T call SDL_mutexP( lock.getMutex() );
};
class ScopedReadLock {
private:
ReadWriteLock& lock;
// Non-copyable
ScopedReadLock( const ScopedReadLock& l ) : lock(l.lock) { assert(false); };
ScopedReadLock & operator= ( const ScopedReadLock & ) { assert(false); return *this; };
public:
ScopedReadLock( ReadWriteLock& l ): lock(l) { l.startReadAccess(); }
~ScopedReadLock() { lock.endReadAccess(); }
};
// TODO: add ReadScopedLock and WriteScopedLock classes for ReadWriteLock
#endif // __READWRITELOCK_H__
|
TheBusinessGrid
Improvements:
Update logo and landing page
Change setup questions from bus list to drop-down
Change content of setup questions
Email authentication after create account
Forgot password functionality
Facebook and Gmail login
Restrict users from opening session-specific pages
URL aliases
Unique users at registration
JSON encryption
HTTPS over HTTP
Create a friendly login page or use AJAX
Editable profiles
Collecting more data and presenting it in charts and graphs
Implementing an algorithm that processed said data |
import numpy as np
import matplotlib.pyplot as plt
fn1 = 'week_spd.txt'
fn2 = 'week_visb.txt'
fn3 = 'week_temp.txt'
fn4 = 'week_prcp.txt'
fn5 = 'week_sd.txt'
fn6 = 'week_sdw.txt'
def open_file(fn):
f = open(fn)
content = f.readlines()
f.close()
return content
def getlist(content):
#52 weeks in a year
number = 52
#array = [0] * number
array = np.zeros(number, dtype = 'float')
for i in range (len(content)):
key, value = content[i].strip('\n').split(',')
index = int(key) - 1
val = float(value)
if index >= 0:
array[index] = val
return array
week_spd = getlist(open_file(fn1))
week_visb = getlist(open_file(fn2))
week_visb_adjust = np.divide(week_visb, 1000)
week_temp = getlist(open_file(fn3))
week_prcp = getlist(open_file(fn4))
week_sd = getlist(open_file(fn5))
week_sdw = getlist(open_file(fn6))
week_sdw_adjust = np.divide(week_sdw, 10)
plt.figure()
plt.title('Weather for 2016', fontsize=20, fontweight='bold')
plt.plot(week_spd, "b", label = 'Wind Speed Rate (meters per secont)')
plt.plot(week_visb_adjust, "c", label = 'Visibility (kilometers)')
plt.plot(week_temp, "m", label = 'Temperature (degrees Celsius)')
plt.plot(week_prcp, "r", label = 'Precipitation (millimeters)')
plt.plot(week_sd, "y", label = 'Depth of snow and ice (centimeters)')
plt.plot(week_sdw_adjust, "k", label = 'Snow Precipitation (centimeters)')
plt.xlabel("Week")
plt.legend()
plt.show()
|
#!/usr/bin/env ruby
system "find . -name '*.rb' | ctags -f .tags --languages=Ruby -L -"
if File.exist? './Gemfile'
require 'bundler'
paths = Bundler.load.specs.map(&:full_gem_path).join(' ')
system "ctags -R -f .gemtags --languages=Ruby #{paths}"
end
|
export const saveConfig = (config: any) => ({
type: 'saveConfig',
payload: { ...config },
});
export const changeTheme = (nameTheme: string) => ({
type: 'changeTheme',
payload: { nameTheme },
});
export const changeStatusNotifDebug = (enabled: boolean) => ({
type: 'changeStatusNotifDebug',
payload: { enabled },
});
|
// Copyright 2018 Esote. All rights reserved. Use of this source code is
// governed by an MIT license that can be found in the LICENSE file.
package matrix2d
// Point represents a point in the matrix, indexed by row and column.
type Point struct {
X int
Y int
}
// Search searches a rectangular, sorted (column-wise and row-wise) matrix.
func Search(matrix [][]int, key int) (Point, bool) {
badpt := Point{-1, -1}
width := len(matrix)
if width < 1 {
return badpt, false
}
height := len(matrix[0])
if height < 1 {
return badpt, false
}
if height < width {
ret, ok := Search(lazyTranspose(matrix), key)
return Point{ret.Y, ret.X}, ok
}
minc := 0
maxr := height - 1
diag := height / width
for minc < width && maxr >= 0 {
r := max(maxr-diag, 0)
if e := matrix[minc][r]; key == e {
return Point{minc, r}, true
} else if key < e {
maxr = r - 1
continue
}
minrc := r + 1
maxrc := maxr
for minrc <= maxr {
mid := minrc + (maxrc-minrc+1)/2
if e := matrix[minc][mid]; key == e {
return Point{minc, mid}, true
} else if key < e {
maxrc = mid - 1
maxr = mid - 1
} else {
minrc = mid + 1
}
}
minc++
}
return badpt, false
}
// Rotate a rectangular dim0 x dim1 matrix. Assumes matrix of valid size.
func lazyTranspose(matrix [][]int) [][]int {
dim0 := len(matrix)
dim1 := len(matrix[0])
ret := make([][]int, dim1)
for i := 0; i < dim1; i++ {
ret[i] = make([]int, dim0)
for j := 0; j < dim0; j++ {
ret[i][j] = matrix[j][i]
}
}
return ret
}
// Find maximum of two integers.
func max(a, b int) int {
if a > b {
return a
}
return b
}
|
/*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.sql.pipeline.persistence
import com.netflix.spinnaker.kork.core.RetrySupport
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType
import de.huxhorn.sulky.ulid.ULID
import org.jooq.DSLContext
import org.jooq.Record
import org.jooq.Table
import org.jooq.impl.DSL
import org.jooq.impl.DSL.field
/**
* Run the provided [fn] in a transaction.
*/
internal fun DSLContext.transactional(
retrySupport: RetrySupport,
fn: (DSLContext) -> Unit
) {
retrySupport.retry(
{
transaction { ctx ->
fn(DSL.using(ctx))
}
},
5, 100, false
)
}
/**
* Converts a String id to a jooq where condition, either using the legacy
* UUID scheme or modern ULID.
*/
internal fun String.toWhereCondition() =
if (isULID(this)) {
field("id").eq(this)
} else {
field("legacy_id").eq(this)
}
/**
* Determines if the given [id] is ULID format or not.
*/
internal fun isULID(id: String): Boolean {
try {
if (id.length == 26) {
ULID.parseULID(id)
return true
}
} catch (ignored: Exception) {}
return false
}
/**
* Convert an execution type to its jooq table object.
*/
internal val ExecutionType.tableName: Table<Record>
get() = when (this) {
ExecutionType.PIPELINE -> DSL.table("pipelines")
ExecutionType.ORCHESTRATION -> DSL.table("orchestrations")
}
/**
* Convert an execution type to its jooq stages table object.
*/
internal val ExecutionType.stagesTableName: Table<Record>
get() = when (this) {
ExecutionType.PIPELINE -> DSL.table("pipeline_stages")
ExecutionType.ORCHESTRATION -> DSL.table("orchestration_stages")
}
/**
* Selects all stages for an [executionType] and List [executionIds].
*/
internal fun DSLContext.selectExecutionStages(executionType: ExecutionType, executionIds: Collection<String>) =
select(field("execution_id"), field("body"))
.from(executionType.stagesTableName)
.where(field("execution_id").`in`(*executionIds.toTypedArray()))
.fetch()
.intoResultSet()
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutoMatchingExchange
{
public class LimitPriceLevel
{
public decimal LimitPrice { get; private set; } //key
public decimal TotalLevelQuantity { get; private set; }
public int NumberOfOrders { get; private set; }
public bool IsBid { get; private set; }
public LimitOrdersLinkedList Orders { get; private set; }
public LimitPriceLevel(LimitOrder order)
{
LimitPrice = order.LimitPrice;
TotalLevelQuantity = order.Quantity;
NumberOfOrders = 1;
IsBid = order.IsBid;
Orders = new LimitOrdersLinkedList();
Orders.AddFirst(order);
order.SetParentLevel(this);
}
public void AddOrder(LimitOrder order)
{
TotalLevelQuantity += order.Quantity;
NumberOfOrders += 1;
Orders.AddLast(order);
order.SetParentLevel(this);
}
public bool RemoveOrder(string orderId, out LimitOrder order)
{
var success = Orders.Remove(orderId, out order);
if (success)
{
TotalLevelQuantity -= order.Quantity;
NumberOfOrders -= 1;
}
else
{
order = null;
}
return success;
}
public bool UpdateOrder(LimitOrder order)
{
decimal prevQty = 0;
var success = Orders.Update(order, out prevQty);
if (success)
{
TotalLevelQuantity = TotalLevelQuantity - prevQty + order.Quantity;
}
return success;
}
}
}
|
class C {
@Foo(false)
static staticMethod() {}
}
|
using NodeCanvas.Framework;
using ParadoxNotion;
using ParadoxNotion.Design;
using System;
using UnityEngine;
namespace NodeCanvas.Tasks.Conditions
{
[Category("Mecanim"), Name("Check Mecanim Int")]
public class MecanimCheckInt : ConditionTask<Animator>
{
[RequiredField]
public BBParameter<string> parameter;
public CompareMethod comparison;
public BBParameter<int> value;
protected override string info
{
get
{
return string.Concat(new object[]
{
"Mec.Int ",
this.parameter.ToString(),
OperationTools.GetCompareString(this.comparison),
this.value
});
}
}
protected override bool OnCheck()
{
return OperationTools.Compare(base.agent.GetInteger(this.parameter.value), this.value.value, this.comparison);
}
}
}
|
// Copyright 2018 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package check
import (
"fmt"
"time"
multierror "github.com/hashicorp/go-multierror"
kubeMeta "istio.io/istio/galley/pkg/metadata/kube"
"istio.io/istio/galley/pkg/source/kube/client"
"istio.io/istio/galley/pkg/source/kube/log"
sourceSchema "istio.io/istio/galley/pkg/source/kube/schema"
"k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/wait"
)
var (
pollInterval = time.Second
pollTimeout = time.Minute
)
// ResourceTypesPresence verifies that all expected k8s resources types are
// present in the k8s apiserver.
func ResourceTypesPresence(k client.Interfaces) error {
cs, err := k.APIExtensionsClientset()
if err != nil {
return err
}
return resourceTypesPresence(cs, kubeMeta.Types.All())
}
func resourceTypesPresence(cs clientset.Interface, specs []sourceSchema.ResourceSpec) error {
search := make(map[string]*sourceSchema.ResourceSpec, len(specs))
for i, spec := range specs {
search[spec.Plural] = &specs[i]
}
err := wait.Poll(pollInterval, pollTimeout, func() (bool, error) {
var errs error
nextResource:
for plural, spec := range search {
gv := schema.GroupVersion{Group: spec.Group, Version: spec.Version}.String()
list, err := cs.Discovery().ServerResourcesForGroupVersion(gv)
if err != nil {
errs = multierror.Append(errs, fmt.Errorf("could not find %v: %v", gv, err))
continue nextResource
}
found := false
for _, r := range list.APIResources {
if r.Name == spec.Plural {
delete(search, plural)
found = true
break
}
}
if !found {
log.Scope.Infof("%s resource type not found", spec.CanonicalResourceName())
}
}
if len(search) == 0 {
return true, nil
}
// entire search failed
if errs != nil {
return true, errs
}
// check again next poll
return false, nil
})
if err != nil {
var notFound []string
for plural := range search {
notFound = append(notFound, plural)
}
return fmt.Errorf("%v: the following resource type(s) were not found: %v", err, notFound)
}
log.Scope.Infof("Discovered all supported resources (# = %v)", len(specs))
return nil
}
|
import styles from './Footer.module.scss';
import { Box, Typography, Divider, Link, Input } from '@mui/material';
import TwitterIcon from '@mui/icons-material/Twitter';
import InstagramIcon from '@mui/icons-material/Instagram';
import LinkedInIcon from '@mui/icons-material/LinkedIn';
import LanguageIcon from '@mui/icons-material/Language';
import Button from '../Button/Button';
import footerLogoImage from '../../assets/svg/footer-logo.svg';
import darkLogo from '../../assets/images/blackLogo.png';
import lightLogo from '../../assets/images/lightLogo.png';
import { solutionsArray, useCases, resources, company } from './constants';
import { getCurrentYear } from '../../utils/date';
import ThemeSwitcher from '../ThemeSwitcher/ThemeSwitcher';
import { LIGHT_MODE_THEME } from '../../utils/constants';
const Footer = ({ theme }: any) => {
const getLinks = (links: any) => {
return (
<ul>
{links.map((item: any, index: number) => (
<li key={index}>
<Link onClick={handleClick} color="inherit" href="/">
{item.label}
</Link>
</li>
))}
</ul>
);
};
const handleClick = (event: any) => {
event.preventDefault();
};
const logo = theme?.theme === LIGHT_MODE_THEME ? darkLogo : lightLogo;
return (
<footer className={styles.footer}>
<Box className={styles.customContainer}>
<Box className={styles.topContent}>
<Box className={styles.logoSection}>
<Link href="/" onClick={handleClick}>
<img src={logo} alt="logo" className="mb-3" />
</Link>
<p className="averta-regular mb-0">
Fullstack product teams to start, run and <br /> grow your website
</p>
</Box>
<Box className={styles.socialIconsWrapper}>
<Box className={styles.socialIconsInner}>
<Box sx={{ display: 'flex', alignItems: 'center' }}>
<ThemeSwitcher theme={theme} />
</Box>
<Box>
<Link onClick={handleClick} color="inherit" href="twitter.com">
<TwitterIcon />
</Link>
<Link
onClick={handleClick}
color="inherit"
href="instagram.com">
<InstagramIcon />
</Link>
<Link onClick={handleClick} color="inherit" href="linkedin.com">
<LinkedInIcon />
</Link>
<Link onClick={handleClick} color="inherit" href="twitter.com">
<LanguageIcon />
</Link>
</Box>
</Box>
<Box className={styles.subscriptionWrapper}>
<Input type="text" placeholder="Subscribe to our newsletter" />
<Button
label="Subscribe"
size="small"
className={styles.btnStyling}
/>
</Box>
</Box>
</Box>
<Box className={styles.mainListingWrapper}>
<Box className={styles.listingWrapper}>
<Typography variant="h6">Solutions</Typography>
{getLinks(solutionsArray)}
</Box>
<Box className={styles.listingWrapper}>
<Typography variant="h6">Use Cases</Typography>
{getLinks(useCases)}
</Box>
<Box className={styles.listingWrapper}>
<Typography variant="h6">Resources</Typography>
{getLinks(resources)}
</Box>
<Box className={styles.listingWrapper}>
<Typography variant="h6">Company</Typography>
{getLinks(company)}
</Box>
</Box>
<Divider className={styles.borderColor} />
<Box className={styles.bottomContent}>
<Box
sx={{ display: 'flex', alignItems: 'center', columnGap: '1rem' }}>
<img src={footerLogoImage} alt="footer logo" />
<Link color="inherit" href="/">
Privacy
</Link>
<Link color="inherit" href="/">
Sitemap
</Link>
</Box>
<p>ยฉ{getCurrentYear()} Webstacks. All Rights Reserved.</p>
</Box>
</Box>
</footer>
);
};
export default Footer;
|
package deltix.containers.interfaces;
/**
* Represents an operation that accepts a single input argument and returns no
* result.
* @param <T> the type of the input to the operation
*/
public interface Consumer<T> extends java.util.function.Consumer<T> {
}
|
class FollowSerializer < ApplicationSerializer
def attributes
{
id: model.id,
user: user,
followable: followable,
created_at: model.created_at,
updated_at: model.updated_at
}
end
private
def followable
if model.association(:followable).loaded? && model.followable.present?
if model.followable.is_a?(Community)
CommunitySerializer.serialize(model.followable)
end
end
end
def user
model.association(:user).loaded? && model.user.present? ? UserSerializer.serialize(model.user) : nil
end
end
|
---
title: "Gist ์ฌ์ฉ"
categories:
- Blog
tags:
- [Blog, jekyll, Github, minimal-mistake, Gist]
toc: true
toc_sticky: true
date: 2021-03-31 15:10:10 +1000
last_modified_at:
---
# Gist
ใ`์ฝ๋` ๋ `๋ก๊ทธ` , `๋ฉ๋ชจ` ๋ฑ์ ๋จ๊ธฐ๋๋ฐ ์ฌ์ฉํ๋ค๊ณ ํ๋ค .
ใ`์งง์ ์ฝ๋` ๋ฅผ ์ค๋ช
ํ๋ ๊ฒ์ด ์๋ `๊ธด ์ค์ ์ฝ๋` ๊ฐ์ ๊ฒฝ์ฐ
ใ`MD` ํ์ผ์ `ํ์ด๋ผ์ดํธ` ๋ฅผ ์ฃผ๋ ๊ฒ ๋ณด๋จ ๋ซ๋ค๊ณ ์๊ฐ์ด ๋ฆ .
ใ์์ผ๋ก ํฌ์คํ
ํ ๋๋ `Gist` ๋ฅผ ์ฌ์ฉํด๋ณด๋ ค๊ณ ํจ.
ใ์ด์ ๊ธ๋ค๋ ์๊ฐ์ด ๋๋ฉด ์กฐ๊ธ์ฉ ์์ ํด์ผ์ง ... .
# ์ฌ์ฉ๋ฒ
[https://gist.github.com/][githublink1] ์์ ์ฌ์ฉํ๋ฉด ๋๋ค .
[githublink1]: https://gist.github.com/

ใ`์ฝ๋` ๋ฅผ ์ ์ฅํ๊ณ ๋์ `Embed` ์์ ์์ค ์ฝ๋๋ฅผ ๋ณต์ฌํด์ `md` ํ์ผ์ ๋ถ์ฌ๋ฃ๊ธฐ ํ๋ฉด ๋๋ค .
```html
<script src="https://gist.github.com/onzero98/fb4b0316942acf9ca38399d2a6b1fe95.js"></script>
```
<script src="https://gist.github.com/onzero98/fb4b0316942acf9ca38399d2a6b1fe95.js"></script> |
package com.testtube.gstreporter.workers
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.util.Log
import androidx.work.Data
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.ktx.storage
import com.testtube.gstreporter.utils.Common
import java.io.ByteArrayOutputStream
import java.io.File
class FirebaseStorageFileUpload(
appContext: Context,
workerParams: WorkerParameters
) :
Worker(appContext, workerParams) {
override fun doWork(): Result {
if (inputData.getBoolean("is-avatar", false)) {
uploadAvatar(inputData)
} else
uploadInvoiceImages(inputData)
return Result.success()
}
private fun uploadInvoiceImages(input: Data) {
val path: String = input.getString("path")!!
val invoice: String = input.getString("inv")!!
val storage = Firebase.storage
val storageRef = storage.reference
val file = Uri.fromFile(File(path))
val ref = storageRef.child("${Common.getUser()}/${invoice}/${file.lastPathSegment}")
val refThumb =
storageRef.child("${Common.getUser()}/${invoice}/thumb/${file.lastPathSegment}")
val uploadTask = ref.putFile(file)
val thumbNail = Common.getCircularCroppedImage(
Common.grabBitMapfromFileAsync(
applicationContext,
path,
96
)!!
)
val baos = ByteArrayOutputStream()
thumbNail?.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val data = baos.toByteArray()
refThumb.putBytes(data)
uploadTask.continueWithTask {
if (!it.isSuccessful) {
Log.e(javaClass.simpleName, "upload-image-exp: ", it.exception)
}
it.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.e(javaClass.simpleName, "download-url: success")
} else {
Log.e(javaClass.simpleName, "download-url-exp: ", task.exception)
}
}
}
}
private fun uploadAvatar(input: Data) {
val path: String = input.getString("path")!!
val storage = Firebase.storage
val storageRef = storage.reference
val file = Uri.fromFile(File(path))
val refThumb = storageRef.child("${Common.getUser()}/avatar.${file.lastPathSegment?.split(".")
?.get(1)}")
val thumbNail = Common.getCircularCroppedImage(
Common.grabBitMapfromFileAsync(
applicationContext,
path,0
)!!
)
val baos = ByteArrayOutputStream()
thumbNail?.compress(Bitmap.CompressFormat.JPEG, 70, baos)
val data = baos.toByteArray()
val uploadThumbTask = refThumb.putBytes(data)
uploadThumbTask.continueWithTask {
if (!it.isSuccessful) {
Log.e(javaClass.simpleName, "upload-image-exp: ", it.exception)
}
it.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.e(javaClass.simpleName, "download-url: success")
} else {
Log.e(javaClass.simpleName, "download-url-exp: ", task.exception)
}
}
}
}
} |
<?php
namespace tests\Illuminate\Queue;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Queue\QueueManager;
use Illuminate\Queue\Worker;
use Mockery as m;
class WorkerTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Mockery\MockInterface
*/
protected $_manager;
/**
* @var \Mockery\MockInterface
*/
protected $_events;
/**
* @var \Mockery\MockInterface
*/
protected $_exceptions;
/**
* @var \Illuminate\Queue\Worker
*/
protected $worker;
public function setUp()
{
parent::setUp();
$this->_manager = m::mock(\Illuminate\Queue\QueueManager::class);
$this->_events = m::mock(\Illuminate\Contracts\Events\Dispatcher::class);
$this->_exceptions = m::mock(\Illuminate\Contracts\Debug\ExceptionHandler::class);
$this->worker = new \Illuminate\Queue\Worker($this->_manager, $this->_events, $this->_exceptions);
}
public function testDaemon0()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$queue = m::mock('UntypedParameter_queue_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
// Traversed conditions
// while (true) == false (line 91)
$actual = $this->worker->daemon($connectionName, $queue, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testDaemon1()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$queue = m::mock('UntypedParameter_queue_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
// Traversed conditions
// while (true) == true (line 91)
// if (!$this->daemonShouldRun($options, $connectionName, $queue)) == false (line 95)
// if ($job) == false (line 113)
// while (true) == false (line 91)
$actual = $this->worker->daemon($connectionName, $queue, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testDaemon2()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$queue = m::mock('UntypedParameter_queue_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
// Traversed conditions
// while (true) == true (line 91)
// if (!$this->daemonShouldRun($options, $connectionName, $queue)) == false (line 95)
// if ($job) == true (line 113)
// while (true) == false (line 91)
$actual = $this->worker->daemon($connectionName, $queue, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testDaemon3()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$queue = m::mock('UntypedParameter_queue_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
// Traversed conditions
// while (true) == true (line 91)
// if (!$this->daemonShouldRun($options, $connectionName, $queue)) == true (line 95)
// while (true) == false (line 91)
$actual = $this->worker->daemon($connectionName, $queue, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testRunNextJob0()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$queue = m::mock('UntypedParameter_queue_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
// Traversed conditions
// if ($job) == false (line 226)
$actual = $this->worker->runNextJob($connectionName, $queue, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testRunNextJob1()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$queue = m::mock('UntypedParameter_queue_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
// Traversed conditions
// if ($job) == true (line 226)
$actual = $this->worker->runNextJob($connectionName, $queue, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
/**
* @expectedException \Exception
*/
public function testProcess0()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$job = m::mock('UntypedParameter_job_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
$actual = $this->worker->process($connectionName, $job, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testProcess1()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$job = m::mock('UntypedParameter_job_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
$actual = $this->worker->process($connectionName, $job, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testProcess2()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$job = m::mock('UntypedParameter_job_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
$actual = $this->worker->process($connectionName, $job, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
/**
* @expectedException \Exception
*/
public function testProcess3()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$job = m::mock('UntypedParameter_job_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
$actual = $this->worker->process($connectionName, $job, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testProcess4()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$job = m::mock('UntypedParameter_job_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
$actual = $this->worker->process($connectionName, $job, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testProcess5()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$job = m::mock('UntypedParameter_job_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
$actual = $this->worker->process($connectionName, $job, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
/**
* @expectedException \Exception
*/
public function testProcess6()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$job = m::mock('UntypedParameter_job_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
$actual = $this->worker->process($connectionName, $job, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testProcess7()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$job = m::mock('UntypedParameter_job_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
$actual = $this->worker->process($connectionName, $job, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testProcess8()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$job = m::mock('UntypedParameter_job_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
$actual = $this->worker->process($connectionName, $job, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
/**
* @expectedException \Exception
*/
public function testProcess9()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$job = m::mock('UntypedParameter_job_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
$actual = $this->worker->process($connectionName, $job, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testProcess10()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$job = m::mock('UntypedParameter_job_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
$actual = $this->worker->process($connectionName, $job, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testProcess11()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$job = m::mock('UntypedParameter_job_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
$actual = $this->worker->process($connectionName, $job, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testProcess12()
{
$connectionName = m::mock('UntypedParameter_connectionName_');
$job = m::mock('UntypedParameter_job_');
$options = m::mock(\Illuminate\Queue\WorkerOptions::class);
// TODO: Your mock expectations here
$actual = $this->worker->process($connectionName, $job, $options);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testMemoryExceeded0()
{
$memoryLimit = m::mock('UntypedParameter_memoryLimit_');
// TODO: Your mock expectations here
$actual = $this->worker->memoryExceeded($memoryLimit);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testStop0()
{
$status = m::mock('UntypedParameter_status_');
// TODO: Your mock expectations here
$actual = $this->worker->stop($status);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testKill0()
{
$status = m::mock('UntypedParameter_status_');
// TODO: Your mock expectations here
// Traversed conditions
// if (extension_loaded('posix')) == false (line 586)
$actual = $this->worker->kill($status);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testKill1()
{
$status = m::mock('UntypedParameter_status_');
// TODO: Your mock expectations here
// Traversed conditions
// if (extension_loaded('posix')) == true (line 586)
$actual = $this->worker->kill($status);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testSleep0()
{
$seconds = m::mock('UntypedParameter_seconds_');
// TODO: Your mock expectations here
// Traversed conditions
// if ($seconds < 1) == false (line 601)
$actual = $this->worker->sleep($seconds);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testSleep1()
{
$seconds = m::mock('UntypedParameter_seconds_');
// TODO: Your mock expectations here
// Traversed conditions
// if ($seconds < 1) == true (line 601)
$actual = $this->worker->sleep($seconds);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testSetCache0()
{
$cache = m::mock(\Illuminate\Contracts\Cache\Repository::class);
// TODO: Your mock expectations here
$actual = $this->worker->setCache($cache);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testGetManager0()
{
// TODO: Your mock expectations here
$actual = $this->worker->getManager();
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
public function testSetManager0()
{
$manager = m::mock(\Illuminate\Queue\QueueManager::class);
// TODO: Your mock expectations here
$actual = $this->worker->setManager($manager);
$expected = null; // TODO: Expected value here
$this->assertEquals($expected, $actual);
}
}
|
; 10. A string of bytes is given. Obtain the mirror image of the binary representation of this string of bytes.
; Ex: The byte string is given: s db 01011100b, 10001001b, 11100101b
; The result is the string: d db 10100111b, 10010001b, 00111010b.
assume cs:code, ds:data
data segment
s db 01011100b, 10001001b, 11100101b
leng equ $-s
d db leng dup (?)
s1 db 10100111b
s2 db 10010001b
s3 db 00111010b
data ends
code segment
start:
mov ax, data
mov ds, ax
mov es, ax
lea si, s + 2
lea di, d
mov ch, leng-1
mov bx, 0
repeat:
mov ah, 00000001b
std
lodsb
mov dl, 0
mov cl, 1
loop1:
mov bl, al
and bl,ah
ror bl, cl
or dl, bl
shl ah, 1
add cl, 2
cmp cl, 17
jnz loop1
mov al, dl
cld
stosb
sub ch, 1
jns repeat
mov ax, 4c00h
int 21h
code ends
end start
|
/*
* $Id: asn.c,v 1.57.2.3 2000/05/15 17:27:21 wessels Exp $
*
* DEBUG: section 53 AS Number handling
* AUTHOR: Duane Wessels, Kostas Anagnostakis
*
* SQUID Internet Object Cache http://squid.nlanr.net/Squid/
* ----------------------------------------------------------
*
* Squid is the result of efforts by numerous individuals from the
* Internet community. Development is led by Duane Wessels of the
* National Laboratory for Applied Network Research and funded by the
* National Science Foundation. Squid is Copyrighted (C) 1998 by
* the Regents of the University of California. Please see the
* COPYRIGHT file for full details. Squid incorporates software
* developed and/or copyrighted by other sources. Please see the
* CREDITS file for full details.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
*
*/
#include "squid.h"
#define WHOIS_PORT 43
/* BEGIN of definitions for radix tree entries */
/* int in memory with length */
typedef u_char m_int[1 + sizeof(unsigned int)];
#define store_m_int(i, m) \
(i = htonl(i), m[0] = sizeof(m_int), xmemcpy(m+1, &i, sizeof(unsigned int)))
#define get_m_int(i, m) \
(xmemcpy(&i, m+1, sizeof(unsigned int)), ntohl(i))
/* END of definitions for radix tree entries */
/* Head for ip to asn radix tree */
struct radix_node_head *AS_tree_head;
/*
* Structure for as number information. it could be simply
* an intlist but it's coded as a structure for future
* enhancements (e.g. expires)
*/
struct _as_info {
intlist *as_number;
time_t expires; /* NOTUSED */
};
struct _ASState {
StoreEntry *entry;
request_t *request;
int as_number;
off_t seen;
off_t offset;
};
typedef struct _ASState ASState;
typedef struct _as_info as_info;
/* entry into the radix tree */
struct _rtentry {
struct radix_node e_nodes[2];
as_info *e_info;
m_int e_addr;
m_int e_mask;
};
typedef struct _rtentry rtentry;
static int asnAddNet(char *, int);
static void asnCacheStart(int as);
static STCB asHandleReply;
static int destroyRadixNode(struct radix_node *rn, void *w);
static int printRadixNode(struct radix_node *rn, void *w);
static void asnAclInitialize(acl * acls);
static void asStateFree(void *data);
static void destroyRadixNodeInfo(as_info *);
static OBJH asnStats;
extern struct radix_node *rn_lookup(void *, void *, void *);
/* PUBLIC */
int
asnMatchIp(void *data, struct in_addr addr)
{
unsigned long lh;
struct radix_node *rn;
as_info *e;
m_int m_addr;
intlist *a = NULL;
intlist *b = NULL;
lh = ntohl(addr.s_addr);
debug(53, 3) ("asnMatchIp: Called for %s.\n", inet_ntoa(addr));
if (AS_tree_head == NULL)
return 0;
if (addr.s_addr == no_addr.s_addr)
return 0;
if (addr.s_addr == any_addr.s_addr)
return 0;
store_m_int(lh, m_addr);
rn = rn_match(m_addr, AS_tree_head);
if (rn == NULL) {
debug(53, 3) ("asnMatchIp: Address not in as db.\n");
return 0;
}
debug(53, 3) ("asnMatchIp: Found in db!\n");
e = ((rtentry *) rn)->e_info;
assert(e);
for (a = (intlist *) data; a; a = a->next)
for (b = e->as_number; b; b = b->next)
if (a->i == b->i) {
debug(53, 5) ("asnMatchIp: Found a match!\n");
return 1;
}
debug(53, 5) ("asnMatchIp: AS not in as db.\n");
return 0;
}
static void
asnAclInitialize(acl * acls)
{
acl *a;
intlist *i;
debug(53, 3) ("asnAclInitialize\n");
for (a = acls; a; a = a->next) {
if (a->type != ACL_DST_ASN && a->type != ACL_SRC_ASN)
continue;
for (i = a->data; i; i = i->next)
asnCacheStart(i->i);
}
}
/* initialize the radix tree structure */
void
asnInit(void)
{
extern int max_keylen;
static int inited = 0;
max_keylen = 40;
if (0 == inited++)
rn_init();
rn_inithead((void **) &AS_tree_head, 8);
asnAclInitialize(Config.aclList);
cachemgrRegister("asndb", "AS Number Database", asnStats, 0, 1);
}
void
asnFreeMemory(void)
{
rn_walktree(AS_tree_head, destroyRadixNode, AS_tree_head);
destroyRadixNode((struct radix_node *) 0, (void *) AS_tree_head);
}
static void
asnStats(StoreEntry * sentry)
{
storeAppendPrintf(sentry, "Address \tAS Numbers\n");
rn_walktree(AS_tree_head, printRadixNode, sentry);
}
/* PRIVATE */
static void
asnCacheStart(int as)
{
LOCAL_ARRAY(char, asres, 4096);
StoreEntry *e;
request_t *req;
ASState *asState = xcalloc(1, sizeof(ASState));
cbdataAdd(asState, cbdataXfree, 0);
debug(53, 3) ("asnCacheStart: AS %d\n", as);
snprintf(asres, 4096, "whois://%s/!gAS%d", Config.as_whois_server, as);
asState->as_number = as;
req = urlParse(METHOD_GET, asres);
assert(NULL != req);
asState->request = requestLink(req);
if ((e = storeGetPublic(asres, METHOD_GET)) == NULL) {
e = storeCreateEntry(asres, asres, null_request_flags, METHOD_GET);
storeClientListAdd(e, asState);
fwdStart(-1, e, asState->request);
} else {
storeLockObject(e);
storeClientListAdd(e, asState);
}
asState->entry = e;
asState->seen = 0;
asState->offset = 0;
storeClientCopy(e,
asState->seen,
asState->offset,
4096,
memAllocate(MEM_4K_BUF),
asHandleReply,
asState);
}
static void
asHandleReply(void *data, char *buf, ssize_t size)
{
ASState *asState = data;
StoreEntry *e = asState->entry;
char *s;
char *t;
debug(53, 3) ("asHandleReply: Called with size=%d\n", size);
if (EBIT_TEST(e->flags, ENTRY_ABORTED)) {
memFree(buf, MEM_4K_BUF);
asStateFree(asState);
return;
}
if (size == 0 && e->mem_obj->inmem_hi > 0) {
memFree(buf, MEM_4K_BUF);
asStateFree(asState);
return;
} else if (size < 0) {
debug(53, 1) ("asHandleReply: Called with size=%d\n", size);
memFree(buf, MEM_4K_BUF);
asStateFree(asState);
return;
} else if (HTTP_OK != e->mem_obj->reply->sline.status) {
debug(53, 1) ("WARNING: AS %d whois request failed\n",
asState->as_number);
memFree(buf, MEM_4K_BUF);
asStateFree(asState);
return;
}
s = buf;
while (s - buf < size && *s != '\0') {
while (*s && xisspace(*s))
s++;
for (t = s; *t; t++) {
if (xisspace(*t))
break;
}
if (*t == '\0') {
/* oof, word should continue on next block */
break;
}
*t = '\0';
debug(53, 3) ("asHandleReply: AS# %s (%d)\n", s, asState->as_number);
asnAddNet(s, asState->as_number);
s = t + 1;
}
asState->seen = asState->offset + size;
asState->offset += (s - buf);
debug(53, 3) ("asState->seen = %d, asState->offset = %d\n",
asState->seen, asState->offset);
if (e->store_status == STORE_PENDING) {
debug(53, 3) ("asHandleReply: store_status == STORE_PENDING: %s\n", storeUrl(e));
storeClientCopy(e,
asState->seen,
asState->offset,
SM_PAGE_SIZE,
buf,
asHandleReply,
asState);
} else if (asState->seen < e->mem_obj->inmem_hi) {
debug(53, 3) ("asHandleReply: asState->seen < e->mem_obj->inmem_hi %s\n", storeUrl(e));
storeClientCopy(e,
asState->seen,
asState->offset,
SM_PAGE_SIZE,
buf,
asHandleReply,
asState);
} else {
debug(53, 3) ("asHandleReply: Done: %s\n", storeUrl(e));
memFree(buf, MEM_4K_BUF);
asStateFree(asState);
}
}
static void
asStateFree(void *data)
{
ASState *asState = data;
debug(53, 3) ("asnStateFree: %s\n", storeUrl(asState->entry));
storeUnregister(asState->entry, asState);
storeUnlockObject(asState->entry);
requestUnlink(asState->request);
cbdataFree(asState);
}
/* add a network (addr, mask) to the radix tree, with matching AS
* number */
static int
asnAddNet(char *as_string, int as_number)
{
rtentry *e = xmalloc(sizeof(rtentry));
struct radix_node *rn;
char dbg1[32], dbg2[32];
intlist **Tail = NULL;
intlist *q = NULL;
as_info *asinfo = NULL;
struct in_addr in_a, in_m;
long mask, addr;
char *t;
int bitl;
t = strchr(as_string, '/');
if (t == NULL) {
debug(53, 3) ("asnAddNet: failed, invalid response from whois server.\n");
return 0;
}
*t = '\0';
addr = inet_addr(as_string);
bitl = atoi(t + 1);
if (bitl < 0)
bitl = 0;
if (bitl > 32)
bitl = 32;
mask = bitl ? 0xfffffffful << (32 - bitl) : 0;
in_a.s_addr = addr;
in_m.s_addr = mask;
xstrncpy(dbg1, inet_ntoa(in_a), 32);
xstrncpy(dbg2, inet_ntoa(in_m), 32);
addr = ntohl(addr);
/*mask = ntohl(mask); */
debug(53, 3) ("asnAddNet: called for %s/%s\n", dbg1, dbg2);
memset(e, '\0', sizeof(rtentry));
store_m_int(addr, e->e_addr);
store_m_int(mask, e->e_mask);
rn = rn_lookup(e->e_addr, e->e_mask, AS_tree_head);
if (rn != NULL) {
asinfo = ((rtentry *) rn)->e_info;
if (intlistFind(asinfo->as_number, as_number)) {
debug(53, 3) ("asnAddNet: Ignoring repeated network '%s/%d' for AS %d\n",
dbg1, bitl, as_number);
} else {
debug(53, 3) ("asnAddNet: Warning: Found a network with multiple AS numbers!\n");
for (Tail = &asinfo->as_number; *Tail; Tail = &(*Tail)->next);
q = xcalloc(1, sizeof(intlist));
q->i = as_number;
*(Tail) = q;
e->e_info = asinfo;
}
} else {
q = xcalloc(1, sizeof(intlist));
q->i = as_number;
asinfo = xmalloc(sizeof(asinfo));
asinfo->as_number = q;
rn = rn_addroute(e->e_addr, e->e_mask, AS_tree_head, e->e_nodes);
rn = rn_match(e->e_addr, AS_tree_head);
assert(rn != NULL);
e->e_info = asinfo;
}
if (rn == 0) {
xfree(e);
debug(53, 3) ("asnAddNet: Could not add entry.\n");
return 0;
}
e->e_info = asinfo;
return 1;
}
static int
destroyRadixNode(struct radix_node *rn, void *w)
{
struct radix_node_head *rnh = (struct radix_node_head *) w;
if (rn && !(rn->rn_flags & RNF_ROOT)) {
rtentry *e = (rtentry *) rn;
rn = rn_delete(rn->rn_key, rn->rn_mask, rnh);
if (rn == 0)
debug(53, 3) ("destroyRadixNode: internal screwup\n");
destroyRadixNodeInfo(e->e_info);
xfree(rn);
}
return 1;
}
static void
destroyRadixNodeInfo(as_info * e_info)
{
intlist *prev = NULL;
intlist *data = e_info->as_number;
while (data) {
prev = data;
data = data->next;
xfree(prev);
}
xfree(data);
}
int
mask_len(int mask)
{
int len = 32;
while ((mask & 1) == 0) {
len--;
mask >>= 1;
}
return len;
}
static int
printRadixNode(struct radix_node *rn, void *w)
{
StoreEntry *sentry = w;
rtentry *e = (rtentry *) rn;
intlist *q;
as_info *asinfo;
struct in_addr addr;
struct in_addr mask;
assert(e);
assert(e->e_info);
(void) get_m_int(addr.s_addr, e->e_addr);
(void) get_m_int(mask.s_addr, e->e_mask);
storeAppendPrintf(sentry, "%15s/%d\t",
inet_ntoa(addr), mask_len(ntohl(mask.s_addr)));
asinfo = e->e_info;
assert(asinfo->as_number);
for (q = asinfo->as_number; q; q = q->next)
storeAppendPrintf(sentry, " %d", q->i);
storeAppendPrintf(sentry, "\n");
return 0;
}
|
// import optional from 'vet/optional';
// import exists from 'vet/exists';
import isBoolean from 'vet/booleans/isBoolean';
// import isNumber from 'vet/numbers/isNumber';
// import isShape from 'vet/objects/isShape';
import Assert from './Assert';
import CatchError from './CatchError';
import InSeries from './InSeries';
import PassThrough from './PassThrough';
describe('Assert', () => {
it('Assert',
InSeries(
(next) => next(null, true),
Assert(
(arg) => isBoolean(arg)
)
)
);
const LONG_CHAIN = InSeries(
...Array(100000).fill(
Assert(
function (val) { return val > 0; }
)
)
);
it('Long Chain Performance', (done) => {
LONG_CHAIN(done, 1, 2, 3, 4, 5, 6);
});
const LONG_CHAIN_PASSTHROUGH = InSeries(
...Array(100000).fill(
PassThrough
)
);
it('Long Chain Performance (reference)', (done) => {
LONG_CHAIN_PASSTHROUGH(done, 1, 2, 3, 4, 5, 6);
});
it(
're-throws error',
InSeries(
CatchError(
Assert(
() => false, // always fail,
() => {
const err : any = new Error('foo');
err.foo = true;
return err;
}
)
),
Assert(
(error) => error.foo === true,
'incorrect error re-thrown'
)
)
);
});
|
require 'spec_helper'
describe "the README examples" do
it 'works as announced' do
grammar = Sexpr.load(<<-YAML)
rules:
# alternative rule
bool_expr:
- bool_and
- bool_or
- bool_not
- var_ref
- bool_lit
# non-terminal
bool_and:
- [ bool_expr, bool_expr ]
bool_or:
- [ bool_expr, bool_expr ]
bool_not:
- [ bool_expr ]
bool_lit:
- [ truth_value ]
var_ref:
- [ var_name ]
# terminals
var_name:
!ruby/regexp /^[a-z]+$/
truth_value:
- true
- false
YAML
# the grammar can be used to verify the structure of s-expressions
f = (grammar === [:bool_and, [:bool_not, [:var_ref, "x"]], [:bool_lit, true]])
f.should be_truthy
f = (grammar === [:bool_and, [:bool_lit, "true"]])
f.should be_falsey
# the grammar can also be used to automatically have support on top of
# such s-expressions
expr = grammar.sexpr([:bool_lit, true])
(Sexpr===expr).should be_truthy
(expr.sexpr_type).should eq(:bool_lit)
# => :bool_lit
(expr.sexpr_body).should eq([true])
# => [true]
copy = expr.sexpr_copy do |base,child|
# copy a s-expression ala Enumerable#inject (base is [:bool_lit] initially)
base << [:bool_lit, !child]
end
copy.should eq([:bool_lit, [:bool_lit, false]])
# => [:bool_lit, [:bool_lit, false]]
(Sexpr===copy).should be_truthy
end
end |
package org.koin.test.android
import android.arch.lifecycle.ViewModel
import org.junit.Assert.assertEquals
import org.junit.Test
import org.koin.android.viewmodel.ViewModelFactory
import org.koin.android.viewmodel.ViewModelParameters
import org.koin.android.viewmodel.ext.koin.viewModel
import org.koin.core.parameter.emptyParameterDefinition
import org.koin.dsl.module.module
import org.koin.standalone.StandAloneContext.startKoin
import org.koin.standalone.get
import org.koin.test.AutoCloseKoinTest
import org.koin.test.ext.junit.assertContexts
import org.koin.test.ext.junit.assertDefinitions
import org.koin.test.ext.junit.assertRemainingInstanceHolders
class ViewModelFactoryTest : AutoCloseKoinTest() {
val module = module {
single { MyService() }
viewModel { MyViewModel(get()) }
}
class MyService
class MyViewModel(val service: MyService) : ViewModel()
@Test
fun should_create_view_model() {
startKoin(listOf(module))
ViewModelFactory.postParameters(null, emptyParameterDefinition())
val vm1 = ViewModelFactory.create(MyViewModel::class.java)
ViewModelFactory.postParameters(null, emptyParameterDefinition())
val vm2 = ViewModelFactory.create(MyViewModel::class.java)
val service = get<MyService>()
assertEquals(vm1.service, vm2.service)
assertEquals(service, vm2.service)
assertContexts(1)
assertDefinitions(2)
assertRemainingInstanceHolders(2)
}
} |
package com.ericampire.android.androidstudycase.data.datasource.lottiefiles
import com.ericampire.android.androidstudycase.data.room.LottieFilesDao
import com.ericampire.android.androidstudycase.domain.entity.Lottiefile
import com.ericampire.android.androidstudycase.util.Result
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
class LocalLottieFileDataSource @Inject constructor(
private val lottieFileDao: LottieFilesDao
) : LottieFileDataSource {
override fun findRecent(): Flow<Result<List<Lottiefile>>> {
return lottieFileDao.findByType("recent").map {
Result.Success(it)
}
}
override fun findPopular(): Flow<Result<List<Lottiefile>>> {
return lottieFileDao.findByType("popular").map {
Result.Success(it)
}
}
override fun findFeatured(): Flow<Result<List<Lottiefile>>> {
return lottieFileDao.findByType("featured").map {
Result.Success(it)
}
}
override suspend fun save(lottiefile: Lottiefile) {
lottieFileDao.save(lottiefile)
}
} |
mod color;
pub mod palette;
pub mod terminal_theme;
pub mod triplet;
pub use self::color::*;
|
kconfig_default_configure() {
yes '' | make oldconfig
}
kconfig_default_build() {
msg "Build procs: '$MK_NPROC'"
make -j $MK_NPROC
}
kconfig_default_install() {
local targets=install
if grep -q '=m$' .config; then
targets="modules_install $targets"
fi
mkdir -p $MK_DESTDIR/boot
make $targets \
INSTALL_PATH=$MK_DESTDIR/boot \
INSTALL_MOD_PATH=$MK_DESTDIR
}
|
mod bystate;
mod digital_cypher_vol_3;
mod easy_diagonal;
mod float_point_approx;
mod position_average;
mod rainfall;
mod reducing_by_steps;
mod steps_in_primes;
fn main() {}
|
package br.com.andretortolano.shared.di
interface SharedDependenciesProvider {
fun getNumberTriviaURL(): String
fun isDebug(): Boolean
} |
use clap::Parser;
mod convert;
mod demux;
mod editor;
mod export;
mod extract_rpu;
mod generate;
mod info;
mod inject_rpu;
mod mux;
pub use convert::ConvertArgs;
pub use demux::DemuxArgs;
pub use editor::EditorArgs;
pub use export::ExportArgs;
pub use extract_rpu::ExtractRpuArgs;
pub use generate::GenerateArgs;
pub use info::InfoArgs;
pub use inject_rpu::InjectRpuArgs;
pub use mux::MuxArgs;
#[derive(Parser, Debug)]
pub enum Command {
#[clap(about = "Converts RPU within a single layer HEVC file")]
Convert(ConvertArgs),
#[clap(
about = "Demuxes single track dual layer Dolby Vision into Base layer and Enhancement layer files"
)]
Demux(DemuxArgs),
#[clap(about = "Edits a binary RPU according to a JSON config")]
Editor(EditorArgs),
#[clap(about = "Exports a binary RPU file to JSON for simpler analysis")]
Export(ExportArgs),
#[clap(about = "Extracts Dolby Vision RPU from an HEVC file")]
ExtractRpu(ExtractRpuArgs),
#[clap(about = "Interleaves RPU NAL units between slices in an HEVC encoded bitstream")]
InjectRpu(InjectRpuArgs),
#[clap(about = "Generates a binary RPU from different sources")]
Generate(GenerateArgs),
#[clap(about = "Prints the parsed RPU data as JSON for a specific frame")]
Info(InfoArgs),
#[clap(about = "Interleaves the enhancement layer into a base layer HEVC bitstream")]
Mux(MuxArgs),
}
|
<?php
namespace App\Http\Controllers;
use App\Entities\Company;
use App\Entities\Country;
use App\Services\Company\CompanyIndex;
use App\Services\Company\CompanyStore;
use App\Services\Company\CompanyUpdate;
use Dingo\Api\Exception\StoreResourceFailedException;
use Session;
use Illuminate\Http\Request;
class CompanyController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$companies = Company::orderBy('id', 'desc')->paginate(10);
return view('companies.index')->withCompanies($companies);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$countries = Country::all();
return view('companies.create', compact('countries'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request, CompanyStore $companyStore)
{
//dd($request->all());
$this->validate($request, [
'name' => 'required',
'phone_country' => 'required_with:phone',
'phone' => 'required|phone',
]);
//create item
$company = $companyStore->createItem($request->all());
$company = json_decode($company);
$result_message = $company->message;
dd($company, $result_message);
if (!$company->error) {
$company = $result_message;
Session::flash('success', 'Successfully created new company - ' . $company->name);
return redirect()->route('companies.show', $company->id);
} else {
$message = $result_message;
Session::flash('error', $message);
return redirect()->back()->withInput()->withErrors($message);
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$company = Company::where('id', $id)
->first();
return view('companies.show')->withCompany($company);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$company = Company::where('id', $id)->first();
return view('companies.edit')->withCompany($company);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$user_id = auth()->user()->id;
$company = Company::findOrFail($id);
$this->validate($request, [
'name' => 'required|max:255|unique:companies,name,'.$company->id,
'phone_number' => 'required|max:13',
'sms_user_name' => 'sometimes'
]);
$phone_number = '';
if ($request->phone_number) {
if (!isValidPhoneNumber($request->phone_number)){
$message = \Config::get('constants.error.invalid_phone_number');
Session::flash('error', $message);
return redirect()->back()->withInput();
}
$phone_number = formatPhoneNumber($request->phone_number);
}
$remove_spaces_regex = "/\s+/";
//remove all spaces
$sms_user_name = preg_replace($remove_spaces_regex, '', $request->sms_user_name);
//update company record
$company->name = $request->name;
$company->phone_number = $phone_number;
$company->email = $request->email;
$company->sms_user_name = $sms_user_name;
$company->physical_address = $request->physical_address;
$company->box = $request->box;
$company->company_no = $request->company_no;
$company->updated_by = $user_id;
$company->save();
Session::flash('success', 'Successfully updated company - ' . $company->name);
return redirect()->route('companies.show', $company->id);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
|
#include <sxc/tui.hpp>
TUI::TUI(std::wstring * input)
: m_input{input}
, m_container{ftxui::Container::Vertical({})}
, m_msg_count{0}
, m_index{-1}
, m_screen{ftxui::ScreenInteractive::Fullscreen()}
{
}
/**
* Initialize the interactive components of the renderer and display it
*
* @param on_enter Callback on enter pressed
* @param on_success Callback on initialization successful (optional)
*/
void TUI::Init(
std::function<void()> on_enter,
std::function<void()> on_success
)
{
ftxui::Component input = ftxui::Make<CustomInput>(m_input);
// Adding callbacks to each key input event
CustomInput::From(input)->on_enter = on_enter;
CustomInput::From(input)->on_arrow_up = [this]()
{
ScrollUp();
};
CustomInput::From(input)->on_arrow_down = [this]()
{
ScrollDown();
};
// Layout the UI elements
auto renderer = ftxui::Renderer(input, [&]
{
return ftxui::vbox(
{
ftxui::vbox(
{
m_container->Render(),
}
) | ftxui::flex | ftxui::frame,
ftxui::separator(),
ftxui::hbox(
{
ftxui::text(L" > "),
input->Render(),
}
),
}
) | ftxui::border;
}
);
// Call the success callback here as the InteractiveScreen::Loop is blocking
on_success();
// Render UI on loop (Blocking)
m_screen.Loop(renderer);
}
/**
* @brief Print a given message to the display panel
* @param message A standard wstring object to be displayed
*/
void TUI::Print(const std::wstring message)
{
{
std::scoped_lock lock(m_mutex);
m_container->Add(ftxui::Make<Focusable>(message));
if (m_index == m_msg_count - 1)
{
// If already at bottom, scroll to down
ScrollDown();
m_index++;
}
m_msg_count++;
}
// Trigger a re-render to update the view with new message
// This section is thread-safe
// https://github.com/ArthurSonzogni/FTXUI/issues/41#issuecomment-671832846
m_screen.PostEvent(ftxui::Event::Custom);
}
/**
* @brief Print a given message to the display panel
* @param message A standard string object to be converted into wstring before
* being displayed
* @warning This will fail if a message contains non-ASCII characters
*/
void TUI::Print(const std::string message)
{
Print(std::wstring(message.begin(), message.end()));
}
/**
* Scroll up in the container
*/
void TUI::ScrollUp()
{
m_container->OnEvent(ftxui::Event::ArrowUp);
if (m_index > -1)
{
m_index--;
}
}
/**
* Scroll down in the container
*/
void TUI::ScrollDown()
{
m_container->OnEvent(ftxui::Event::ArrowDown);
if (m_index < m_msg_count - 1)
{
m_index++;
}
}
/**
* Clear input
*/
void TUI::ClearInput()
{
m_input->clear();
}
/**
* Clear display panel that contains content
*/
void TUI::ClearContainer()
{
m_container->~ComponentBase();
m_container = ftxui::Container::Vertical({});
}
|
cd src
bash run.sh ../examples/sample1.html ../examples/sample1.tex
cd ../examples/
pdflatex -interaction=nonstopmode sample1.tex
rm sample1.aux sample1.log sample1.out
cd .. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.