text
stringlengths 27
775k
|
|---|
# KE Homes
#### Author Antony Mburia Shalyn Nyakea Marial Lugare Sheina Hamisi Ephraim Mokoba
## Description
This is a webapp where tenants can find houses
## Screenshot
<img src="images/Screenshot from 2022-01-20 07-07-23.png" alt="">
<img src="images/Screenshot from 2022-01-20 07-07-49.png" alt="">
## Setup/Installation Requirements
* Clone the repository to your computer from
https://github.com/antonymburia/ke_homes.git
* Open the project using your preferred code editor.
* Open the project using a web browser, preferably Google Chrome.
## Known Bugs
There are no known bugs
## Technologies Used
HTML
CSS
Bootstrap
Javascript
## Support and contact details
for any query or support reach me via.
* antonymburia10@gmail.com
### License
This project is under [MIT](LICENSE).
### Coraborators
Shalyn Nyakea,
Marial Lugare,
Sheina Hamisi,
Ephraim Mokoba
|
#include "Precompiled.h"
#include "FileSystem.h"
namespace Lumos
{
}
|
# frozen_string_literal: true
module FingerprintConcern
extend ActiveSupport::Concern
included do
before_action :ensure_fingerprinted
end
def ensure_fingerprinted
cookies[:fp] ||= SecureRandom.uuid
end
def user_fingerprint
cookies[:fp]
end
end
|
import { render } from '@testing-library/react'
import { Link } from './Link'
test('has a href attribute when rendering with linkWrapper', () => {
// eslint-disable-next-line jsx-a11y/anchor-has-content
const LinkWrapper = (props) => <a {...props} />
const { container } = render(
<Link href="https://storybook.js.org/tutorials/" LinkWrapper={LinkWrapper}>
Link Text
</Link>
)
const linkElement = container.querySelector(
'a[href="https://storybook.js.org/tutorials/"]'
)
expect(linkElement).not.toBeNull()
expect(linkElement.textContent).toEqual('Link Text')
})
|
package logit
import (
"testing"
)
func TestLogit(t *testing.T) {
cfg := Config{
PrintCaller: true,
PrintJSON: true,
PrintStdout: true,
BuiltinFields: map[string]string{
"host_name": "parrot01",
},
}
err := InitLogs(&cfg)
if err != nil {
t.Fatal(err)
return
}
name := "jemy"
Logger.Info("what is your name? ", name)
Logger.Infof("what is your name? %s", name)
Logger.Infow("what is your name?", "name", name)
logId := []interface{}{"logid", "a34sb1312432"}
Logger.Infow("hello world", logId...)
Debug("hello world")
Info("hello world")
Warn("hello world")
Error("hello world")
Fatal("hello world") // exit with 1
Panic("hello world") // print stack
}
|
package main
import "log"
/**
三数取中法可以保证每次选取的pivot不是最大值和最小值
避免排序区间一边倒的情况
*/
func main() {
arr := []int{10, 5, 7, 3, 4, 2, 8}
arr1 := []int{10, 5, 7, 3, 4, 2, 8}
log.Println("快速排序-递归法(三数取中):", QuickSortV1(arr))
log.Println("快速排序-递归法(三数取中):", QuickSortV2(arr1))
}
func QuickSortV1(arr []int) []int {
SortV1(arr, 0, len(arr)-1)
return arr
}
func SortV1(arr []int, low, high int) {
if low >= high {
return
}
pivotIndex := partitionV1(arr, low, high)
SortV1(arr, low, pivotIndex-1)
SortV1(arr, pivotIndex+1, high)
}
func partitionV1(arr []int, low, high int) int {
// 三数取中,将中间大小的数字交换到low的位置作为pivot
midIndex := ((high - low) >> 1) + low
if arr[low] > arr[high] {
arr[low], arr[high] = arr[high], arr[low]
}
if arr[midIndex] > arr[high] {
arr[midIndex], arr[high] = arr[high], arr[midIndex]
}
if arr[midIndex] > arr[low] {
arr[midIndex], arr[low] = arr[low], arr[midIndex]
}
pivot := arr[low]
pivotIndex := low
for low < high {
// high挪动到一个比基准值小的位置,准备交换
for low < high && arr[high] >= pivot {
high--
}
// low挪动到一个比基准值大的位置,准备交换,相等的值不需要挪动位置
for low < high && arr[low] <= pivot {
low++
}
// 其实不可能大于,最多是等于
if low >= high {
break
}
arr[low], arr[high] = arr[high], arr[low]
}
arr[pivotIndex], arr[low] = arr[low], arr[pivotIndex]
return pivotIndex
}
func QuickSortV2(arr []int) []int {
SortV1(arr, 0, len(arr)-1)
return arr
}
func SortV2(arr []int, low, high int) {
if low >= high {
return
}
pivotIndex := partitionV2(arr, low, high)
SortV2(arr, low, pivotIndex-1)
SortV2(arr, pivotIndex+1, high)
}
func partitionV2(arr []int, low, high int) int {
// 三数取中,将中间大小的数字交换到low的位置作为pivot
midIndex := ((high - low) >> 1) + low
if arr[low] > arr[high] {
arr[low], arr[high] = arr[high], arr[low]
}
if arr[midIndex] > arr[high] {
arr[midIndex], arr[high] = arr[high], arr[midIndex]
}
if arr[midIndex] < arr[low] {
arr[midIndex], arr[low] = arr[low], arr[midIndex]
}
pivot := arr[midIndex]
for low < high {
for low < high && arr[low] < pivot {
low++
}
for low < high && arr[high] > pivot {
high--
}
if low >= high {
break
}
arr[low], arr[high] = arr[high], arr[low]
}
// 返回left,就是left-1
// 返回right,就是right+1
// 此时right <= left
return high
}
|
;
; Copyright © 2013 Sebastian Hoß <mail@shoss.de>
; This work is free. You can redistribute it and/or modify it under the
; terms of the Do What The Fuck You Want To Public License, Version 2,
; as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
;
(ns finj.deprecation-test
(:require [finj.deprecation :refer :all]
[com.github.sebhoss.predicate :refer :all]
[clojure.test :refer :all]))
(deftest straight-line-annual-expense-test
(testing "with positive integers"
(is (= 180 (straight-line-annual-expense :fixed-asset 1000 :residual-value 100 :period 5)))
(is (= 225 (straight-line-annual-expense :fixed-asset 2000 :residual-value 200 :period 8)))
(is (= 225 (straight-line-annual-expense :fixed-asset 3000 :residual-value 300 :period 12)))))
(deftest straight-line-expense-test
(testing "with positive integers"
(is (= '(900 900 900) (straight-line-expense :fixed-asset 3000 :residual-value 300 :period 3)))))
(deftest straight-line-accumulated-test
(testing "with positive integers"
(is (= '(900 1800 2700) (straight-line-accumulated :fixed-asset 3000 :residual-value 300 :period 3)))))
(deftest straight-line-book-value-test
(testing "with positive integers"
(is (= '(3000 2100 1200 300) (straight-line-book-value :fixed-asset 3000 :residual-value 300 :period 3)))))
(deftest declining-balance-rate-test
(testing "with positive integers"
(is (≈ 0.53584 (declining-balance-rate :fixed-asset 3000 :residual-value 300 :period 3)) 0.00001)))
(deftest declining-balance-rate-expense-test
(testing "with positive integers"
(is (= '(1607.5233499161661 746.1462430742686 346.33040700956514)
(declining-balance-rate-expense :fixed-asset 3000 :residual-value 300 :period 3)))))
(deftest declining-balance-rate-accumulated-test
(testing "with positive integers"
(is (= '(1607.5233499161661 2353.6695929904345 2699.9999999999995)
(declining-balance-rate-accumulated :fixed-asset 3000 :residual-value 300 :period 3)))))
(deftest declining-balance-rate-book-value-test
(testing "with positive integers"
(is (= '(3000 1392.4766500838339 646.3304070095653 300.00000000000017)
(declining-balance-rate-book-value :fixed-asset 3000 :residual-value 300 :period 3)))))
(deftest sum-of-years-digit-expense-test
(testing "with positive integers"
(is (= '(1350 900 450) (sum-of-years-digit-expense :fixed-asset 3000 :residual-value 300 :period 3)))))
(deftest sum-of-years-digit-accumulated-test
(testing "with positive integers"
(is (= '(1350 2250 2700) (sum-of-years-digit-accumulated :fixed-asset 3000 :residual-value 300 :period 3)))))
(deftest sum-of-years-digit-book-value-test
(testing "with positive integers"
(is (= '(3000 1650 750 300)
(sum-of-years-digit-book-value :fixed-asset 3000 :residual-value 300 :period 3)))))
(deftest units-of-production-expense-test
(testing "with positive integers"
(is (= '(450 900 1350)
(units-of-production-expense :fixed-asset 3000 :residual-value 300 :production [100 200 300])))))
(deftest units-of-production-accumulated-test
(testing "with positive integers"
(is (= '(450 1350 2700)
(units-of-production-accumulated :fixed-asset 3000 :residual-value 300 :production [100 200 300])))))
(deftest units-of-production-book-value-test
(testing "with positive integers"
(is (= '(3000 2550 1650 300)
(units-of-production-book-value :fixed-asset 3000 :residual-value 300 :production [100 200 300])))))
|
# Logger
> 📋🦄 Colorful command-line logger
## Usage
```go
package main
import (
"github.com/mineway/logger"
)
func main() {
// Define log directory location
logger.SetLogLocation("/var/log/logger")
logger.Fatal("Hello world from %s !", "README.md")
// Result => [20:10:15][fatal] Hello world from README.md !
// os exit (1)
logger.Error("Hello world from %s !", "README.md")
// Result => [20:10:15][error] Hello world from README.md !
logger.Warning("Hello world from %s !", "README.md")
// Result => [20:10:15][warning] Hello world from README.md !
logger.Info("Hello world from %s !", "README.md")
// Result => [20:10:15][info] Hello world from README.md !
logger.Success("Hello world from %s !", "README.md")
// Result => [20:10:15][success] Hello world from README.md !
logger.Log("Hello world from %s !", "README.md")
// Result => [20:10:15][log] Hello world from README.md !
}
```
|
package advent_of_code
import scala.util._
@main def day13 =
given Day = Day(13)
val data = loadData
part1
part2
def part1 =
given Part = PartA
val t = data.split("\n")
val d = t(0).toInt
val n = t(1).split(',').map(v => Try(v.toLong)).collect { case Success(v) => v}
val r = n
.map(v => (v, d.toDouble / v.toDouble))
.map((n, v) => (n, (v.toLong * n) + n))
.map((n, v) => (n, v, v - d))
.minBy(_._3)
val result = r._1 * r._3
printResult(result)
def part2 =
given Part = PartB
val n = data.split('\n')(1)
.split(',')
.zipWithIndex
.map((v, i) => (Try(v.toLong), i.toLong))
.collect { case (Success(v), i) => (v, i) }
def infiniteBigIntList(from: BigInt): LazyList[BigInt] =
LazyList.cons(from, infiniteBigIntList(from + 1))
def find(a: (Long,Long), b: (Long,Long)): BigInt =
infiniteBigIntList(0)
.map(v => (v, (v + a._2) % a._1, (v + b._2) % b._1))
.filter{ case (v, a, b) => a == 0 && b == 0 }
.map(_._1)
.head
def comb(n: List[(Long,Long)]): List[((Long, Long),(Long, Long))] =
n.toList match {
case h :: tail => tail.map(e => (h, e)) ++ comb(tail)
case _ => Nil
}
val a = comb(n.toList)
.map{ case (a,b) => (find(a,b), BigInt(a._1 * b._1)) }
.sortBy(v => v._1 + v._2)
.reverse
.toVector
val x = a.head
val y = a.drop(1)
val (r, _) = y.foldLeft(x){case (xx, yy) =>
val s = LazyList.iterate(xx._1)(_ + xx._2)
.filter { v => (v - yy._1) % yy._2 == 0 }
.take(2).toList
(s(0), s(1) - s(0))
}
printResult(r)
|
package ratelimit_test
import (
"testing"
"time"
"github.com/thomasbeukema/ratelimit"
)
func cleanWhen(id string, lmt *ratelimit.Limiter) bool {
/*
You are free to implement you own logic in here to decide which Limiter to keep
and which to remove. One example could be to check the 'exp' key from a JWT token,
and to remove the limiter if the token has expired.
*/
// For the sake of simplicity; this will only remove 'userThree'
if len(id) > 8 {
return true // Return true if Limiter should be removed
}
return false // Return false if Limiter shouldn't be removed
}
func PoolTest(t *testing.T) {
pool := ratelimit.NewPool()
userOneLimiter := ratelimit.NewLimiter(10, time.Minute) // Create new Limiter instance
pool.Register("userOne", userOneLimiter) // Register Limiter in pool with ID 'userOne'
userTwoLimiter := ratelimit.NewLimiter(20, time.Minute) // Create new Limiter instance
pool.Register("userTwo", userTwoLimiter) // Register Limiter in pool with ID 'userTwo'
userThreeLimiter := ratelimit.NewLimiter(30, time.Minute) // Create new Limiter instance
pool.Register("userThree", userThreeLimiter) // Register Limiter in pool with ID 'userThree'
_, err := pool.Find("userOne") // Retrieve Limiter by ID
if err != nil {
t.Errorf("Error at pool.Find: %v", err)
}
err = pool.Remove("userTwo") // Remove limiter from the pool
if err != nil {
t.Errorf("Error at pool.Remove: %v", err)
}
err = pool.Clean(cleanWhen) // Function which loops over every Limiter, decides to remove based on 'cleanWhen'
if err != nil {
t.Errorf("Error at pool.Clean: %v", err)
}
}
|
# Base classe of roughly everything.
class Object
# Method that sets the properties of the object to a value using a Hash of property_name => value
# @param properties [Hash{Symbol => Object}] dict of properties with their new value
# @return [self]
# @author Nuri Yuri
def apply_property(properties)
common_properties = CommonProperties
sym = nil
properties.each do |i|
sym = common_properties[i[0]]
send(sym, i[1]) if sym
end
return self
end
# Method that shows the help
def help
cc 0x75
puts "\r#{'PSDK Help'.center(80)}"
cc 0x07
print <<~EODESCRIPTION
Here's the list of the command you can enter in this terminal.
Remember that you're executing actual Ruby code.
When an ID is 005 or 023 you have to write 5 or 23, the 0-prefix should never appear in the command you enter.
EODESCRIPTION
cc 0x06
print <<~EOLIST
Warp the player to another map :\e[37m
- Debugger.warp(map_id, x, y)\e[36m
Test a trainer battle :\e[37m
- Debugger.battle_trainer(trainer_id)\e[36m
List the switches that match a specific name (with their value) :\e[37m
- Debugger.find_switch(/name/i)\e[36m
Change a switch value :\e[37m
- $game_switches[id] = value\e[36m
List the variables that match a specific name (with their value) :\e[37m
- Debugger.find_var(/name/i)\e[36m
Change a variable value :\e[37m
- $game_variables[id] = value\e[36m
List all the Pokemon ID that match a specific name :\e[37m
- Debugger.find_pokemon(/name/i)\e[36m
List all the Nature ID that match a specific name :\e[37m
- Debugger.find_nature(/name/i)\e[36m
List all the Ability ID that match a specific name :\e[37m
- Debugger.find_ability(/name/i)\e[36m
List all the Move ID that match a specific name :\e[37m
- Debugger.find_skill(/name/i)\e[36m
List all the Item ID that match a specific name :\e[37m
- Debugger.find_item(/name/i)\e[36m
Add a Pokemon to the party :\e[37m
- S.MI.add_pokemon(id, level)\e[36m
Add a Pokemon defined by a Hash to the party :\e[37m
- S.MI.add_specific_pokemon(hash)\e[36m
Remove a Pokemon from the Party :\e[37m
- S.MI.withdraw_pokemon_at(index)\e[36m
Learn a skill to a Pokemon :\e[37m
- S.MI.skill_learn(pokemon, skill_id)
- S.MI.skill_learn($actors[index_in_the_party], skill_id)\e[36m
Add an egg to the party :\e[37m
- S.MI.add_egg(id)\e[36m
Start a wild battle :\e[37m
- S.MI.call_battle_wild(id, level)
- S.MI.call_battle_wild(id1, level1, id2, level2) \e[32m# 2v2\e[37m
- S.MI.call_battle_wild(pokemon, nil)
- S.MI.call_battle_wild(pokemon1, nil, pokemon2)\e[36m
Save the game :\e[37m
- S.MI.force_save
EOLIST
end
# Constant that contains common properties used by #apply_properties
CommonProperties = {
x: :x=,
y: :y=,
z: :z=,
ox: :ox=,
oy: :oy=,
zoom_x: :zoom_x=,
zoom_y: :zoom_y=,
angle: :angle=,
opacity: :opacity=,
blend_type: :blend_type=,
mirror: :mirror=,
visible: :visible=,
zoom: :zoom=
}
end
|
package com.github.christophpickl.kpotpourri.common.io
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.testng.annotations.Test
@Test class IoTest {
fun `readFromStdOut - When print a string, Then that string should have been captured`() {
val sentToSysOut = Io.readFromStdOut {
print("out")
}
assertThat(sentToSysOut, equalTo("out"))
}
fun `writeToStdIn - When a string is written to stdin, Then that string should have been read`() {
var actual: String? = null
Io.writeToStdIn("in") {
actual = readLine()
}
assertThat(actual, equalTo("in"))
}
fun `readStdoutAndWriteStdin - sunshine`() {
var actualIn: String? = null
val actualOut = Io.readStdoutAndWriteStdin("in") {
actualIn = readLine()
print("out")
}
assertThat(actualIn, equalTo("in"))
assertThat(actualOut, equalTo("out"))
}
fun `hitEnterAndReadStdout - sunshine`() {
var actualIn: String? = null
val actualOut = Io.hitEnterAndReadStdout {
actualIn = readLine()
print("out")
}
assertThat(actualIn, equalTo(""))
assertThat(actualOut, equalTo("out"))
}
}
|
---
title: DjangoWebアプリ開発(はじめてのテスト)
date: 2018-01-04T05:00:10.000Z
category: Django
description: Djangoにおけるテストコードの実装から実行までの手順をご紹介いたします。
tags: ["Django", "Test", "UnitTest"]
thumbnail: "./django-logo-positive-e1523125572702.png"
hero: "./django-logo-positive-e1523125572702.png"
---
# 本レッスンのゴール
- Model の単体テストコードを実装し、動かし、結果を得る
# 前提条件
- Model の実装が完了していること。
<attention>
Model の実装手順については、以下をご参照ください。
<a href="https://startappdevfrom35.com/djangofirstdbappdbbuild/">Model の実装手順</a>
</attention>
# 全体の流れ
以下の流れで進めます。
1. 単体テストコードの実装
2. テスト実行
# 作業
## 1. 単体テストコードの実装
今回は、<a href="https://startappdevfrom35.com/djangofirstdbappdbbuild/">こちら</a>で作成した IncomeCategory クラス並びに
Income クラスの単体テストコードを実装します。確認したい事は次の3点です。
- 正しく IncomeCategory に値が設定されるか
- 正しく Income に値が設定されるか
- IncomeCategory の指定なしで Income を登録できない事
これらをテストするコードを、myapp/tests.py に以下の様に実装します。
```python
from django.test import TestCase
from django.db.utils import IntegrityError
from .models import IncomeCategory, Income
class IncomeCategoryTestClass(TestCase):
def test_was_registered_correctly(self):
income_category = IncomeCategory(name="給与")
income_category.save()
self.assertEqual(income_category.name, "給与")
class IncomeTestClass(TestCase):
def test_was_registered_correctly(self):
"""
Income : 正常に登録できる。
"""
income_category = IncomeCategory(name="給与")
income_category.save()
income = Income(amount=10000, incomecategoryid=income_category)
income.save()
self.assertEqual(income.incomecategoryid.name, "給与")
self.assertEqual(income.amount, 10000)
def test_failed_registration(self):
"""
Income : 登録時にエラーが発生する
"""
with self.assertRaises(IntegrityError):
income = Income(amount=10000)
income.save()
self.assertEqual(income.amount, 10000)
```
<attention>
テストのメソッド名は必ずtestで始めるようにしてください。
</attention>
以上で、テストコードの実装は完了です。
## 2. テスト実行
次に、manage.py のあるディレクトリで、以下のコマンドを実行します。
```bash
$ python manage.py test myapp
```
以下の様に出力されれば、全テストに合格です。
```bash
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
...
---
Ran 3 tests in 0.005s
OK
Destroying test database for alias 'default'...
```
<point>
Creating test database.. , Destroying test database.. とあるように、
テストの都度、テスト用データベースを別に作成、破棄している事がわかります。
これにより、テストが実際のDBに変更を加える事を防ぎ、
安心して何度でもテストを回す事が出来ます。
</point>
|
# encoding: utf-8
class RubyDocx::Document
TEMPLATE = 'document.xml'
attr_accessor :children
def initialize(children = [])
@children = children
end
def append(block)
@children << block
end
def prepend(block)
@children.unshift block
end
def build
doc = Nokogiri::XML(File.read( File.expand_path("../../templates/#{TEMPLATE}", __FILE__) ))
body = doc.at '/w:document/w:body'
@children.each { |child| body.add_child child.build }
doc
end
def render
build.to_s
end
def file
file = Tempfile.new('order_preview')
write_file(file)
end
def save(path)
file = File.open(path, 'w')
write_file(file).close
end
protected
def write_file(file)
zf = Zip::File.new File.expand_path("../../template.docx", __FILE__)
buffer = Zip::OutputStream.write_buffer do |out|
zf.entries.each do |e|
if e.ftype == :directory
out.put_next_entry(e.name)
else
out.put_next_entry(e.name)
if e.name == "word/document.xml"
out.write render
else
out.write e.get_input_stream.read
end
end
end
end
file.write(buffer.string)
file
end
end
|
## 0.2.2
* Bump `filepath` and `wai-middleware-static` upper version bounds
|
---
layout: post
title: "Google despide a otro trabajador después de que accediera a datos privados"
category: genbeta
---
Es una realidad. Muchos de los usarios que utilizamos los servicios del
gigante californiano Google tenemos claro que tienen **acceso a una gran
multitud de datos sensibles**. Sólo hay que pararse a pensar unos segundos
para darse cuenta de que pueden conocer nuestras citas con el urólogo,
nuestros intereses, e incluso, nuestros posibles flirteos con emails o
conversaciones por Google Talk.
Por ello, enterarnos de que **un empleado de 27 años de Google ha sido
despedido por acceder a información privada** debería remover los cimientos de
nuestra confianza. En este caso, según citan algunos medios, David Barksdale
se saltó las políticas de seguridad accediendo a datos privados de varios
menores. Aparentemente no se conocen las causas que llevaron a dicho empleado
**a acceder a datos privados de varios adolescentes para después amenazarles e
insultarles**, lo que sí parece confirmarse es que no habría un trasfondo
sexual en su acción.
Según un comunidado de Google, confirma el despido de David Barksdale y
comunica que, efectivamente, ha sido por **saltarse _estrictas políticas
internas de privacidad_**. Así mismo, nos informa de que continuamente están
mejorando sus sistemas mediante la creación y ampliación de logs y controles.
Así como auditando los accesos a informaciones privadas.
Una de las consecuencias de las tendencias actuales en la web es la cantidad
de información personal que tenemos dispersa a lo largo de diferentes
servicios web. Información personal que cedemos generosamente porque es
necesaria para utilizar un servicio, o porque, es introducida durante el uso
normal del mismo. Un ejemplo claro podría ser el de un proyecto personal, o
empresarial, cuyo germen nace de una herramienta online para ayudarnos a crear
un mapa mental. La información que ahí exponemos puede valer millones de euros
o, sencillamente, podría ser utilizada en nuestra contra reportando
consecuencias poco deseables. Por ello antes de utilizar un servicio online,
deberíamos pensar un par de veces en el nivel de confianza que tenemos en él.
Según nuestra [Ley Orgánica de Protección de
Datos](http://www.tecnologiapyme.com/tag/guia-lopd) que tantos quebraderos de
cabeza está dando a las empresas españolas, se garantiza, dentro de la
empresa, el conocimiento de qué personas acceden a la información privada y se
debe auditar cada acceso y modificación de los mismos (siempre que sean de
grado 3). Aunque puedan parecer medidas excesivas, **este tipo de noticias
hacen que se vean necesarias esas actuaciones por parte de las
instituciones**.
Y, aunque se auditen los accesos a la información privada, **resulta
_imposible_ evitar que una persona con acceso a datos privados haga un mal uso
de ellos**. Por ello se podría optar por integrar una zona de datos a la cual
no pueda acceder únicamente una persona (No-Lone Zone), parecida a los
protocolos establecidos en el ámbito militar y que tan famosos se hacen en las
películas (girando varias llaves a la vez, códigos que se encuentran en
distintas cajas fuertes, ...).
Vía | [TechCruch](http://techcrunch.com/2010/09/14/google-engineer-fired-
security/)
Más información | [Gawker](http://gawker.com/5637234/)
En Genbeta | [Google actualizará su política de privacidad para hacerla más
fácil de entender](http://www.genbeta.com/actualidad/google-actualizara-su-
politica-de-privacidad-para-hacerla-mas-facil-de-entender)
Artículo extraído de [Genbeta](http://www.genbeta.com).
|
name := "primefactorizer"
version := "0.1"
scalaVersion := "2.12.8"
libraryDependencies += "org.apache.commons" % "commons-math3" % "3.6"
libraryDependencies += "com.typesafe.play" %% "play-json" % "2.6.11"
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.5" % Test
libraryDependencies += "commons-io" % "commons-io" % "2.6"
mainClass in (Compile, run) := Some("com.github.nightgecko.primefactorizer.PrimeFactorizer")
|
---
---
# Manipulating files and directories
## Where am I?
Files and directories are identified by an **absolute path**, which shows how
to reach it from the *root directory*.
The root directory is identified by `/`.
As an example, `/home/benoist` is a directory located in the `home` directory,
itself located in the root directory.
`/home/benoist/list.txt` is a file located in `/home/benoist`.
Importantly, one cannot know if a path refers to a file or a directory simply
based on its name.
As a convention, most files will have an *extension*, i.e. the part following
the `.` character in a file name (e.g. `.txt` is the extension of file `foo.txt`).
In contrast to absolute path, one can refer to a file or directory thanks to its
**relative path**, which is its path relatively to the
**current working directory**.
As an example, if the current working directory is `/home/benoist`,
then `./lists.txt` is the relative path to `/home/benoist/lists.txt`.
The command `pwd` prints the absolute path of the current working directory.
```bash
$ pwd
/data
```
## Listing the content of a directory
To display the content of a directory, use the `ls` command (which stands
for "listing").
Use the `ls` command to list files and directories present in your current
working directory.
```bash
$ ls
animals creatures iris.csv molecules tooth.csv
```
As you can see, based on this result, there is no way to distinguish files from
directories.
`creatures` and `molecules`, which have no extension, are probably directories
and `iris.csv`, which extension is `.csv` is probably a file.
But this is only a convention and we need a better way to make sure of it.
### Identifying files and directories
The command `ls -l` runs the command `ls` with the option `-l` (which stands
for "long")
```bash
$ ls -l
total 20
drwxr-xr-x 2 fish fish 4096 Nov 23 15:11 animals
drwxr-xr-x 2 fish fish 4096 Nov 14 15:31 creatures
-rw-r--r-- 1 fish fish 3715 Nov 14 15:35 iris.csv
drwxr-xr-x 2 fish fish 4096 Nov 13 13:58 molecules
-rw-r--r-- 1 fish fish 1855 Nov 20 16:07 tooth.csv
```
The character `d` starting each path line indicates that this path is
a directory.
### Knowing files size
**Question**: use `man ls` to find how to print human readable file sizes.
> **Solution**:
> > The `-h` option allows to print human readable sizes.
> > ```bash
> > total 20K
> > drwxr-xr-x 2 fish fish 4.0K Nov 23 15:11 animals
> > drwxr-xr-x 2 fish fish 4.0K Nov 14 15:31 creatures
> > -rw-r--r-- 1 fish fish 3.7K Nov 14 15:35 iris.csv
> > drwxr-xr-x 2 fish fish 4.0K Nov 13 13:58 molecules
> > -rw-r--r-- 1 fish fish 1.9K Nov 20 16:07 tooth.csv
> > ```
{:.answer}
**Question**: list the content of the directory named `molecules`.
> **Solution**:
> > ```bash
> > $ ls molecules
> > cubane.pdb ethane.pdb methane.pdb octane.pdb pentane.pdb propane.pdb
> > ```
{:.answer}
**Question**: list the content of the directory named `molecules` with the
element size.
> **Solution**:
> > ```bash
> > $ ls -lh molecules
> > total 24K
> > -rw-r--r-- 1 fish fish 1.2K Nov 13 13:58 cubane.pdb
> > -rw-r--r-- 1 fish fish 622 Nov 13 13:58 ethane.pdb
> > -rw-r--r-- 1 fish fish 422 Nov 13 13:58 methane.pdb
> > -rw-r--r-- 1 fish fish 1.8K Nov 13 13:58 octane.pdb
> > -rw-r--r-- 1 fish fish 1.2K Nov 13 13:58 pentane.pdb
> > -rw-r--r-- 1 fish fish 825 Nov 13 13:58 propane.pdb
> > ```
{:.answer}
**Question**: list the content of the root directory.
> **Solution**:
> > ```bash
> > $ ls /
> > bin dev initrd.img lib64 mnt root srv tmp vmlinuz
> > boot etc initrd.img.old lost+found opt run swapfile usr vmlinuz.old
> > data home lib media proc sbin sys var
> > ```
{:.answer}
**Question**: list the content of directory `home/fish` which is located
in the parent directory of `/data`.
> **Solution**:
> > ```bash
> > $ ls ../home/fish/
> > ```
> > `..` is the shortcut for the parent directory of the current directory.
> > In the same fashion, `../..` would be the parent of the parent.
> >
> > In this example, there is no output to the `ls` command, which basically
> > means that the directory is empty.
{:.answer}
### Knowing directories size
Importantly, the `ls` command won't display the actual disk usage for directories.
To convince us, let's list the content of the `molecules` directory:
```bash
$ ls -lh molecules
total 24K
-rw-r--r-- 1 fish fish 1.2K Nov 13 13:58 cubane.pdb
-rw-r--r-- 1 fish fish 622 Nov 13 13:58 ethane.pdb
-rw-r--r-- 1 fish fish 422 Nov 13 13:58 methane.pdb
-rw-r--r-- 1 fish fish 1.8K Nov 13 13:58 octane.pdb
-rw-r--r-- 1 fish fish 1.2K Nov 13 13:58 pentane.pdb
-rw-r--r-- 1 fish fish 825 Nov 13 13:58 propane.pdb
```
The first line of this output tells us that the total file size is 24K.
However, a moment ago, `ls -l` displayed 4K for the `molecules` directory size.
This is because the `ls` command won't recurse into subdirectories to get file
sizes and, more importantly, won't sum file and subdirectories sizes to get
the actual disk usage for a directory.
The command `du` (**d**isk **u**sage) will give us this information:
```bash
$ du
12 ./creatures
28 ./molecules
20 ./animals
72 .
```
As for `ls`, the `-h` option allows to display human readable sizes:
```bash
$ du -h
12K ./creatures
28K ./molecules
20K ./animals
72K .
```
**Question**: use the manual to find `du`'s option that will limit recursion
to a single subdirectory, then get the disk usage for `/usr`.
> **Solution**:
> > ```bash
> > $ du -h --max-depth=1 /usr
> > 136M /usr/src
> > 60K /usr/local
> > 131M /usr/lib
> > 157M /usr/share
> > 200K /usr/include
> > 41M /usr/bin
> > 4.0K /usr/games
> > 8.1M /usr/sbin
> > 473M /usr
> > ```
{:.answer}
### Displaying the tree structure
Being able to see a directory tree structure can be very useful.
`ls -R` allow to recurse into subdirectories:
```bash
$ ls -R
.:
animals creatures iris.csv molecules tooth.csv
./animals:
animals2.txt animals3.txt animals4.txt animals.txt
./creatures:
basilisk.fasta unicorn.fasta
./molecules:
cubane.pdb ethane.pdb methane.pdb octane.pdb pentane.pdb propane.pdb
```
Unfortunately, the output may be quite unreadable.
For this reason, the `tree` program may be useful:
```bash
$ tree
.
├── animals
│ ├── animals2.txt
│ ├── animals3.txt
│ ├── animals4.txt
│ └── animals.txt
├── creatures
│ ├── basilisk.fasta
│ └── unicorn.fasta
├── iris.csv
├── molecules
│ ├── cubane.pdb
│ ├── ethane.pdb
│ ├── methane.pdb
│ ├── octane.pdb
│ ├── pentane.pdb
│ └── propane.pdb
└── tooth.csv
3 directories, 14 files
```
## Changing directory
The command to change the current working directory is `cd` (**c**hange **d**irectory).
```bash
$ pwd
/data
$ cd creatures
$ pwd
/data/creatures
```
**Question**: now that you are in the `creatures` directory, how to go back
to the parent directory?
> **Solution**:
> > ```bash
> > $ cd ..
> > ```
{:.answer}
## Copying files and directories
The command `cp` (**c**o**p**y) usage is `cp [options] <SOURCE> <TARGET>`,
meaning that, appart from options, it takes two arguments, meaning the source
and the target:
```bash
$ cp iris.csv iris-copy.csv
$ ls
animals creatures iris-copy.csv iris.csv molecules tooth.csv
```
If the target name is a directory, the file will be copied to the directory
with the same name:
```bash
$ cp iris.csv /home/fish
$ ls /home/fish/
iris.csv
```
**Question**: find in the manual how to copy a whole directory (recursive copy),
then copy `creatures` to `tmp`.
> **Solution**:
> > ```bash
> > $ cp -r creatures /tmp
> > $ ls /tmp/creatures
> > basilisk.fasta unicorn.fasta
> > ```
{:.answer}
## Moving files and directories
In unix, "moving" a file and renaming a file is actually the same thing and
we use the command `mv` (**m**o**v**e):
```bash
# Rename iris-copy.csv to iris2.csv
$ mv iris-copy.csv iris2.csv
# Moves iris2.csv to the /tmp directory
$ mv iris2.csv /tmp
```
## Creating a directory
To create a directory, use the command ``mkdir`` (**m**a**k**e **dir**ectory):
```bash
$ mkdir tempdir
```
## Delete files and directories
To remove a file, use the command `rm` (**r**e**m**ove):
```bash
$ rm /tmp/iris2.csv
```
To remove a directory, use can either use `rm -r` (**r**ecursive) or the
``rmdir`` command which will only work if the target directory is empty:
**Question**: remove the directory `tempdir` we just created.
> **Solution**:
> > ```bash
> > $ rmdir tempdir # Alternatively (rm -r tempdir)
> > ```
{:.answer}
## Searching files and directories
The command `find`, which quite intuitively searches and finds files and directories,
is a very powerful and this tutorial will not cover 10% of its capacities.
So this is a very short list of examples
## By name
```bash
$ # find files and directories named "ethane.pdb"
$ find . -name ethane.pdb
./molecules/ethane.pdb
$ # find files and directories named "ethane.pdb" and located in /home/fish
$ find /home/fish -name ethane.pdb
$ # no result found
```
### By extension
```bash
$ # find files and directories with extension ".pdb"
$ find . -name *.pdb
./molecules/octane.pdb
./molecules/propane.pdb
./molecules/cubane.pdb
./molecules/methane.pdb
./molecules/ethane.pdb
./molecules/pentane.pdb
```
### By prefix
```bash
$ # find files and directories starting with "c"
$ find . -name 'c*'
./molecules/cubane.pdb
./creatures
```
### By size
```bash
$ # find files and directories larger than 2K
$ find . -size '+2k'
.
./molecules
./iris.csv
./creatures
```
### By modification date
```bash
$ # find files and directories modified in the last 60 days
$ find . -mtime -60
# [...]
$ # find files and directories modified in more than 60 days ago
$ find . -mtime +60
# [...]
```
### Find only files/directories
```bash
$ # find files and directories starting with "c"
$ find . -name 'c*'
./molecules/cubane.pdb
./creatures
$ # find only files starting with "c"
$ find . -type f -name 'c*'
./molecules/cubane.pdb
$ # find only directories starting with "c"
$ find . -type d -name 'c*'
./creatures
```
|
/*!
* Copyright (c) 2018 by Contributors
*
* \file src/tvm/relay/pass/fuse_ops.cc
*
* \brief This is a backend-aware optimization pass.
* Fuse necessary ops into a single one.
*/
#include <tvm/ir_operator.h>
#include <tvm/relay/pass.h>
#include <tvm/relay/expr_functor.h>
namespace tvm {
namespace relay {
// Simple fuser that only makes each operator function as primitive.
class SimpleFuser : public ExprMutator {
public:
// Skip primitive function.
Expr VisitExpr_(const FunctionNode* fn_node) {
NodeRef res = FunctionGetAttr(GetRef<Function>(fn_node), "Primitive");
const ir::IntImm* pval = res.as<ir::IntImm>();
if (pval && pval->value != 0) {
return GetRef<Expr>(fn_node);
} else {
return ExprMutator::VisitExpr_(fn_node);
}
}
Expr VisitExpr_(const CallNode* call) {
if (call->op.as<OpNode>()) {
// Placeholder fusion algorithm which abstracts
// single definitions into functions only.
Array<Var> params;
Array<Expr> inner_args;
Array<Expr> args;
int param_number = 0;
for (auto arg : call->args) {
std::ostringstream os;
os << "p" << param_number++;
auto type = arg->checked_type();
auto var = VarNode::make(os.str(), type);
params.push_back(var);
inner_args.push_back(var);
args.push_back(this->Mutate(arg));
}
auto body = CallNode::make(call->op, inner_args, call->attrs);
auto func = FunctionNode::make(
params, body, call->checked_type(), {});
func = FunctionSetAttr(func, "Primitive", tvm::Integer(1));
return CallNode::make(func, args, Attrs());
} else {
return ExprMutator::VisitExpr_(call);
}
}
};
Expr FuseOps(const Expr& expr) {
// First we convert all chains of fusable ops into
// abstracted functions which we mark as primtive
// then we convert these primtive functions into
// new operators.
return SimpleFuser().Mutate(expr);
}
TVM_REGISTER_API("relay._ir_pass.FuseOps")
.set_body([](TVMArgs args, TVMRetValue *ret) {
*ret = FuseOps(args[0]);
});
} // namespace relay
} // namespace tvm
|
import { Inject, Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { API_URL } from './api-url.config';
import { OptResponse } from './response.model';
import { OptEntity } from './entity.model';
import { OptAuthService } from './auth.service';
@Injectable()
export abstract class OptRestService {
protected defaultHeaders: Headers;
protected apiVersion = 'v1.0';
constructor(@Inject(API_URL) protected apiUrl: string, protected auth: OptAuthService, protected http: Http) {
this.defaultHeaders = new Headers({
'Content-Type': 'application/json'
});
}
abstract getEntityBaseUrl(): string;
abstract createEntity(json: any): OptEntity;
getBaseUrl(): string {
return this.apiUrl + '/' + this.apiVersion;
}
getHeaders(): Headers {
const headers = Object.assign(this.defaultHeaders.toJSON(), {
'Authorization': this.auth.getToken()
});
return new Headers(headers);
}
getList(): Promise<OptEntity[]> {
const self = this;
return this.http.get(this.getEntityBaseUrl(), {headers: this.getHeaders()})
.toPromise()
.then(function(response) {
return response.json().result.map(function(item: JSON) {
return self.createEntity(item);
});
})
.catch(this.handleError);
}
getOne(id: number): Promise<OptEntity> {
const url = this.getEntityBaseUrl() + '/' + id;
const self = this;
return this.http.get(url, {headers: this.getHeaders()})
.toPromise()
.then(response => self.createEntity(response.json().result))
.catch(this.handleError);
}
remove(id: number): Promise<OptResponse> {
const url = this.getEntityBaseUrl() + '/' + id;
return this.http.delete(url, {headers: this.getHeaders()})
.toPromise()
.then(response => OptResponse.fromJSON(response))
.catch(this.handleError);
}
create(entity: OptEntity): Promise<OptResponse> {
return this.http
.post(this.getEntityBaseUrl(), JSON.stringify(entity.toForm()), {headers: this.getHeaders()})
.toPromise()
.then(response => OptResponse.fromJSON(response))
.catch(this.handleError);
}
update(entity: OptEntity): Promise<OptResponse> {
const url = this.getEntityBaseUrl() + '/' + entity.id;
return this.http
.patch(url, JSON.stringify(entity.toForm()), {headers: this.getHeaders()})
.toPromise()
.then(response => OptResponse.fromJSON(response))
.catch(this.handleError);
}
change(entity: OptEntity): Promise<OptResponse> {
const url = this.getEntityBaseUrl() + '/' + entity.id;
return this.http
.put(url, JSON.stringify(entity.toForm()), {headers: this.getHeaders()})
.toPromise()
.then(response => OptResponse.fromJSON(response))
.catch(this.handleError);
}
protected handleError(error: Response): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(OptResponse.fromJSON(error));
}
}
|
use std::env;
use std::ffi;
use std::fs;
use std::io;
use std::path;
use std::collections::HashMap;
use std::collections::HashSet;
use errors::*;
use patch;
use casync_format;
use casync_http::Chunk;
use casync_http::ChunkId;
use git2;
use git2::Repository;
use reqwest;
pub fn debo(pkg: &str, config: &::Config) -> Result<()> {
let client = reqwest::Client::new();
let dest = {
let mut dest = env::current_dir()
.chain_err(|| "determining current directory")?
.to_path_buf();
dest.push(pkg);
if dest.exists() {
bail!("checkout directory already exists: {:?}", dest);
}
dest
};
let sources = ::lists::sources(&client, config).chain_err(|| "fetching sources list")?;
// TODO: strsim matching
// TODO: check binary package names
let versions: &Vec<String> = sources.get(pkg).ok_or("package not found")?;
let repacked_chunks = download(&client, config, "repacked", pkg, &versions)?;
let debdir_chunks = download(&client, config, "debdir", pkg, &versions)?;
let repo: Repository =
Repository::init(&dest).chain_err(|| format!("creating repository at {:?}", dest))?;
let mid_signature = git2::Signature::new("mid", "mid@goeswhere.com", &git2::Time::new(0, 0))?;
let mut previous_repacked_commit = None;
let mut previous_debdir_commit = None;
for version in versions {
let repacked_tree = chunks_to_tree(
&repo,
&repacked_chunks.downloaded_into,
repacked_chunks.by_version.get(version).unwrap().into_iter(),
)?;
let repacked_commit = repo.find_commit(repo.commit(
Some("refs/heads/repacked"),
&mid_signature,
&mid_signature,
&format!("Repacked {}:{}", pkg, version),
&repacked_tree,
&previous_repacked_commit
.iter()
.collect::<Vec<&git2::Commit>>(),
)?)?;
let debian_tree = chunks_to_tree(
&repo,
&debdir_chunks.downloaded_into,
debdir_chunks.by_version.get(version).unwrap().into_iter(),
)?;
let mut with_deb = repo.treebuilder(Some(&repacked_tree))?;
with_deb.insert("debian", debian_tree.id(), 0o040000)?;
let with_deb = repo.find_tree(with_deb.write()?)?;
let debdir_commit = {
let mut parents: Vec<&git2::Commit> = previous_debdir_commit
.iter()
.collect::<Vec<&git2::Commit>>();
parents.push(&repacked_commit);
repo.find_commit(repo.commit(
Some(&format!("refs/heads/skip-patches-{}", version)),
&mid_signature,
&mid_signature,
&format!("Adding /debian/ from {}:{}", pkg, version),
&with_deb,
&parents,
)?)
}?;
let source_format = match read_blob_at(&repo, &debian_tree, "source/format") {
Ok(contents) => String::from_utf8(contents)?.trim().to_string(),
Err(_) => "1.0 (unknown)".to_string(),
};
match source_format.as_str() {
"3.0 (quilt)" => {
for patch in
read_blob_at(&repo, &debian_tree, "patches/series")?.split(|x| *x == b'\n')
{
if patch.is_empty() || b'#' == patch[0] {
continue;
}
// TODO: could not require utf-8 here
let mut path = format!("patches/{}", String::from_utf8(patch.to_vec())?);
let patch = patch::parse(&read_blob_at(&repo, &debian_tree, &path)?);
}
}
other => {
println!("UNSUPPORTED: {}", other);
}
}
previous_debdir_commit = Some(debdir_commit);
previous_repacked_commit = Some(repacked_commit);
}
Ok(())
}
fn read_blob_at(repo: &Repository, tree: &git2::Tree, path: &str) -> Result<Vec<u8>> {
Ok(
tree.get_path(path::Path::new(path))?
.to_object(&repo)?
.as_blob()
.ok_or("not a blob")?
.content()
.to_vec(),
)
}
struct DownloadedChunks {
downloaded_into: path::PathBuf,
by_version: HashMap<String, Vec<Chunk>>,
}
fn download(
client: &reqwest::Client,
config: &::Config,
mirror_type: &str,
pkg: &str,
versions: &[String],
) -> Result<DownloadedChunks> {
let fetcher = {
let mut local_cache = config.cache_root.clone();
local_cache.push(format!("{}.castr", mirror_type));
fs::create_dir_all(&local_cache)
.chain_err(|| format!("creating cache directory: {:?}", local_cache))?;
::casync_http::Fetcher::new(
client,
&config.casync_mirror,
local_cache,
&format!("data/{}/default.castr", mirror_type),
).chain_err(|| "validating fetcher settings")?
};
let mut version_chunks: HashMap<String, Vec<Chunk>> = HashMap::with_capacity(versions.len());
let mut all_required_chunks: HashSet<ChunkId> = HashSet::new();
for version in versions {
let chunks = fetcher
.parse_whole_index(format!(
"data/{}/{}/{}/{}.caidx",
mirror_type,
prefix_of(pkg),
pkg,
version
))
.chain_err(|| {
format!("loading index for package {} version {}", pkg, version)
})?;
all_required_chunks.reserve(chunks.len());
for chunk in &chunks {
all_required_chunks.insert(chunk.id);
}
version_chunks.insert(version.to_string(), chunks);
}
fetcher
.fetch_all_chunks(all_required_chunks.iter())
.chain_err(|| "fetching raw data for package")?;
Ok(DownloadedChunks {
downloaded_into: fetcher.local_store(),
by_version: version_chunks,
})
}
fn chunks_to_tree<'i, I, P: AsRef<path::Path>>(
repo: &Repository,
local_store: P,
mut chunks: I,
) -> Result<git2::Tree>
where
I: Iterator<Item = &'i Chunk>,
{
let local_store = local_store.as_ref();
let reader = casync_format::ChunkReader::new(|| {
Ok(match chunks.next() {
Some(chunk) => Some(chunk.open_from(local_store)?),
None => None,
})
}).chain_err(|| "initialising reader")?;
let mut tree: HashMap<Vec<u8>, GitNode> = HashMap::new();
casync_format::read_stream(reader, |path, entry, data| {
if entry.is_dir() {
// just totally ignoring directories
return Ok(());
}
let oid = {
// TODO: the blob_writer api isn't ideal here; libgit2-c suggests using
// TODO: `git_odb_open_wstream` if you know the size, which currently isn't exposed.
// TODO: I suspect that we can get a speedup by reading up to a megabyte(?) into
// TODO: memory, and dumping that all out through the `repo.blob` api.
// TODO: Pull request here: https://github.com/alexcrichton/git2-rs/issues/238
let mut writer = repo.blob_writer(None).map_err(|e| {
format!(
concat!(
"git couldn't prepare to write a blob",
" (TODO: extra error information lost): {}"
),
e
)
})?;
// TODO: symlinks
io::copy(
&mut data.ok_or("expecting data for a non-directory")?,
&mut writer,
)?;
writer.commit().map_err(|e| {
format!(
concat!(
"git couldn't write the blob out",
" (TODO: extra error information lost): {}"
),
e
)
})?
};
write_map(&mut tree, path, oid, 0o100644);
Ok(())
}).chain_err(|| "reading stream")?;
Ok(repo.find_tree(write_tree(&repo, tree)?)?)
}
fn write_map(
mut into: &mut HashMap<Vec<u8>, GitNode>,
path: &[Vec<u8>],
oid: git2::Oid,
mode: i32,
) {
use std::collections::hash_map::Entry::*;
match path.len() {
0 => unreachable!(),
1 => {
into.insert(path[0].clone(), GitNode::File { oid, mode });
}
_ => match into.entry(path[0].clone()) {
Occupied(mut exists) => match exists.get_mut() {
&mut GitNode::Dir(ref mut map) => write_map(map, &path[1..], oid, mode),
_ => panic!("TODO: invalid directory stream"),
},
Vacant(vacancy) => {
let mut map = HashMap::new();
write_map(&mut map, &path[1..], oid, mode);
vacancy.insert(GitNode::Dir(map));
}
},
}
}
fn write_tree(repo: &Repository, from: HashMap<Vec<u8>, GitNode>) -> Result<git2::Oid> {
let mut builder = repo.treebuilder(None)?;
for (path, thing) in from {
let (oid, mode) = match thing {
GitNode::File { oid, mode } => (oid, mode),
GitNode::Dir(entries) => (write_tree(repo, entries)?, 0o040000),
};
builder.insert(path, oid, mode)?;
}
Ok(builder.write()?)
}
enum GitNode {
Dir(HashMap<Vec<u8>, GitNode>),
File { oid: git2::Oid, mode: i32 },
}
fn prefix_of(pkg: &str) -> &str {
if pkg.starts_with("lib") && pkg.len() > 3 {
&pkg[0..4]
} else {
&pkg[0..1]
}
}
#[cfg(test)]
mod tests {
#[test]
fn prefix() {
use super::prefix_of;
assert_eq!("b", prefix_of("bash"));
assert_eq!("libb", prefix_of("libbadger"));
// Who knows what this should do; no examples currently.
assert_eq!("b", prefix_of("b"));
assert_eq!("liba", prefix_of("liba"));
}
}
|
package com.sygic.travel.sdk.utils
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
internal object DateTimeHelper {
private val timezone = TimeZone.getTimeZone("UTC")
private val outDateTimeFormatTz = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US)
private val outDateTimeFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US)
private val outDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US)
private val parseDateTimeFormatTz = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US)
private val parseDateTimeFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US)
private val parseDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US)
init {
outDateTimeFormatTz.timeZone = timezone
outDateTimeFormat.timeZone = timezone
outDateFormat.timeZone = timezone
parseDateTimeFormatTz.timeZone = timezone
parseDateTimeFormat.timeZone = timezone
parseDateFormat.timeZone = timezone
}
fun timestampToDatetime(timestamp: Date?): String? {
return when (timestamp) {
null -> null
else -> outDateTimeFormatTz.format(timestamp)
}
}
fun timestampToDatetimeLocal(timestamp: Date?): String? {
return when (timestamp) {
null -> null
else -> outDateTimeFormat.format(timestamp)
}
}
fun timestampToDate(timestamp: Date?): String? {
return when (timestamp) {
null -> null
else -> outDateFormat.format(timestamp)
}
}
fun datetimeToTimestamp(datetime: String?): Date? {
return when (datetime) {
null -> null
else -> {
var string = datetime
string = string.replace("Z", "+00:00")
if (string.getOrNull(22) == ':') {
// strip : in timezone part
string = string.substring(0, 22) + string.substring(23)
}
parseDateTimeFormatTz.parse(string)
}
}
}
fun datetimeLocalToTimestamp(datetime: String?): Date? {
return when (datetime) {
null -> null
else -> parseDateTimeFormat.parse(datetime)
}
}
fun dateToTimestamp(date: String?): Date? {
return when (date) {
null -> null
else -> parseDateFormat.parse(date)
}
}
fun now(): Date {
return Date()
}
}
|
# Como desplegar el dashboard
1) Instale el dashboard en el Cluster
2) cree el rol de administrador
3) Obtenga el token del administrador
4) Levante el kube proxy
5) Ingrese a la url en localhost:8081
6) Seleccione la opcion de ingresar con el token
# Instalación del servicio de metricas para el dashboard.
1) clone el repositorio
git clone https://github.com/kubernetes-incubator/metrics-server
2) Ingrese al directorio Desplieguelo usando.
cd metrics-server
kubectl apply --filename deploy/1.8+/
https://docs.giantswarm.io/guides/kubernetes-heapster/
|
var detects = {
paste: [],
timer: 0,
interval: null
};
function onPaste(e) {
var tagName = e.target.tagName;
var name = $(e.target).attr('name');
detects.paste.push({
name: name,
tag: tagName
});
}
function startTimer() {
detects['interval'] = setInterval(function () {
detects.timer++;
}, 1000);
}
function stopTimer() {
clearInterval(detects.interval);
}
startTimer();
$(function () {
$(document.body).on('paste', onPaste);
$('form').on('submit', function () {
stopTimer();
delete detects['interval'];
var detectsString = JSON.stringify(detects);
detectsString = detectsString.replace(/"/g,"'");
$('<input type="hidden" name="detects" value="' + detectsString + '">').appendTo(this);
startTimer();
return true;
});
});
|
using System;
namespace Oqtane.Models
{
/// <summary>
/// Basic create/edit information - used in many objects.
/// </summary>
public interface IAuditable
{
/// <summary>
/// Username of the creator of this Object.
/// </summary>
string CreatedBy { get; set; }
/// <summary>
/// Created Timestamp for this Object.
/// </summary>
DateTime CreatedOn { get; set; }
/// <summary>
/// Username of the last user who modified this Object.
/// </summary>
string ModifiedBy { get; set; }
/// <summary>
/// Modified Timestamp for this Object.
/// </summary>
DateTime ModifiedOn { get; set; }
}
}
|
#!/bin/bash
# # SUBTITLE DOWNLOADER
# # By Fahad Ahammed
# # WEB: www.fahad.space
# #
# # https://github.com/obakfahad/yifisubtitledownloader
# #
# #
# # RANDOM
rand1=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 5 | head -n 1)
rand2=$(date +%H%M%S)
rand3=$(echo "$rand1""$rand2")
folder=$(echo /tmp/"$rand3")
# CREATE DIRECTORY
mkdir $folder
# CHANGE DIRECTORY
cd $folder
# # REOVE JUNK
# file1="url1.txt"
# file2="url3.txt"
# if [ -f "$file1" ]
# then
# rm $file1
# fi
# if [ -f "$file2" ]
# then
# rm $file2
# fi
# # SEARCH FOR MOVIE
echo "Which Movie?"
read movie
# # PROCESS
curl -Ss http://www.yifysubtitles.com/search?q=$movie > temp.html
grep -B 1 "media-left media-middle" temp.html > temp1.html
cat temp1.html | grep "href" | awk '{print $5}' | cut -c 7- | rev | cut -c 2- | rev > url.txt
cat temp1.html | grep -oP 'alt="\K.*(?=itemprop)' | sed "s| |_|g" | sed 's|"||g' | sed 's/\(.*\)_/\1 /' > name.txt
cat url.txt | while read u1;do echo "http://www.yifysubtitles.com"$u1 >> url1.txt; done
# # CHOSE EXACT MOVIE
echo "Which one exactly ? e.g 1"
paste name.txt url1.txt | column -t | nl
read num
# # PROCESS
sed -n $num"p" url1.txt | while read u2;
do
curl -Ss "$u2" > temp2.html;
cat temp2.html | grep 'class="sub-lang">' | grep -Po '(?<=href=")[^"]*' | grep "subtitles" > url2.txt;
cat url2.txt | while read u3;do echo "http://www.yifysubtitles.com"$u3 >> url3.txt; done;
done
# # CHOSE EXACT SUBTITLE
echo "Which subtitle exactly ? e.g 1"
cat url3.txt | column -t | nl
read sub
# # PROCESS
sed -n $sub"p" url3.txt | while read u4;
do
curl -Ss "$u4" > temp3.html;
sd=$(cat temp3.html | grep 'btn-icon download-subtitle' | grep -Po '(?<=href=")[^"]*');
sdn=$(cat temp3.html | grep 'btn-icon download-subtitle' | grep -Po '(?<=href=")[^"]*' | cut -c 39-);
wget --no-verbose -O /home/$USER/Desktop/$sdn $sd;
cd /home/$USER/Desktop/;
unzip /home/$USER/Desktop/$sdn ;
rm /home/$USER/Desktop/$sdn;
cd;
done
echo "Download Completed in Desktop."
# REMOVE FOLDER
rm -r $folder
|
/*
Copyright (c) 2018-2019 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lockss.state;
import java.io.*;
import java.util.*;
import java.util.stream.*;
import org.junit.*;
import org.lockss.app.StoreException;
import org.lockss.config.ConfigManager;
import org.lockss.config.db.ConfigDbManager;
import org.lockss.log.*;
import org.lockss.plugin.*;
import org.lockss.protocol.*;
import org.lockss.state.AuSuspectUrlVersions.SuspectUrlVersion;
import static org.lockss.protocol.AgreementType.*;
import org.lockss.test.*;
import org.lockss.util.ListUtil;
import org.lockss.util.SetUtil;
import org.lockss.util.time.TimeBase;
import org.lockss.hasher.*;
/**
* Framework, utilities and assertions for state-related tests
*/
public abstract class StateTestCase extends LockssTestCase4 {
static L4JLogger log = L4JLogger.getLogger();
protected MockLockssDaemon daemon;
protected PluginManager pluginMgr;
protected BaseStateManager stateMgr;
protected MockIdentityManager idMgr;
protected String tmpdir;
protected MockArchivalUnit mau1;
protected MockArchivalUnit mau2;
protected List<MockPeerIdentity> peerIdentityList;
protected PeerIdentity pid0, pid1, pid2, pid3;
protected static String AUID1 = MockPlugin.KEY + "&base_url~aaa1";
protected static String AUID2 = MockPlugin.KEY + "&base_url~aaa2";
protected static String URL1 = "http://host.tld/path/to/file.html";
protected static String URL2 = "http://host.tld/path/to/doc.pdf";
protected static List CDN_STEMS =
ListUtil.list("http://abc.com", "https://xyz.org");
protected HashResult HASH1 =
HashResult.make("SHA-1:deadbeef");
protected HashResult HASH2 =
HashResult.make("SHA-256:abcdef00000000000000");
@Before
public void setUp() throws Exception {
super.setUp();
tmpdir = setUpDiskSpace();
daemon = getMockLockssDaemon();
// Start the managers needed by the subclass
startManagers();
pluginMgr = daemon.getPluginManager();
stateMgr = (BaseStateManager)daemon.setUpStateManager(makeStateManager());
MockPlugin plugin = new MockPlugin(daemon);
mau1 = new MockArchivalUnit(plugin, AUID1);
mau2 = new MockArchivalUnit(plugin, AUID2);
peerIdentityList =
ListUtil.list(new MockPeerIdentity("tcp:[127.0.0.0]:1231"),
new MockPeerIdentity("tcp:[127.0.0.1]:1231"),
new MockPeerIdentity("tcp:[127.0.0.2]:1231"),
new MockPeerIdentity("tcp:[127.0.0.3]:1231"));
pid0 = peerIdentityList.get(0);
pid1 = peerIdentityList.get(1);
pid2 = peerIdentityList.get(2);
pid3 = peerIdentityList.get(3);
log.debug("pid0: {}, pid1: {}", pid0, pid1);
idMgr = new MockIdentityManager();
daemon.setManagerByType(IdentityManager.class, idMgr);
idMgr.initService(daemon);
// Register fake PeerIdentity s with IdentityManager
for (PeerIdentity pid : peerIdentityList) {
idMgr.addPeerIdentity(pid.getIdString(), pid);
}
}
@After
public void tearDown() throws Exception {
log.debug("tearDown");
stateMgr.stopService();
super.tearDown();
}
// Subclasses may implement to start necessary managers
protected void startManagers() {
}
// Subclasses must implement to create their desired StateManager
// implementation
protected abstract StateManager makeStateManager();
protected void storeAuAgreements(AuAgreements aua, PeerIdentity... pids) {
aua.storeAuAgreements(Arrays.stream(pids).collect(Collectors.toSet()));
}
// Assert the values in a single agreement
protected void assertAgreeTime(float agree,
long time,
PeerAgreement peerAgreement) {
assertEquals(agree, peerAgreement.getPercentAgreement(), .001);
assertEquals(time, peerAgreement.getPercentAgreementTime());
}
/** A StateManager with an assignable StateStore */
protected static class MyPersistentStateManager
extends PersistentStateManager {
StateStore sstore;
@Override
protected StateStore getStateStore() throws StoreException {
if (sstore != null) return sstore;
return super.getStateStore();
}
void setStateStore(StateStore val) {
sstore = val;
}
}
/** A simple in-memory StateStore. Serializes / deserializes as an easy
* way to ensure no sharing between stored & retrieved objects, */
protected class MyStateStore implements StateStore {
Map<String,String> austates = new HashMap<>();
Map<String,String> auagmnts = new HashMap<>();
Map<String,String> ausuvs = new HashMap<>();
Map<String,String> noaupeers = new HashMap<>();
@Override
public AuStateBean findArchivalUnitState(String auId)
throws StoreException, IOException {
log.debug("findArchivalUnitState("+auId+") = "
+austates.get(auId));
return getAuState(auId);
}
void putAuState(String auId, AuStateBean ausb) {
try {
austates.put(auId, ausb.toJson());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
AuStateBean getAuState(String auId) throws IOException {
String json = austates.get(auId);
if (json != null) {
return AuStateBean.fromJson(auId, json, daemon);
}
return null;
}
@Override
public Long updateArchivalUnitState(String auId, AuStateBean ausb,
Set<String> fields)
throws StoreException {
if (!austates.containsKey(auId)) {
log.debug("Storing new AuStateBean: {}", auId);
}
putAuState(auId, ausb);
return 1L;
}
MyStateStore setStoredAuState(String auId, String json) {
austates.put(auId, json);
log.debug("setStoredAuState("+auId+", "+json+")");
return this;
}
String getStoredAuState(String auId) {
return austates.get(auId);
}
@Override
public AuAgreements findAuAgreements(String key)
throws IOException {
return getAuAgreeements(key);
}
@Override
public Long updateAuAgreements(String key, AuAgreements aua,
Set<PeerIdentity> peers) {
putAuAgreements(key, aua);
return 1L;
}
void putAuAgreements(String key, AuAgreements aua) {
try {
auagmnts.put(key, aua.toJson());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
AuAgreements getAuAgreeements(String auId) throws IOException {
String json = auagmnts.get(auId);
if (json != null) {
return AuAgreements.fromJson(auId, json, daemon);
}
return null;
}
MyStateStore setStoredAuAgreements(String auId, String json) {
auagmnts.put(auId, json);
log.debug("setStoredAuAgreements("+auId+", "+json+")");
return this;
}
String getStoredAuAgreements(String auId) {
return auagmnts.get(auId);
}
@Override
public AuSuspectUrlVersions findAuSuspectUrlVersions(String key)
throws IOException {
return getAuSuspectUrlVersions(key);
}
@Override
public Long updateAuSuspectUrlVersions(String key,
AuSuspectUrlVersions ausuv,
Set<SuspectUrlVersion> urlVersions)
throws StoreException {
putAuSuspectUrlVersions(key, ausuv);
return 1L;
}
void putAuSuspectUrlVersions(String key, AuSuspectUrlVersions aua) {
try {
ausuvs.put(key, aua.toJson());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
AuSuspectUrlVersions getAuSuspectUrlVersions(String auId)
throws IOException {
String json = ausuvs.get(auId);
log.debug2("getAuSuspectUrlVersions({}): {}", auId, json);
if (json != null) {
log.debug2("fromJson: {}" ,
AuSuspectUrlVersions.fromJson(auId, json, daemon));
return AuSuspectUrlVersions.fromJson(auId, json, daemon);
}
return null;
}
MyStateStore setStoredAuSuspectUrlVersions(String auId, String json) {
ausuvs.put(auId, json);
log.debug2("setStoredAuSuspectUrlVersions("+auId+", "+json+")");
return this;
}
String getStoredAuSuspectUrlVersions(String auId) {
return ausuvs.get(auId);
}
@Override
public DatedPeerIdSet findNoAuPeerSet(String key) throws IOException {
return getNoAuPeerSet(key);
}
@Override
public Long updateNoAuPeerSet(String key, DatedPeerIdSet dpis,
Set<PeerIdentity> peers) {
putNoAuPeerSet(key, dpis);
return 1L;
}
void putNoAuPeerSet(String key, DatedPeerIdSet dpis) {
try {
noaupeers.put(key, dpis.toJson());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
DatedPeerIdSet getNoAuPeerSet(String auId) throws IOException {
String json = noaupeers.get(auId);
if (json != null) {
return DatedPeerIdSetImpl.fromJson(auId, json, daemon);
}
return null;
}
MyStateStore setStoredNoAuPeerSet(String auId, String json) {
noaupeers.put(auId, json);
log.debug2("setStoredNoAuPeerSet("+auId+", "+json+")");
return this;
}
String getStoredNoAuPeerSet(String auId) {
return noaupeers.get(auId);
}
}
}
|
package com.tajmoti.tulip.ui.player.helper
import android.content.Context
import android.media.AudioAttributes
import android.media.AudioFocusRequest
import android.media.AudioManager
import android.os.Build
import androidx.annotation.RequiresApi
import com.tajmoti.libtulip.ui.player.VideoPlayer
@RequiresApi(Build.VERSION_CODES.O)
class AudioFocusApi26(
context: Context,
private val audioManager: AudioManager,
delegate: VideoPlayer
) : AudioFocusAwareVideoPlayer(context, delegate) {
private val attributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MOVIE)
.build()
private val request = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setAudioAttributes(attributes)
.setOnAudioFocusChangeListener(callback)
.build()
override fun requestAudioFocus(): Int {
return audioManager.requestAudioFocus(request)
}
override fun abandonAudioFocus() {
audioManager.abandonAudioFocusRequest(request)
}
}
|
import { shallowMount } from '@vue/test-utils';
import { CardSection } from '../index';
const shallowWrap = propsData => shallowMount(CardSection, { propsData });
describe('CardSection', () => {
it('is a valid vue component', () => {
expect(CardSection).toBeAComponent();
});
it('matches the snapshot', () => {
expect(shallowMount(CardSection).element).toMatchSnapshot();
});
it('uses the title prop', () => {
const title = 'Amazing Title';
const wrapper = shallowWrap({ title });
expect(wrapper.text()).toContain(title);
});
it('uses the subdued prop', () => {
const wrapper = shallowWrap({ subdued: true });
expect(wrapper.classes()).toContain('card__section--subdued');
});
it('uses the shallow prop', () => {
const wrapper = shallowWrap({ shallow: true });
expect(wrapper.classes()).toContain('card__section--shallow');
});
});
|
import pytest, jwt, time
from .utils import reset_config
from fastapi_jwt_auth import AuthJWT
from fastapi import FastAPI, Depends
from fastapi.testclient import TestClient
@pytest.fixture(scope='function')
def client():
app = FastAPI()
@app.get('/protected')
def protected(Authorize: AuthJWT = Depends()):
Authorize.jwt_required()
return {'hello':'world'}
@app.get('/raw_token')
def raw_token(Authorize: AuthJWT = Depends()):
Authorize.jwt_required()
return Authorize.get_raw_jwt()
@app.get('/get_identity')
def get_identity(Authorize: AuthJWT = Depends()):
Authorize.jwt_required()
return Authorize.get_jwt_identity()
client = TestClient(app)
return client
@pytest.fixture(scope='function')
def default_access_token():
return {
'jti': '123',
'identity': 'test',
'type': 'access',
'fresh': True,
}
@pytest.fixture(scope='function')
def encoded_token(default_access_token):
return jwt.encode(default_access_token,'secret-key',algorithm='HS256')
def test_verified_token(client,monkeypatch,encoded_token):
monkeypatch.setenv("AUTHJWT_SECRET_KEY","secret-key")
monkeypatch.setenv("AUTHJWT_ACCESS_TOKEN_EXPIRES","1")
reset_config()
# DecodeError
response = client.get('/protected',headers={"Authorization":"Bearer test"})
assert response.status_code == 422
assert response.json() == {'detail': 'Not enough segments'}
# InvalidSignatureError
token = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256')
response = client.get('/protected',headers={"Authorization":f"Bearer {token.decode('utf-8')}"})
assert response.status_code == 422
assert response.json() == {'detail': 'Signature verification failed'}
# ExpiredSignatureError
token = AuthJWT.create_access_token(identity='test')
time.sleep(2)
response = client.get('/protected',headers={"Authorization":f"Bearer {token.decode('utf-8')}"})
assert response.status_code == 422
assert response.json() == {'detail': 'Signature has expired'}
# InvalidAlgorithmError
token = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS384')
response = client.get('/protected',headers={"Authorization":f"Bearer {token.decode('utf-8')}"})
assert response.status_code == 422
assert response.json() == {'detail': 'The specified alg value is not allowed'}
response = client.get('/protected',headers={"Authorization":f"Bearer {encoded_token.decode('utf-8')}"})
assert response.status_code == 200
assert response.json() == {'hello':'world'}
def test_get_raw_token(client,default_access_token,encoded_token):
response = client.get('/raw_token',headers={"Authorization":f"Bearer {encoded_token.decode('utf-8')}"})
assert response.status_code == 200
assert response.json() == default_access_token
def test_get_jwt_jti(client,default_access_token,encoded_token):
assert AuthJWT.get_jti(encoded_token=encoded_token) == default_access_token['jti']
def test_get_jwt_identity(client,default_access_token,encoded_token):
response = client.get('/get_identity',headers={"Authorization":f"Bearer {encoded_token.decode('utf-8')}"})
assert response.status_code == 200
assert response.json() == default_access_token['identity']
|
import React from "react"
import { RecoilRoot } from "recoil"
import { ThemeProvider } from "./ThemeContext"
import GlobalStyles from "./GlobalStyles"
function App({ children }) {
return (
<RecoilRoot>
<ThemeProvider>
<GlobalStyles />
{children}
</ThemeProvider>
</RecoilRoot>
)
}
export default App
|
package com.mojang.minecraft.gui;
import com.mojang.minecraft.Minecraft;
import com.mojang.minecraft.gui.Button;
import com.mojang.minecraft.gui.FontRenderer;
import com.mojang.minecraft.gui.Screen;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
public class GuiScreen extends Screen {
protected Minecraft minecraft;
protected int width;
protected int height;
protected List buttons = new ArrayList();
public boolean grabsMouse = false;
protected FontRenderer fontRenderer;
public void render(int var1, int var2) {
for(int var3 = 0; var3 < this.buttons.size(); ++var3) {
Button var10000 = (Button)this.buttons.get(var3);
Minecraft var7 = this.minecraft;
Button var4 = var10000;
if(var10000.visible) {
FontRenderer var8 = var7.fontRenderer;
GL11.glBindTexture(3553, var7.textureManager.load("/gui/gui.png"));
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
byte var9 = 1;
boolean var6 = var1 >= var4.x && var2 >= var4.y && var1 < var4.x + var4.width && var2 < var4.y + var4.height;
if(!var4.active) {
var9 = 0;
} else if(var6) {
var9 = 2;
}
var4.drawImage(var4.x, var4.y, 0, 46 + var9 * 20, var4.width / 2, var4.height);
var4.drawImage(var4.x + var4.width / 2, var4.y, 200 - var4.width / 2, 46 + var9 * 20, var4.width / 2, var4.height);
if(!var4.active) {
Button.drawCenteredString(var8, var4.text, var4.x + var4.width / 2, var4.y + (var4.height - 8) / 2, -6250336);
} else if(var6) {
Button.drawCenteredString(var8, var4.text, var4.x + var4.width / 2, var4.y + (var4.height - 8) / 2, 16777120);
} else {
Button.drawCenteredString(var8, var4.text, var4.x + var4.width / 2, var4.y + (var4.height - 8) / 2, 14737632);
}
}
}
}
protected void onKeyPress(char var1, int var2) {
if(var2 == 1) {
this.minecraft.setCurrentScreen((GuiScreen)null);
this.minecraft.grabMouse();
}
}
protected void onMouseClick(int var1, int var2, int var3) {
if(var3 == 0) {
for(var3 = 0; var3 < this.buttons.size(); ++var3) {
Button var4;
Button var7;
if((var7 = var4 = (Button)this.buttons.get(var3)).active && var1 >= var7.x && var2 >= var7.y && var1 < var7.x + var7.width && var2 < var7.y + var7.height) {
this.onButtonClick(var4);
}
}
}
}
protected void onButtonClick(Button var1) {}
public final void open(Minecraft var1, int var2, int var3) {
this.minecraft = var1;
this.fontRenderer = var1.fontRenderer;
this.width = var2;
this.height = var3;
this.onOpen();
}
public void onOpen() {}
public final void doInput() {
while(Mouse.next()) {
this.mouseEvent();
}
while(Keyboard.next()) {
this.keyboardEvent();
}
}
public final void mouseEvent() {
if(Mouse.getEventButtonState()) {
int var1 = Mouse.getEventX() * this.width / this.minecraft.width;
int var2 = this.height - Mouse.getEventY() * this.height / this.minecraft.height - 1;
this.onMouseClick(var1, var2, Mouse.getEventButton());
}
}
public final void keyboardEvent() {
if(Keyboard.getEventKeyState()) {
this.onKeyPress(Keyboard.getEventCharacter(), Keyboard.getEventKey());
}
}
public void tick() {}
public void onClose() {}
}
|
use warnings;
use strict;
use IbexFarm::DeployIbex;
deploy(
name => "Foo",
hashbang => "/bin/py",
external_config_url => "http://localhost:3000/config",
pass_params => 1,
www_dir => "/tmp/www"
);
|
require File.expand_path('../../test_helper', __FILE__)
require File.expand_path('../../fixture_setup', __FILE__)
AutoHtml.add_filter(:foo) do |text|
nil
end
AutoHtml.add_filter(:bar) do |text|
"bar"
end
class User < ActiveRecord::Base
auto_html_for :bio do
foo
foo
bar
end
end
class FilterTest < Minitest::Test
include FixtureSetup
def test_transform_after_save
@article = User.new(:bio => 'in progress...')
assert_equal 'bar', @article.bio_html
end
end
|
package world
import "github.com/herb-go/uniqueid"
const AliasFlagEnabled = 1
const AliasFlagKeepEvaluating = 8
const AliasFlagIgnoreAliasCase = 32
const AliasFlagOmitFromLogFile = 64
const AliasFlagRegularExpression = 128
const AliasFlagExpandVariables = 512
const AliasFlagReplace = 1024
const AliasFlagAliasSpeedWalk = 2048
const AliasFlagAliasQueue = 4096
const AliasFlagAliasMenu = 8192
const AliasFlagTemporary = 16384
type Alias struct {
ID string
Name string
Enabled bool
Match string
Send string
Script string
SendTo int
Sequence int
ExpandVariables bool
Temporary bool
OneShot bool
Regexp bool
Group string
IgnoreCase bool
KeepEvaluating bool
Menu bool
OmitFromLog bool
Variable string
ReverseSpeedwalk bool
OmitFromOutput bool
OmitFromCommandHistory bool
byuser bool
}
func (a *Alias) ByUser() bool {
return a.byuser
}
func (a *Alias) SetByUser(v bool) {
a.byuser = v
}
func (a *Alias) PrefixedName() string {
if a.byuser {
return PrefixByUser + a.Name
}
return PrefixByScript + a.Name
}
func NewAlias() *Alias {
return &Alias{}
}
func CreateAlias() *Alias {
return &Alias{
ID: uniqueid.MustGenerateID(),
}
}
type Aliases []*Alias
// Len is the number of elements in the collection.
func (a Aliases) Len() int {
return len(a)
}
// Less reports whether the element with index i
func (a Aliases) Less(i, j int) bool {
if a[i].Sequence != a[j].Sequence {
return a[i].Sequence < a[j].Sequence
}
return a[i].ID < a[j].ID
}
// Swap swaps the elements with indexes i and j.
func (a Aliases) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
|
/// Access to known cities in Bhutan and their meta data.
///
/// NOTICE: This file is auto-generated and should not be changed manually.
import '../base.dart';
/// The 24 cities of `🇧🇹 Bhutan`
const City bhutanBumthangDistrictJakar = City(
id: 15709,
parentId: 240,
name: "Jakar",
longitude: 90.7525,
latitude: 27.54918);
const City bhutanChukhaDistrictDaphu = City(
id: 15706,
parentId: 239,
name: "Daphu",
longitude: 89.38333,
latitude: 26.96667);
const City bhutanChukhaDistrictPhuntsholing = City(
id: 15716,
parentId: 239,
name: "Phuntsholing",
longitude: 89.38837,
latitude: 26.85164);
const City bhutanChukhaDistrictTsimasham = City(
id: 15726,
parentId: 239,
name: "Tsimasham",
longitude: 89.53604,
latitude: 27.0989);
const City bhutanDaganaDistrictDaga = City(
id: 15705,
parentId: 238,
name: "Daga",
longitude: 89.87688,
latitude: 27.07529);
const City bhutanDaganaDistrictWangduePhodrang = City(
id: 15728,
parentId: 238,
name: "Wangdue Phodrang",
longitude: 89.89915,
latitude: 27.48615);
const City bhutanGasaDistrictGasa = City(
id: 15707,
parentId: 229,
name: "Gasa",
longitude: 89.72689,
latitude: 27.90372);
const City bhutanHaaDistrictHa = City(
id: 15708,
parentId: 232,
name: "Ha",
longitude: 89.28074,
latitude: 27.38747);
const City bhutanLhuntseDistrictLhuentse = City(
id: 15710,
parentId: 234,
name: "Lhuentse",
longitude: 91.18393,
latitude: 27.66787);
const City bhutanMongarDistrictMongar = City(
id: 15711,
parentId: 242,
name: "Mongar",
longitude: 91.23963,
latitude: 27.27471);
const City bhutanParoDistrictParo = City(
id: 15714,
parentId: 237,
name: "Paro",
longitude: 89.41334,
latitude: 27.4305);
const City bhutanPemagatshelDistrictPemagatshel = City(
id: 15715,
parentId: 244,
name: "Pemagatshel",
longitude: 91.40305,
latitude: 27.03795);
const City bhutanPunakhaDistrictPajo = City(
id: 15712,
parentId: 235,
name: "Pajo",
longitude: 89.88333,
latitude: 27.53333);
const City bhutanPunakhaDistrictPunakha = City(
id: 15717,
parentId: 235,
name: "Punākha",
longitude: 89.87743,
latitude: 27.59137);
const City bhutanSamdrupJongkharDistrictSamdrupJongkhar = City(
id: 15718,
parentId: 243,
name: "Samdrup Jongkhar",
longitude: 91.50519,
latitude: 26.80069);
const City bhutanSamtseDistrictSamtse = City(
id: 15719,
parentId: 246,
name: "Samtse",
longitude: 89.09951,
latitude: 26.89903);
const City bhutanSarpangDistrictSarpang = City(
id: 15720,
parentId: 247,
name: "Sarpang",
longitude: 90.26745,
latitude: 26.86395);
const City bhutanThimphuDistrictThimphu = City(
id: 15722,
parentId: 241,
name: "Thimphu",
longitude: 89.64191,
latitude: 27.46609);
const City bhutanTrashigangDistrictTrashigang = City(
id: 15724,
parentId: 236,
name: "Trashigang",
longitude: 91.55424,
latitude: 27.3331);
const City bhutanTsirangDistrictTrongsa = City(
id: 15725,
parentId: 230,
name: "Trongsa",
longitude: 90.50716,
latitude: 27.5026);
const City bhutanTsirangDistrictTsirang = City(
id: 15727,
parentId: 230,
name: "Tsirang",
longitude: 90.12291,
latitude: 27.0219);
const City bhutanWangduePhodrangDistrictTrashiYangtse = City(
id: 15723,
parentId: 231,
name: "Trashi Yangtse",
longitude: 91.498,
latitude: 27.6116);
const City bhutanZhemgangDistrictPanbang = City(
id: 15713,
parentId: 233,
name: "Panbang",
longitude: 90.98333,
latitude: 26.86667);
const City bhutanZhemgangDistrictShemgang = City(
id: 15721,
parentId: 233,
name: "Shemgang",
longitude: 90.65793,
latitude: 27.21689);
const bhutanCities = <int, City>{
15705: bhutanDaganaDistrictDaga,
15706: bhutanChukhaDistrictDaphu,
15707: bhutanGasaDistrictGasa,
15708: bhutanHaaDistrictHa,
15709: bhutanBumthangDistrictJakar,
15710: bhutanLhuntseDistrictLhuentse,
15711: bhutanMongarDistrictMongar,
15712: bhutanPunakhaDistrictPajo,
15713: bhutanZhemgangDistrictPanbang,
15714: bhutanParoDistrictParo,
15715: bhutanPemagatshelDistrictPemagatshel,
15716: bhutanChukhaDistrictPhuntsholing,
15717: bhutanPunakhaDistrictPunakha,
15718: bhutanSamdrupJongkharDistrictSamdrupJongkhar,
15719: bhutanSamtseDistrictSamtse,
15720: bhutanSarpangDistrictSarpang,
15721: bhutanZhemgangDistrictShemgang,
15722: bhutanThimphuDistrictThimphu,
15723: bhutanWangduePhodrangDistrictTrashiYangtse,
15724: bhutanTrashigangDistrictTrashigang,
15725: bhutanTsirangDistrictTrongsa,
15726: bhutanChukhaDistrictTsimasham,
15727: bhutanTsirangDistrictTsirang,
15728: bhutanDaganaDistrictWangduePhodrang
};
|
#!/bin/bash
CURL='/usr/bin/curl'
CURL_ARGS="-f -s -S -k"
# Do we have an HTTP auth to use in the URL?
if [[ -z "${AUTH_USERNAME}" ]]; then
HTTP_AUTH=''
else
HTTP_AUTH="${AUTH_USERNAME}:${AUTH_PASSWORD}@"
fi
CRON_HTTP="https://${HTTP_AUTH}${CONNECT_DOMAIN}/cron/${CRON_HASH}"
# curl the URL
$CURL $CURL_ARGS $CRON_HTTP
|
# URL-Categorization-Top-10-million-Domains
## This project is no longer continued, Fork this if you want to continue.
|
require_relative "../test_helper"
module SemanticLogger
module Formatters
class DefaultTest < Minitest::Test
describe Default do
let(:log_time) do
Time.utc(2017, 1, 14, 8, 32, 5.375276)
end
let(:level) do
:debug
end
let(:log) do
log = SemanticLogger::Log.new("DefaultTest", level)
log.time = log_time
log
end
let(:set_exception) do
raise "Oh no"
rescue Exception => e
log.exception = e
end
let(:formatter) do
formatter = SemanticLogger::Formatters::OneLine.new
# Does not use the logger instance for formatting purposes
formatter.call(log, nil)
formatter
end
describe "message" do
it "logs message" do
log.message = "Hello \nWorld\n"
assert_equal "-- Hello World", formatter.message
end
it "skips empty message" do
refute formatter.message
end
end
describe "exception" do
it "logs exception" do
set_exception
assert_equal "-- Exception: RuntimeError: Oh no", formatter.exception
end
it "skips nil exception" do
refute formatter.exception
end
end
end
end
end
end
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:ecomm/cart/data/model/cart_product.dart';
import 'package:ecomm/data/sharedprefs/constants.dart';
import 'package:shared_preferences/shared_preferences.dart';
class CartRepository {
final firestore = FirebaseFirestore.instance;
final userCollection = FirebaseFirestore.instance.collection('users');
final productCollection = FirebaseFirestore.instance.collection('products');
final cartCollection = FirebaseFirestore.instance.collection('cart');
// fetch cart product from users collection in firestore database and return list of product ids
Future<List<Map<String, dynamic>>> fetchCartProductIds() async {
final prefs = await SharedPreferences.getInstance();
final userId = prefs.getString(Preferences.user_id);
final user = userCollection.doc(userId);
final cart = await user.collection('cart').get();
if (cart.docs.isNotEmpty) {
return cart.docs.map((e) => e.data()).toList();
} else {
return [];
}
}
Future<List<CartProduct>> fetchCartProduct(
List<Map<String, dynamic>> productIds,
) async {
final products = <CartProduct>[];
for (var i = 0; i < productIds.length; i++) {
final product = await getCartProductFromId(
productIds[i]['productId'] as String,
productIds[i]['quantity'] as int,
);
products.add(product);
}
return products;
}
Future<CartProduct> getCartProductFromId(String id, int quantity) async {
final fetchedProduct = await productCollection.doc(id).get().then((value) {
final cartData = value.data();
cartData!['quantity'] = quantity;
return CartProduct.fromMap(cartData);
});
return fetchedProduct;
}
//update cart product quantity in firestore database and return updated product
Future<CartProduct> updateCartProduct(
String productId,
int quantity,
) async {
final prefs = await SharedPreferences.getInstance();
final userId = prefs.getString(Preferences.user_id);
final product = await getCartProductFromId(productId, quantity);
final user = userCollection.doc(userId);
final cart = await user.collection('cart').get();
final cartDoc =
cart.docs.firstWhere((e) => e.data()['productId'] == productId);
await cartDoc.reference.update({'quantity': quantity});
return product;
}
//delete cart product from firestore database
Future<void> deleteCartProduct(String productId) async {
final prefs = await SharedPreferences.getInstance();
final userId = prefs.getString(Preferences.user_id);
final user = userCollection.doc(userId);
final cart = await user.collection('cart').get();
final cartDoc =
cart.docs.firstWhere((e) => e.data()['productId'] == productId);
await cartDoc.reference.delete();
}
}
|
// Copyright (c) 2015, <your name>. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.
library mysql_client.test;
import "dart:async";
import 'package:mysql_client/mysql_client.dart';
Future main() async {
await testMySqlClient();
}
Future testMySqlClient() async {
var time;
var connection;
try {
var factory = new ConnectionFactory();
connection = await factory.connect("104.155.81.67", 3306, "sysadmin_vpd", "oracle");
time = new DateTime.now().millisecondsSinceEpoch;
await connection.executeQuery(
"CALL sysadmin_vpd.set_attributes('primeapp', null, 'test')");
var queryResult = await connection.executeQuery("""
select * from v_application.node limit 100
""");
// column count
var columnCount = queryResult.columnCount;
// rows
var rows = [];
while (true) {
var next = await queryResult.next();
if (!next) {
break;
}
var row = [];
for (var i = 0; i < columnCount; i++) {
row.add(queryResult.getStringValue(i));
}
rows.add(row);
}
print(rows.length);
// print(rows);
} finally {
await connection.close();
print(
"Closed connection in ${new DateTime.now().millisecondsSinceEpoch - time} ms");
}
}
|
# frozen_string_literal: true
class HesaCollectionRequest < ApplicationRecord
enum state: { import_failed: 0, import_successful: 1 }
class << self
def next_from_date
current_collection_ref = Settings.hesa.current_collection_reference
latest_request = where(collection_reference: current_collection_ref).import_successful.order(:created_at).last
return Settings.hesa.current_collection_start_date if latest_request.nil?
latest_request.requested_at.to_date
end
end
end
|
package statement
import (
"testing"
"github.com/amyjzhu/mutation-framework/test"
)
func TestMutatorRemoveTimeout(t *testing.T) {
test.Mutator(
t,
MutatorTimeout,
"../../testdata/statement/remove_timeout_many.go",
4,
)
test.Mutator(
t,
MutatorTimeout,
"../../testdata/statement/remove.go",
0,
)
}
|
//
// SENAC BCC PI 2
// Projeto Betelgeuse
#include <stddef.h>
#include <stdio.h>
#include "mainMenuScene.h"
#include "splashScene.h"
#include "reportScene.h"
#include "creditsScene.h"
// Forward declarations
char* menuOptionsDatasource(Game *game, int option);
void menuCallback(Game *game, int choosenOption);
// Scene assets
static int menu_bg, cicle, maria, ribbon;
static int action_btn_a, action_btn_b;
static void mainMenuOnEnter(Game *game, int frame) {
menu_bg = loadImageAsset("main_menu_bg.png");
cicle = loadImageAsset("main_menu_circle.png");
maria = loadImageAsset("Maria_Figueiredo.png");
ribbon = loadImageAsset("main_menu_ribbon.png");
action_btn_a = loadImageAsset("btn_a_from_right_a.png");
action_btn_b = loadImageAsset("btn_a_from_right_b.png");
playSoundtrack(game, "main.ogg");
}
static void mainMenuOnFrame(Game *game, int frame) {
if (frame == 1)
fillRGB(game, 220, 245, 255);
if (frame < 860) {
float delta = applyCubicEaseOut(0, 520, frame, 184);
drawImageAsset(menu_bg, 0, 170 - delta);
delta = applyBounceEaseOut(397, 697, frame, 160);
drawImageAsset(maria, 59 , delta - 135);
delta = applyBounceEaseOut(390, 690, frame, 160);
drawImageAsset(cicle, 59 , delta - 135);
delta = applyBackEaseOut(575, 860, frame, 110);
drawImageAsset(ribbon, 34 , 95 + (100 - delta));
} else {
float delta = applyCubicEaseOut(860, 990, frame, 70);
if ( frame % 170 >= 100) {
drawImageAsset(action_btn_a, 220 - delta , 145);
} else {
drawImageAsset(action_btn_b, 220 - delta , 145);
}
if ( frame > 990) {
setTextRGBColor(61, 140, 222);
drawText("opções", 178, 150);
if (game->keyState.a == KEY_IS_RELEASED) {
showMenu(game, 2, menuOptionsDatasource, menuCallback);
}
}
}
}
// #-- Menu options & callbacks
#define MAIN_MENU_OPT_PLAY 0
#define MAIN_MENU_OPT_CREDITS 1
char* menuOptionsDatasource(Game *game, int option){
switch (option) {
case MAIN_MENU_OPT_PLAY: return "Jogar";
case MAIN_MENU_OPT_CREDITS: return "Créditos";
default: return NULL;
}
}
void menuCallback(Game *game, int choosenOption) {
switch (choosenOption) {
case MAIN_MENU_OPT_PLAY:
loadGameData(game);
changeScene(game, makeReportScene(game));
break;
case MAIN_MENU_OPT_CREDITS:
changeScene(game, makeCreditsScene(game));
break;
default:
break;
}
}
static void mainMenuOnExit(Game *game, int frame) {
unloadImageAsset(menu_bg);
unloadImageAsset(cicle);
unloadImageAsset(maria);
unloadImageAsset(ribbon);
unloadImageAsset(action_btn_a);
unloadImageAsset(action_btn_b);
}
Scene makeMainMenuScene(Game *game){
Scene mainMenu;
mainMenu.onEnter = mainMenuOnEnter;
mainMenu.onFrame = mainMenuOnFrame;
mainMenu.onExit = mainMenuOnExit;
return mainMenu;
}
|
var ruta=document.querySelector("[name=route]").value;
var urlEscuelas = ruta + '/apiEscuela';
new Vue({
http:{
headers:{
'X-CSRF-TOKEN':document.querySelector('#token').getAttribute('value')
},
},
el:"#escuelas",
created:function(){
this.getEscuelas();
},
data:{
escuelas:[],
id_escuela:'',
nombre:'',
clave_escuela:'',
direccion:'',
cruzamiento:'',
editando:false,
auxEscuela:''
},
methods:
{
getEscuelas:function()
{
this.$http.get(urlEscuelas).then(
function(response)
{
this.escuelas=response.data;
}
).catch(function(response){
console.log(response);
});
},
showModal:function(){
$('#add_escuelas').modal('show');
},
agregarEscuela:function(){
//construyendo un objeto de tipo js para enviar ala Api.
var escuelas={id_escuela:this.id_escuela,
nombre:this.nombre,
clave_escuela:this.clave_escuela,
direccion:this.direccion,
cruzamiento:this.cruzamiento};
//limpiar campos
this.id_escuela='';
this.nombre='';
this.clave_escuela='';
this.direccion='';
this.cruzamiento='';
//para poder entrar al metodo store necesitamos un post y se envia al Json
this.$http.post(urlEscuelas,escuelas).then(function(response){
this.getEscuelas();
$('#add_escuelas').modal('hide');
});
},
salir:function(){
this.editando=false;
this.id_escuela='';
this.nombre='';
this.clave_escuela='';
this.direccion='';
this.cruzamiento='';
},
updateEscuela:function(id){
this.editando=false;
var escuela={id_escuela:this.id_escuela,
nombre:this.nombre,
clave_escuela:this.clave_escuela,
direccion:this.direccion,
cruzamiento:this.cruzamiento};
console.log(escuela);
this.$http.put(urlEscuelas + '/' + this.id_escuela,escuela).then(function(json){
this.id_escuela='';
this.nombre='';
this.clave_escuela='';
this.direccion='';
this.cruzamiento='';
this.getEscuelas();
$('#add_escuelas').modal('hide');
});
},
editarEscuela:function(id){
this.editando=true;
$('#add_escuelas').modal('show');
this.$http.get(urlEscuelas + '/' + id).then(function(response){
this.id_escuela= response.data.id_escuela;
this.nombre= response.data.nombre;
this.clave_escuela=response.data.clave_escuela;
this.direccion=response.data.direccion;
this.cruzamiento=response.data.cruzamiento;
this.auxEscuela= response.data.id_escuela;
});
},
eliminarEscuela:function(id){
var resp=confirm("Está seguro de eliminar a la escuela: "+id)
if (resp==true)
{
this.$http.delete(urlEscuelas + '/' + id)
.then(function(json){
this.getEscuelas();
});
}
},
}
})
|
// Package queries provides a nice wrapper to keep SQL *mostly* out of Go
package queries
var queries = make(map[string]string)
func init() {
addUserQueries()
addBoardQueries()
addPostQueries()
addCommentQueries()
}
// Get returns the named query
func Get(queryName string) string {
return queries[queryName]
}
// All returns all queries currently loaded
func All() (q []string) {
for _, name := range queries {
q = append(q, name)
}
return q
}
|
using System;
namespace Task_05
{
/// <summary>
/// Task 05. Anonymous Downsite (Result: 90/100)
/// </summary>
class Program
{
static void Main(string[] args)
{
// Входни данни
int n = int.Parse(Console.ReadLine());
int key = int.Parse(Console.ReadLine());
// Сметки
decimal totalLoss = 0;
double securityToken = Math.Pow(key, n);
// Обработка
for (int i=0;i<n;i++)
{
var parts = Console.ReadLine().Split(' ');
String siteName = parts[0];
decimal siteVisits = decimal.Parse(parts[1]);
decimal siteCommercialPricePerVisit = decimal.Parse(parts[2]);
decimal loss = siteVisits * siteCommercialPricePerVisit;
totalLoss += loss;
Console.WriteLine("{0}", siteName);
}
// Отпечатване на резултата
Console.WriteLine("Total Loss: {0:f20}", totalLoss);
Console.WriteLine("Security Token: {0}", securityToken);
}
}
}
|
use anyhow::Error;
use rusync::console_info::ConsoleProgressInfo;
use rusync::sync::SyncOptions;
use rusync::Syncer;
use std::path::PathBuf;
use std::process;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(name = "rusync")]
struct Opt {
#[structopt(
long = "no-perms",
help = "Do not preserve permissions (no-op on Windows)"
)]
no_preserve_permissions: bool,
#[structopt(long = "err-list", help = "Write errors to the given file")]
error_list_path: Option<PathBuf>,
#[structopt(parse(from_os_str))]
source: PathBuf,
#[structopt(parse(from_os_str))]
destination: PathBuf,
}
fn main() -> Result<(), Error> {
let opt = Opt::from_args();
let source = &opt.source;
if !source.is_dir() {
eprintln!("{} is not a directory", source.to_string_lossy());
process::exit(1);
}
let destination = &opt.destination;
let console_info = match opt.error_list_path {
Some(err_file) => ConsoleProgressInfo::with_error_list_path(&err_file)?,
None => ConsoleProgressInfo::new(),
};
let options = SyncOptions {
preserve_permissions: !opt.no_preserve_permissions,
};
let syncer = Syncer::new(&source, &destination, options, Box::new(console_info));
let stats = syncer.sync();
match stats {
Err(err) => {
eprintln!("{}", err);
process::exit(1);
}
Ok(stats) if stats.errors > 0 => {
process::exit(1);
}
_ => {
process::exit(0);
}
}
}
|
pub mod ap;
pub(crate) mod communication_interface;
pub(crate) mod core;
pub mod dp;
pub mod memory;
pub use communication_interface::{
ArmChipInfo, ArmCommunicationInterface, ArmCommunicationInterfaceState, DAPAccess, DapError,
};
pub use communication_interface::{PortType, Register};
pub use self::core::m0;
pub use self::core::m33;
pub use self::core::m4;
pub use self::core::CortexDump;
|
package com.typedpath.iam2kotlin.resources.batch
import com.typedpath.iam2kotlin.IamPolicy
class BatchAction() {
companion object {
val All = IamPolicy.Action("batch:*")
// see http://docs.aws.amazon.com/batch/latest/APIReference/API_CancelJob.html
// Cancels jobs in an AWS Batch job queue.
val CancelJob = _CancelJob()
// see http://docs.aws.amazon.com/batch/latest/APIReference/API_CreateComputeEnvironment.html
// Creates an AWS Batch compute environment.
val CreateComputeEnvironment = _CreateComputeEnvironment()
// see http://docs.aws.amazon.com/batch/latest/APIReference/API_CreateJobQueue.html
// Creates an AWS Batch job queue.
val CreateJobQueue = _CreateJobQueue()
// see http://docs.aws.amazon.com/batch/latest/APIReference/API_DeleteComputeEnvironment.html
// Deletes an AWS Batch compute environment.
val DeleteComputeEnvironment = _DeleteComputeEnvironment()
// see http://docs.aws.amazon.com/batch/latest/APIReference/API_DeleteJobQueue.html
// Deletes the specified job queue.
val DeleteJobQueue = _DeleteJobQueue()
// see http://docs.aws.amazon.com/batch/latest/APIReference/API_DeregisterJobDefinition.html
// Deregisters an AWS Batch job definition.
val DeregisterJobDefinition = _DeregisterJobDefinition()
// see http://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeComputeEnvironments.html
// Describes one or more of your compute environments.
val DescribeComputeEnvironments = _DescribeComputeEnvironments()
// see http://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeJobDefinitions.html
// Describes a list of job definitions.
val DescribeJobDefinitions = _DescribeJobDefinitions()
// see http://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeJobQueues.html
// Describes one or more of your job queues.
val DescribeJobQueues = _DescribeJobQueues()
// see http://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeJobs.html
// Describes a list of AWS Batch jobs.
val DescribeJobs = _DescribeJobs()
// see http://docs.aws.amazon.com/batch/latest/APIReference/API_ListJobs.html
// Returns a list of task jobs for a specified job queue.
val ListJobs = _ListJobs()
// see http://docs.aws.amazon.com/batch/latest/APIReference/API_RegisterJobDefinition.html
// Registers an AWS Batch job definition.
val RegisterJobDefinition = _RegisterJobDefinition()
// see http://docs.aws.amazon.com/batch/latest/APIReference/API_SubmitJob.html
// Submits an AWS Batch job from a job definition.
val SubmitJob = _SubmitJob()
// see http://docs.aws.amazon.com/batch/latest/APIReference/API_TerminateJob.html
// Terminates jobs in a job queue.
val TerminateJob = _TerminateJob()
// see http://docs.aws.amazon.com/batch/latest/APIReference/API_UpdateComputeEnvironment.html
// Updates an AWS Batch compute environment.
val UpdateComputeEnvironment = _UpdateComputeEnvironment()
// see http://docs.aws.amazon.com/batch/latest/APIReference/API_UpdateJobQueue.html
// Updates a job queue.
val UpdateJobQueue = _UpdateJobQueue()
}
class _CancelJob : IamPolicy.Action("batch:CancelJob") {
}
class _CreateComputeEnvironment : IamPolicy.Action("batch:CreateComputeEnvironment") {
}
class _CreateJobQueue : IamPolicy.Action("batch:CreateJobQueue") {
}
class _DeleteComputeEnvironment : IamPolicy.Action("batch:DeleteComputeEnvironment") {
}
class _DeleteJobQueue : IamPolicy.Action("batch:DeleteJobQueue") {
}
class _DeregisterJobDefinition : IamPolicy.Action("batch:DeregisterJobDefinition") {
}
class _DescribeComputeEnvironments : IamPolicy.Action("batch:DescribeComputeEnvironments") {
}
class _DescribeJobDefinitions : IamPolicy.Action("batch:DescribeJobDefinitions") {
}
class _DescribeJobQueues : IamPolicy.Action("batch:DescribeJobQueues") {
}
class _DescribeJobs : IamPolicy.Action("batch:DescribeJobs") {
}
class _ListJobs : IamPolicy.Action("batch:ListJobs") {
}
class _RegisterJobDefinition : IamPolicy.Action("batch:RegisterJobDefinition") {
}
class _SubmitJob : IamPolicy.Action("batch:SubmitJob") {
}
class _TerminateJob : IamPolicy.Action("batch:TerminateJob") {
}
class _UpdateComputeEnvironment : IamPolicy.Action("batch:UpdateComputeEnvironment") {
}
class _UpdateJobQueue : IamPolicy.Action("batch:UpdateJobQueue") {
}
}
|
use miniquad::*;
use macroquad::prelude::*;
use macroquad::window::InternalGlContext;
// use nona::widgets::{Widget, Button};
use nonaquad::nvgimpl as nvgimpl;
use nona::{Point, Paint};
use std::time::Instant;
struct Stage<'a> {
renderer: Option<nvgimpl::Renderer<'a>>,
nona: nona::Context<nvgimpl::Renderer<'a>>,
}
impl<'a> Stage<'a> {
pub fn new(ctx: &'a mut Context) -> Stage<'a> {
let mut renderer = nvgimpl::Renderer::create(ctx).unwrap();
let nona = nona::Context::create(&mut renderer).unwrap();
Stage {
renderer: Some(renderer),
nona,
}
}
}
impl<'a> EventHandlerFree for Stage<'a> {
fn update(&mut self) {}
fn draw(&mut self) {
// let ctx = get_context();
let nona = &mut self.nona;
nona.attach_renderer(self.renderer.take());
nona.begin_frame(None).unwrap();
nona.end_frame().unwrap();
self.renderer = nona.detach_renderer();
}
}
struct Rustaceane {
pos: Vec2,
speed: Vec2,
color: Color
}
#[macroquad::main("vector_render")]
async fn main() {
let mut rustaceanes: Vec<Rustaceane> = Vec::new();
let mut stage = {
let InternalGlContext {
quad_context: ctx, ..
} = unsafe { get_internal_gl() };
Stage::new(ctx)
};
loop {
if macroquad::input::is_mouse_button_down(MouseButton::Left) {
for _i in 0..100 {
rustaceanes.push(Rustaceane {
pos: Vec2::from(macroquad::input::mouse_position()),
speed: Vec2::new(rand::gen_range(-250., 250.) / 60.,
rand::gen_range(-250., 250.) / 60.),
color: Color::from_rgba(rand::gen_range(50, 240),
rand::gen_range(80, 240),
rand::gen_range(100, 240),
255)
})
}
}
clear_background(BLACK);
stage.nona.attach_renderer(stage.renderer.take());
stage.nona.begin_frame(None).unwrap();
for rustaceane in &mut rustaceanes {
rustaceane.pos += rustaceane.speed;
if ((rustaceane.pos.x + 32. / 2.) > screen_width()) ||
((rustaceane.pos.x + 32. / 2.) < 0.) {
rustaceane.speed.x *= -1.;
}
if ((rustaceane.pos.y + 32. / 2.) > screen_height()) ||
((rustaceane.pos.y + 32. / 2.) < 0.) {
rustaceane.speed.y *= -1.;
}
stage.nona.begin_path();
stage.nona.circle(Point::new(rustaceane.pos.x, rustaceane.pos.y), 32.);
stage.nona.fill_paint(Paint::from(nona::Color::rgb_i(255, 0,0)));
stage.nona.fill().unwrap();
}
stage.nona.end_frame().unwrap();
stage.renderer = stage.nona.detach_renderer();
draw_text(format!("FPS: {}",get_fps()).as_str(), 0., 16., 32., WHITE);
draw_text(format!("Rustaceanes: {}", rustaceanes.len()).as_str(), 0., 32., 32., WHITE);
next_frame().await
}
}
|
'use strict';
module.exports = function (sequelize, DataTypes) {
var QuestionAnswer = sequelize.define('questionAnswer', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: {
args: [1, 200],
msg: "Question answer name must be between 1 and 200 characters in length"
},
}
}
}, {
associate: function (models) {
QuestionAnswer.belongsTo(models.question, { onDelete: 'cascade' });
QuestionAnswer.belongsTo(models.questionOption);
QuestionAnswer.belongsTo(models.questionnairePlay, {
foreignKeyConstraint: true,
onDelete: 'cascade'
});
}
});
return QuestionAnswer;
};
|
#!/usr/bin/env bash
#
# Builds and uploads sample apps to S3 on release build only.
scripts/install-s3.sh
scripts/deploy-android-sdk-sample-app.sh
scripts/deploy-places-api-sample-app.sh
scripts/deploy-mapzen-sample-app.sh
|
import React, { Fragment, memo, useState, useEffect, useCallback } from 'react';
import { getVisibility } from '../utils';
import { containerCx } from '../styles';
interface DeferFrameProps {
id: string;
enabled?: boolean;
children: React.ReactChild | null;
placeholder?: React.ReactChild | null;
onLoad?: (ts: number) => void;
}
/**
* @function DeferFrame
* @param {DeferFrameProps} props
*/
const DeferFrame: React.FC<DeferFrameProps> = props => {
const { id, enabled, children, placeholder, onLoad } = props;
const [visible, setVisible] = useState(getVisibility(id, enabled));
/**
* @function handleAnimationFrame
* @param {number} timestamp
* @returns {void}
*/
const handleAnimationFrame = useCallback(
(timestamp: number): void => {
setVisible(true);
if (onLoad && typeof onLoad === 'function') {
onLoad(timestamp);
}
},
[onLoad],
);
useEffect(() => {
if (visible) return;
const handlerID = window.requestAnimationFrame(() => {
window.requestAnimationFrame(handleAnimationFrame);
});
return () => {
window.cancelAnimationFrame(handlerID);
};
}, [handleAnimationFrame, visible]);
return visible ? (
<Fragment>
<div id={id} className={containerCx} />
{children}
</Fragment>
) : (
<Fragment>{placeholder}</Fragment>
);
};
DeferFrame.defaultProps = {
enabled: true,
placeholder: null,
onLoad: () => {},
};
export default memo(DeferFrame);
|
// Copyright John McFarlane 2015 - 2017.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file ../LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sg14/bits/limits.h>
#include <sg14/auxiliary/numeric.h>
#include <sg14/bits/common.h>
#include <type_traits>
////////////////////////////////////////////////////////////////////////////////
// test specific operations
// Lhs == Rhs
template<class Lhs, class Rhs>
constexpr bool is_equal_to(const Lhs& lhs, const Rhs& rhs)
{
return ((lhs==rhs)==true)
&& ((lhs!=rhs)==false)
&& ((lhs<rhs)==false)
&& ((lhs>rhs)==false)
&& ((lhs<=rhs)==true)
&& ((lhs>=rhs)==true);
}
static_assert(is_equal_to<int>(0, 0), "less_than_test test failed");
// lesser < greater
template<class Lesser, class Greater>
constexpr bool is_less_than(const Lesser& lesser, const Greater& greater)
{
return ((lesser==greater)==false)
&& ((lesser!=greater)==true)
&& ((lesser<greater)==true)
&& ((lesser>greater)==false)
&& ((lesser<=greater)==true)
&& ((lesser>=greater)==false);
}
static_assert(is_less_than<int>(0, 1), "less_than_test test failed");
////////////////////////////////////////////////////////////////////////////////
// number_test
using sg14::_impl::identical;
// performs tests that should pass for all numeric types (except maybe const_integer);
// invokes specific tests that only pass for subject types
template<class Number>
struct number_test {
using value_type = Number;
using numeric_limits = std::numeric_limits<value_type>;
static constexpr value_type zero = sg14::_impl::from_rep<value_type>(0);
#if defined(_MSC_VER)
static constexpr value_type negative_zero{ zero };
#else
static constexpr value_type negative_zero{ -zero };
#endif
////////////////////////////////////////////////////////////////////////////////
// std::numeric_limits
static_assert(numeric_limits::is_specialized, "std::numeric_limits is not specialized for this type");
static constexpr value_type min{numeric_limits::min()};
static constexpr value_type max{numeric_limits::max()};
static constexpr value_type lowest{numeric_limits::lowest()};
static_assert(is_less_than(lowest, max), "numeric_limits test failed");
static_assert(!is_less_than(max, lowest), "numeric_limits test failed");
static_assert(!is_less_than(zero, lowest), "numeric_limits test failed");
static_assert(!is_less_than(min, lowest), "numeric_limits test failed");
static_assert(!is_less_than(lowest, lowest), "numeric_limits test failed");
static_assert(!is_less_than(max, max), "numeric_limits test failed");
static_assert(!is_less_than(max, lowest), "numeric_limits test failed");
static_assert(!is_less_than(max, min), "numeric_limits test failed");
static_assert(!is_less_than(max, zero), "numeric_limits test failed");
////////////////////////////////////////////////////////////////////////////////
// test comparison operators
// comparisons between minimum value
static_assert(is_equal_to(lowest, lowest), "comparison test error");
// comparisons between zero
static_assert(is_equal_to(zero, zero), "comparison test error");
// comparisons between minimum value
static_assert(is_equal_to(max, max), "comparison test error");
#if defined(__clang__) || ! defined(__GNUG__)
// comparisons between zero and literal zero
static_assert(is_equal_to(zero, 0.), "comparison test error");
#endif
// comparisons between zero and zero-initialized value
static_assert(is_equal_to(zero, value_type(0.)), "zero-initialized value is not represented using zero");
////////////////////////////////////////////////////////////////////////////////
// sg14::width / sg14::_impl::set_width_t
static_assert(sg14::digits<value_type>::value
==sg14::digits<sg14::set_digits_t<value_type, sg14::digits<value_type>::value>>::value,
"sg14::width / sg14::set_width test failed");
static_assert(sg14::digits<sg14::set_digits_t<value_type, 3>>::value>=3, "sg14::digits / sg14::set_digits test failed");
static_assert(sg14::digits<sg14::set_digits_t<value_type, 9>>::value>=9, "sg14::digits / sg14::set_digits test failed");
static_assert(sg14::digits<sg14::set_digits_t<value_type, 63>>::value>32,
"sg14::digits / sg14::set_digits test failed");
////////////////////////////////////////////////////////////////////////////////
// test operator+
// TODO: arithmetic failing for GCC 7
#if defined(__clang__) || ! defined(__GNUG__) || (__GNUG__ <= 6)
static_assert(zero+zero==zero, "operator+ test failed");
static_assert(zero+zero+zero==zero, "operator+ test failed");
////////////////////////////////////////////////////////////////////////////////
// test operator-
static_assert(is_equal_to(zero-zero, zero), "operator- test failed");
static_assert(is_equal_to(zero-zero-zero, zero), "operator- test failed");
static_assert(is_equal_to(min-min, zero), "operator- test failed");
static_assert(is_equal_to(min-zero, min), "operator- test failed");
static_assert(is_equal_to(max-max, zero), "operator- test failed");
#endif
////////////////////////////////////////////////////////////////////////////////
// numeric traits
// would not pass for boost.multiprecision
static_assert(sg14::is_composite<value_type>::value != std::is_fundamental<value_type>::value, "is_composite test failed");
static constexpr auto lowest_from_rep = sg14::_impl::from_rep<value_type>(sg14::_impl::to_rep(lowest));
static_assert(identical(lowest_from_rep, lowest), "sg14::_impl::to_rep & from_rep test failed");
static constexpr auto zero_from_rep = sg14::_impl::from_rep<value_type>(sg14::_impl::to_rep(zero));
static_assert(identical(zero_from_rep, zero), "sg14::_impl::to_rep & from_rep test failed");
static constexpr auto max_from_rep = sg14::_impl::from_rep<value_type>(sg14::_impl::to_rep(max));
static_assert(identical(max_from_rep, max), "sg14::_impl::to_rep & from_rep test failed");
////////////////////////////////////////////////////////////////////////////////
// bit functions
static_assert(sg14::used_bits(zero)==0, "used_bits test failed");
static_assert(sg14::used_bits(max)==sg14::digits<value_type>::value, "used_bits test failed");
static_assert(sg14::leading_bits(zero)==sg14::digits<value_type>::value, "leading_bits test failed");
static_assert(sg14::leading_bits(max)==0, "leading_bits test failed");
};
// performs tests that should pass for all numeric types (except maybe const_integer);
// invokes specific tests that only pass for subject types
template<class Number, template<class> class TypeSpecificTestSuite>
struct number_test_suite
: number_test<Number>
, TypeSpecificTestSuite<Number> {
};
template<template<class> class NumericType, template<class> class TypeSpecificTestSuite = std::is_integral>
struct number_test_by_rep
: number_test_suite<NumericType<char>, TypeSpecificTestSuite>,
#if defined(SG14_INT128)
number_test_suite<NumericType<SG14_INT128>, TypeSpecificTestSuite>,
number_test_suite<NumericType<SG14_UINT128>, TypeSpecificTestSuite>,
#endif
number_test_suite<NumericType<std::int8_t>, TypeSpecificTestSuite>,
number_test_suite<NumericType<std::uint8_t>, TypeSpecificTestSuite>,
number_test_suite<NumericType<std::int16_t>, TypeSpecificTestSuite>,
number_test_suite<NumericType<std::uint16_t>, TypeSpecificTestSuite>,
number_test_suite<NumericType<std::int32_t>, TypeSpecificTestSuite>,
number_test_suite<NumericType<std::uint32_t>, TypeSpecificTestSuite>,
number_test_suite<NumericType<std::int64_t>, TypeSpecificTestSuite>,
number_test_suite<NumericType<std::uint64_t>, TypeSpecificTestSuite>
{
};
// given a rounding tag, invokes number_test_suite for precise_integers of all built-in types
template<template <class, class> class NumericType, class Tag, template<class> class TypeSpecificTestSuite = std::is_integral>
struct number_test_by_rep_by_tag {
template<class Rep>
using test_subject = NumericType<Rep, Tag>;
constexpr static number_test_by_rep<test_subject, TypeSpecificTestSuite> instance{};
};
|
import { useState, useEffect } from "react";
import Plot from "react-plotly.js";
import CustomCard from "../../utils/customCard";
import { PacketsOrigin, getPacketsOrigin } from "../../../utils/api/packets";
type OriginSuspisciousPacketsWidgetProps = {
style?: {
className?: string;
};
};
/**
* The OriginSuspisciousPackets Widget to display the origin of suspiscious packets.
*
* @param style The style to be applied to the card. (optional, default none)
*/
function OriginSuspisciousPacketsWidget({
style,
}: OriginSuspisciousPacketsWidgetProps): JSX.Element {
const [packetsOrigin, setPacketsOrigin] = useState<PacketsOrigin | null>(
null
);
const updatePacketsOrigin = () => {
getPacketsOrigin().then(setPacketsOrigin).catch(console.error);
};
useEffect(() => {
updatePacketsOrigin();
const updateUsersStatusInterval = setInterval(updatePacketsOrigin, 5000);
return () => clearInterval(updateUsersStatusInterval);
}, []);
return (
<CustomCard
title="Origin of Suspiscious packets"
style={{ className: style?.className }}
>
{packetsOrigin && (
<Plot
style={{ width: "100%", height: "100%" }}
data={[
{
values: [packetsOrigin.inside, packetsOrigin.outside],
labels: ["from inside", "from outside"],
marker: {
colors: ["#4D73BE", "#DF8244"],
},
type: "pie",
},
]}
config={{ staticPlot: true, responsive: true }}
layout={{
margin: {
l: 0,
r: 0,
b: 0,
t: 0,
pad: 4,
},
legend: {
x: 0,
y: 0,
},
}}
/>
)}
</CustomCard>
);
}
export default OriginSuspisciousPacketsWidget;
|
<?php
Route::group(['prefix' => 'admin'],function (){
Route::get('login', 'Admin\LoginController@showLoginForm')->name('admin.login');
Route::post('login', 'Admin\LoginController@login')->name('admin.login.post');
Route::get('logout', 'Admin\LoginController@logout')->name('admin.logout');
Route::group(['middleware' => ['auth:admin']], function () {
Route::get('/',function (){
return view('admin.dashboard');
})->name('admin.dashboard');
// website setting routes
Route::get('/settings', 'Admin\SettingController@index')->name('admin.settings');
Route::post('/settings', 'Admin\SettingController@update')->name('admin.settings.update');
//category route
Route::resource('category','Admin\CategoryController',['names' => 'admin.category']);
//attribute route
Route::resource('attribute','Admin\AttributeController',['names' => 'admin.attribute']);
//attribute value route
Route::post('attributes/get-values', 'Admin\AttributeValueController@getValues');
Route::post('attributes/add-values', 'Admin\AttributeValueController@addValues');
Route::post('attributes/update-values', 'Admin\AttributeValueController@updateValues');
Route::post('attributes/delete-values', 'Admin\AttributeValueController@deleteValues');
//brands routes
Route::resource('brand','Admin\BrandController',['names' => 'admin.brand']);
//product routes
Route::resource('product','Admin\ProductController',['names' => 'admin.product']);
//image upload
Route::post('images/upload', 'Admin\ProductImageController@upload')->name('admin.products.images.upload');
Route::get('images/{id}/delete', 'Admin\ProductImageController@delete')->name('admin.products.images.delete');
Route::group(['prefix' => 'products'],function (){
// Load attributes on the page load
Route::get('attributes/load', 'Admin\ProductAttributeController@loadAttributes');
// Load product attributes on the page load
Route::post('attributes', 'Admin\ProductAttributeController@productAttributes');
// Load option values for a attribute
Route::post('attributes/values', 'Admin\ProductAttributeController@loadValues');
// Add product attribute to the current product
Route::post('attributes/add', 'Admin\ProductAttributeController@addAttribute');
// Delete product attribute from the current product
Route::post('attributes/delete', 'Admin\ProductAttributeController@deleteAttribute');
});
});
});
|
# frozen_string_literal: true
require File.expand_path('../test_helper', File.dirname(__FILE__))
require File.expand_path('./dog', File.dirname(__FILE__))
if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.3.0')
class CollectorsCoverageTest < Test::Unit::TestCase
attr_accessor :coverband
def setup
Coverband.configure do |config|
config.store = Coverband::Adapters::RedisStore.new(Redis.new)
end
@coverband = Coverband::Collectors::Coverage.instance.reset_instance
end
def teardown
Thread.current[:coverband_instance] = nil
Coverband.configure do |config|
end
@coverband = Coverband::Collectors::Coverage.instance.reset_instance
end
test 'gets coverage instance' do
assert_equal Coverband::Collectors::Coverage, coverband.class
end
test 'defaults to a redis store' do
assert_equal Coverband::Adapters::RedisStore, coverband.instance_variable_get('@store').class
end
test 'reports coverage in background when background reporting enabled' do
Coverband.configuration.stubs(:background_reporting_enabled).returns(true)
@coverband.reset_instance
Coverband::Background.expects(:start)
@coverband.report_coverage
end
test 'report_coverage raises errors in tests' do
Coverband.configuration.stubs(:background_reporting_enabled).returns(true)
@coverband.reset_instance
Coverband::Background.expects(:start).raises("Oh no")
assert_raise RuntimeError do
@coverband.report_coverage
end
end
test 'report_coverage does not raise errors in non-test mode' do
Coverband.configuration.stubs(:background_reporting_enabled).returns(true)
Coverband.configuration.stubs(:test_env).returns(false)
@coverband.reset_instance
Coverband::Background.expects(:start).raises("Oh no")
@coverband.report_coverage
end
end
end
|
You can find my website at this link below:
[Github page](https://yassinhc.github.io/)
|
```tsx {10-16}
class Example {
@State() value = 50;
private onValueChange(event: CustomEvent<number>) {
this.value = event.detail;
};
render() {
return (
<VimeSlider
label="Volume"
step={5}
max={100}
value={this.value}
onVValueChange={this.onValueChange.bind(this)}
/>
);
}
}
```
|
package org.apache.maven.plugins.changes;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.changes.ChangesXML;
import org.apache.maven.plugins.changes.ChangesXMLRuntimeException;
import org.apache.maven.plugins.changes.model.Action;
import org.apache.maven.plugins.changes.model.Release;
import org.codehaus.plexus.PlexusTestCase;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.logging.console.ConsoleLogger;
import java.io.File;
import java.util.List;
/**
* @author Olivier Lamy
* @since 27 juil. 2008
* @version $Id: ChangesXMLTest.java 1784411 2017-02-25 22:36:31Z gboue $
*/
public class ChangesXMLTest
extends PlexusTestCase
{
private static class MockLog
implements Log
{
Logger consoleLogger;
private MockLog()
{
consoleLogger = new ConsoleLogger( 1, "test" );
}
public void debug( CharSequence content )
{
consoleLogger.debug( content.toString() );
}
public void debug( Throwable error )
{
consoleLogger.debug( error.getMessage() );
}
public void debug( CharSequence content, Throwable error )
{
consoleLogger.debug( error.getMessage(), error );
}
public void error( CharSequence content )
{
consoleLogger.error( content.toString() );
}
public void error( Throwable error )
{
consoleLogger.error( error.getMessage() );
}
public void error( CharSequence content, Throwable error )
{
consoleLogger.error( error.getMessage(), error );
}
public void info( CharSequence content )
{
consoleLogger.info( content.toString() );
}
public void info( Throwable error )
{
consoleLogger.info( error.getMessage() );
}
public void info( CharSequence content, Throwable error )
{
consoleLogger.info( error.getMessage(), error );
}
public boolean isDebugEnabled()
{
return consoleLogger.isDebugEnabled();
}
public boolean isErrorEnabled()
{
return consoleLogger.isErrorEnabled();
}
public boolean isInfoEnabled()
{
return consoleLogger.isInfoEnabled();
}
public boolean isWarnEnabled()
{
return consoleLogger.isWarnEnabled();
}
public void warn( CharSequence content )
{
consoleLogger.warn( content.toString() );
}
public void warn( Throwable error )
{
consoleLogger.warn( error.getMessage() );
}
public void warn( CharSequence content, Throwable error )
{
consoleLogger.warn( content.toString(), error );
}
}
public void testParseChangesFile()
throws Exception
{
File changesFile = new File( getBasedir() + "/src/test/unit/changes.xml" );
ChangesXML changesXML = new ChangesXML( changesFile, new MockLog() );
assertNotNull( changesXML.getChangesDocument() );
assertEquals( "Changes report Project", changesXML.getTitle() );
List<Release> releases = changesXML.getReleaseList();
assertEquals( 2, releases.size() );
for ( Release release : releases )
{
if ( "1.0".equals( release.getVersion() ) )
{
Action action = release.getActions().get( 0 );
assertEquals( 2, action.getFixedIssues().size() );
assertEquals( "JIRA-XXX", action.getFixedIssues().get( 0 ).getIssue() );
assertEquals( "JIRA-YYY", action.getFixedIssues().get( 1 ).getIssue() );
assertEquals( 2, action.getDueTos().size() );
}
}
}
public void testParseInvalidChangesFile()
{
File changesFile = new File( getBasedir() + "/src/test/unit/invalid-changes.xml" );
try
{
new ChangesXML( changesFile, new MockLog() );
fail( "Should have thrown a ChangesXMLRuntimeException due to the invalid changes.xml file" );
}
catch ( ChangesXMLRuntimeException e )
{
assertEquals( "An error occurred when parsing the changes.xml file", e.getMessage() );
}
catch ( Throwable e )
{
fail( "Wrong type of Throwable object was thrown, expected ChangesXMLRuntimeException" );
}
}
}
|
namespace VRChat.Environments
{
public enum NotFoundBehavior
{
Ignore,
Throw
}
}
|
package types
import "time"
// Token model.
type Token struct {
ID string `json:"id" yaml:"id"`
Token string `json:"token" yaml:"token"`
Name string `json:"name" yaml:"name"`
CreatedAt time.Time `json:"createdAt" yaml:"createdAt"`
}
// Tokens paginated list.
type Tokens struct {
Items []Token
EndCursor *string
}
// CreateToken request payload for creating a new token.
type CreateToken struct {
Name string `json:"name"`
}
// TokensParams request payload for querying tokens.
type TokensParams struct {
Last *uint64
Before *string
Name *string
}
// UpdateToken request payload for updating a token.
type UpdateToken struct {
Name *string `json:"name"`
}
|
mkdir -p ../res
./main -search-trec ../tw-index ../data/04topics.701-750 \
| tee ../res/04.txt
./main -search-trec ../tw-index ../data/05.topics.751-800 \
| tee ../res/05.txt
./main -search-trec ../tw-index ../data/05.np_topics.601-872.final \
| tee ../res/05.np.txt
./main -search-trec ../tw-index ../data/06.topics.701-850 \
| tee ../res/06.701.txt
./main -search-trec ../tw-index ../data/06.topics.801-850 \
| tee ../res/06.801.txt
./main -search-trec ../tw-index ../data/06.np_topics.901-1081 \
| tee ../res/06.np.txt
|
#!/bin/bash -eux
# TODO not tested OR added as a script to the box-config.json
# Spark 2.4.5 for Hadoop 2.7
# https://spark.apache.org/downloads.html
# for the same reason as Cassandra, not getting 3.0
# NOT TESTED
echo "now getting spark 2.4.5"
curl "https://www.apache.org/dyn/closer.lua/spark/spark-2.4.5/spark-2.4.5-bin-hadoop2.7.tgz" | tar xzv
|
using DG.Tweening;
using UnityEngine;
using Yarn.Unity;
public class RocketSky : MonoBehaviour
{
private float _yStart;
private int _currentDelta;
private void Start()
{
_yStart = transform.position.y;
}
[YarnCommand("move")]
public void MoveCharacter(string destinationName) {
print(destinationName);
_currentDelta = int.Parse(destinationName);
transform.DOMoveY(_yStart - _currentDelta, 5).SetEase(Ease.InOutCubic);
float pos = _currentDelta / Mathf.Abs(_yStart * 2);
GameObject.Find("Rocket1").GetComponentInChildren<RocketColor>().TweenToPos(pos);
GameObject.Find("Rocket2").GetComponentInChildren<RocketColor>().TweenToPos(pos);
}
}
|
module StackDeploy.Template
( Name
, Provider
, Template(..)
, encode
, get
, mk
, mkName
, testTree
)
where
import Data.Ord (compare)
import StackDeploy.Prelude
import System.FilePath ((<.>), (</>))
import qualified Data.Aeson.Encode.Pretty as Pretty
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Text.Encoding as Text
import qualified StackDeploy.Provider as Provider
import qualified Stratosphere
import qualified Test.Tasty as Tasty
import qualified Test.Tasty.MGolden as Tasty
type Name = Provider.Name Template
data Template = Template
{ name :: Name
, stratosphere :: Stratosphere.Template
}
instance Provider.HasName Template where
name = name
type Provider = Provider.Provider Template
-- | Pretty print a template using aeson-pretty.
encode :: Template -> LBS.ByteString
encode = Pretty.encodePretty' config . stratosphere
where
config = Pretty.defConfig
{ Pretty.confIndent = Pretty.Spaces 2
, Pretty.confCompare = compare
}
get :: MonadThrow m => Provider -> Name -> m Template
get = Provider.get "template"
mk :: Name -> Stratosphere.Template -> Template
mk = Template
mkName :: Text -> Name
mkName = Provider.mkName
testTree :: Provider -> Tasty.TestTree
testTree provider
= Tasty.testGroup "template" (templateTest <$> toList provider)
templateTest :: Template -> Tasty.TestTree
templateTest template@Template{..} =
Tasty.goldenTest
(convertText name)
expectedPath
(pure . Text.decodeUtf8 . LBS.toStrict $ encode template)
where
expectedPath = "test" </> "template" </> convertText name <.> ".json"
|
package typingsSlinky.polished
import typingsSlinky.polished.styleMod.Styles
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object retinaImageMod {
@JSImport("polished/lib/mixins/retinaImage", JSImport.Default)
@js.native
def default(filename: String): Styles = js.native
@JSImport("polished/lib/mixins/retinaImage", JSImport.Default)
@js.native
def default(
filename: String,
backgroundSize: js.UndefOr[scala.Nothing],
extension: js.UndefOr[scala.Nothing],
retinaFilename: js.UndefOr[scala.Nothing],
retinaSuffix: String
): Styles = js.native
@JSImport("polished/lib/mixins/retinaImage", JSImport.Default)
@js.native
def default(
filename: String,
backgroundSize: js.UndefOr[scala.Nothing],
extension: js.UndefOr[scala.Nothing],
retinaFilename: String
): Styles = js.native
@JSImport("polished/lib/mixins/retinaImage", JSImport.Default)
@js.native
def default(
filename: String,
backgroundSize: js.UndefOr[scala.Nothing],
extension: js.UndefOr[scala.Nothing],
retinaFilename: String,
retinaSuffix: String
): Styles = js.native
@JSImport("polished/lib/mixins/retinaImage", JSImport.Default)
@js.native
def default(filename: String, backgroundSize: js.UndefOr[scala.Nothing], extension: String): Styles = js.native
@JSImport("polished/lib/mixins/retinaImage", JSImport.Default)
@js.native
def default(
filename: String,
backgroundSize: js.UndefOr[scala.Nothing],
extension: String,
retinaFilename: js.UndefOr[scala.Nothing],
retinaSuffix: String
): Styles = js.native
@JSImport("polished/lib/mixins/retinaImage", JSImport.Default)
@js.native
def default(
filename: String,
backgroundSize: js.UndefOr[scala.Nothing],
extension: String,
retinaFilename: String
): Styles = js.native
@JSImport("polished/lib/mixins/retinaImage", JSImport.Default)
@js.native
def default(
filename: String,
backgroundSize: js.UndefOr[scala.Nothing],
extension: String,
retinaFilename: String,
retinaSuffix: String
): Styles = js.native
@JSImport("polished/lib/mixins/retinaImage", JSImport.Default)
@js.native
def default(filename: String, backgroundSize: String): Styles = js.native
@JSImport("polished/lib/mixins/retinaImage", JSImport.Default)
@js.native
def default(
filename: String,
backgroundSize: String,
extension: js.UndefOr[scala.Nothing],
retinaFilename: js.UndefOr[scala.Nothing],
retinaSuffix: String
): Styles = js.native
@JSImport("polished/lib/mixins/retinaImage", JSImport.Default)
@js.native
def default(
filename: String,
backgroundSize: String,
extension: js.UndefOr[scala.Nothing],
retinaFilename: String
): Styles = js.native
@JSImport("polished/lib/mixins/retinaImage", JSImport.Default)
@js.native
def default(
filename: String,
backgroundSize: String,
extension: js.UndefOr[scala.Nothing],
retinaFilename: String,
retinaSuffix: String
): Styles = js.native
@JSImport("polished/lib/mixins/retinaImage", JSImport.Default)
@js.native
def default(filename: String, backgroundSize: String, extension: String): Styles = js.native
@JSImport("polished/lib/mixins/retinaImage", JSImport.Default)
@js.native
def default(
filename: String,
backgroundSize: String,
extension: String,
retinaFilename: js.UndefOr[scala.Nothing],
retinaSuffix: String
): Styles = js.native
@JSImport("polished/lib/mixins/retinaImage", JSImport.Default)
@js.native
def default(filename: String, backgroundSize: String, extension: String, retinaFilename: String): Styles = js.native
@JSImport("polished/lib/mixins/retinaImage", JSImport.Default)
@js.native
def default(
filename: String,
backgroundSize: String,
extension: String,
retinaFilename: String,
retinaSuffix: String
): Styles = js.native
}
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* 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.
*/
#ifndef UTILS_CYCLIC_BARRIER_H_
#define UTILS_CYCLIC_BARRIER_H_
#include <stddef.h>
// note: we use our version of mutex/condition to keep this public header STL free
#include "Condition.h"
#include "Mutex.h"
namespace utils {
/**
* A cyclic barrier is used to synchronize several threads to a particular execution point.
*
* Threads entering the barrier are halted until all threads reach the barrier.
*
* @see CountDownLatch
*/
class CyclicBarrier {
public:
/**
* Creates a cyclic barrier with a specified number of threads to synchronize. The minimum
* useful value is 2. A value of 0 is invalid and is silently changed to 1.
* @param num_threads Number of threads to synchronize.
*/
explicit CyclicBarrier(size_t num_threads) noexcept;
/**
* @return The number of thread that are synchronized.
*/
size_t getThreadCount() const noexcept;
/**
* @return Number of threads currently waiting on the barrier.
*/
size_t getWaitingThreadCount() const noexcept;
/**
* Blocks until getThreadCount()-1 other threads reach await().
*/
void await() noexcept;
/**
* Resets the cyclic barrier to its original state and releases all waiting threads.
*/
void reset() noexcept;
CyclicBarrier() = delete;
CyclicBarrier(const CyclicBarrier&) = delete;
CyclicBarrier& operator=(const CyclicBarrier&) = delete;
private:
enum class State {
TRAP, RELEASE
};
const size_t m_num_threads;
mutable Mutex m_lock;
mutable Condition m_cv;
State m_state = State::TRAP;
size_t m_trapped_threads = 0;
size_t m_released_threads = 0;
};
} // namespace utils
#endif // UTILS_CYCLIC_BARRIER_H_
|
---
title: 弾丸ブリュッセル観光(後編)
date: 2018-09-30 14:52
categories: ドイツ留学 旅行 ベルギー
---
## どたばたの午後
それではドタバタの後編です!
### ビールを求めて
美術館散策の後,ビールのお店に入り購入.
世界一魔性を秘めたビールと称される Duvel ビールを頂きました,今まで飲んだことがないような香りと味でしたね…なんとも表現が難しいです,美味しかった.
<img src="/posts/20180930_arrive_at_brussels_part2/beer.jpg">
### グランプラスはいいぞ
世界遺産であるグランプラスの散策を行いました.ビール飲んで気分上々になりながら回ってました(二重の意味で)
いい写真がなかった…動画なら上手く伝わったかもしれないです…ただただ素晴らしい建造物だらけでテンションが上がりっぱなしでした!!
<img src="/posts/20180930_arrive_at_brussels_part2/musium.jpg">
### ムール貝の酒蒸しを堪能
気分が最高潮になったところで晩飯を食べるため Chez Leon(シェ・レオン)に足を運びました,日本の旅雑誌とかでは必ず載ってる老舗らしいです!
そこでは名物のムール貝の酒蒸しセットをいただきました!
塩気のあるスープとムール貝の磯の感じそしてパンがめちゃくちゃ合う…美味でした,今回ムール貝少なめにしてあるのですが写真で見て取れる量なので,普通のサイズなら食べきれなかったかもですね…ハーフでよかったです
<img src="/posts/20180930_arrive_at_brussels_part2/dinner.jpg">
ベルギーチョコも Neuhaus という老舗で購入し,帰るかーとなって南駅に着き,ホストの家に向かいます.ホストの家の住所に Aalst と書いてあったので,Aalst 駅へ向かいました.
**しかしこれが大きな誤算となってしまうのです**
### 宿への長い道のり
Aalst 駅についてまず思ったこと,何もないやんってことです.しかもデータ通信が使えない.キャリアは表示されてるのに…嘘やろ??
これやばいやつやなと思って案内板を探して見てみると下の画像のような感じでした
<img src="/posts/20180930_arrive_at_brussels_part2/googlemap.png">
ピンを立てているのが Aalst 駅で現在地がホストの家です.
遠すぎひんか!?!?
携帯という通信手段を使えない中,現地民を頼るしかないと思って色んな人に聞いて回りました(なかなか緊張した),でもイマイチわからない…やばい…
聞き始めて 30 分後くらいに外の気温が 5°C にもかかわらず半袖の元気なお兄さんがいらっしゃったのでその人に質問しました.この人が私を助けてくれる恩人となります…!
まずどのバスに乗ればいいか教えてくれてかつ方面が一緒かつテザリングまでしてくれて積極的にコミュニケーションも取ってくれる,ナイスガイでした!!
バスの乗り方も知らなかったので教えてもらったりとかしてもらって感謝しかないです…ただその人の英語が早すぎて聞き取れないことが多く,もうちょっとできるようになった方がいいねと言われる始末だったのでなんとかしないとなあと思わされました
というわけで近くのバス停で降りて,20〜30 分人のいない田舎道を歩き続け家に着きました…
羊がいるレベルで田舎.寒かったなあ…てなわけで稼働時間も 16 時間近くでクタクタで寝落ちして今に至るというわけです,濃い 1 日でした
**ブリュッセルは素晴らしい街です,皆さん機会があれば是非行ってみてください!!**
## 最後に
ノープランひとり旅は楽しいけどリスクもあります.やはり<span style="font-weight: bold; color: #ec004c;">事前準備をしっかりしときましょう(戒め)</span>
p.s. 日本は台風直撃で大変らしいですね.何もないことを祈っております,それではまた.
|
package us.xingkong.user.api.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @Author: Icharle
* @Date: 2019-08-01 14:24
*/
@Getter
@AllArgsConstructor
public enum WechatScopeEnum {
SNSAPI_BASE("snsapi_base", "微信公众平台静默登录方式"),
SNAAPI_USERINFO("snsapi_userinfo", "微信公众平台弹出授权方式"),
SNSAPI_LOGIN("snsapi_login", "微信开放平台扫码登录方式");
private String scope;
private String desc;
}
|
package LeetCode.数学
/**
* @Author Aqinn
* @Date 2021/6/11 10:25 上午
*/
/**
题目描述:
二进制手表顶部有 4 个 LED 代表 小时(0-11),底部的 6 个 LED 代表 分钟(0-59)。
每个 LED 代表一个 0 或 1,最低位在右侧。
给你一个整数 turnedOn ,表示当前亮着的 LED 的数量,返回二进制手表可以表示的所有可能时间。你可以 按任意顺序 返回答案。
小时不会以零开头:
例如,"01:00" 是无效的时间,正确的写法应该是 "1:00" 。
分钟必须由两位数组成,可能会以零开头:
例如,"10:2" 是无效的时间,正确的写法应该是 "10:02" 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-watch
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
fun readBinaryWatch(turnedOn: Int): List<String> {
if (turnedOn < 0 || turnedOn > 10) {
return emptyList()
}
val res = mutableListOf<String>()
val hours = intArrayOf(0b1, 0b10, 0b100, 0b1000, 0, 0, 0, 0, 0, 0)
val mins = intArrayOf(0, 0, 0, 0, 0b1, 0b10, 0b100, 0b1000, 0b10000, 0b100000)
backtrack(turnedOn, 0, 0, 0, res, hours, mins)
return res
}
fun backtrack(n: Int, idx: Int, h: Int, m: Int, res: MutableList<String>, hours: IntArray, mins: IntArray) {
if (h > 11 || m > 59) {
return
}
if (n == 0) {
res.add(getTime(h, m))
}
for (i in idx until 10) {
backtrack(n - 1, i + 1, h + hours[i], m + mins[i], res, hours, mins)
}
}
fun getTime(h: Int, m: Int): String {
return "%d:%02d".format(h, m)
}
fun main() {
val list = readBinaryWatch(1)
println(list)
}
|
package com.quickblox.sample.videochat.kotlin.fragments
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.quickblox.sample.videochat.kotlin.R
import com.quickblox.sample.videochat.kotlin.activities.CallActivity
import com.quickblox.users.model.QBUser
class ScreenShareFragment : BaseToolBarFragment() {
private val TAG = ScreenShareFragment::class.simpleName
private var onSharingEvents: OnSharingEvents? = null
private var currentCallStateCallback: CallActivity.CurrentCallStateCallback? = null
companion object {
fun newInstance(): ScreenShareFragment = ScreenShareFragment()
}
override fun getFragmentLayout(): Int {
return R.layout.fragment_pager
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = super.onCreateView(inflater, container, savedInstanceState)
val adapter = ImagesAdapter(childFragmentManager)
val pager = view?.findViewById<View>(R.id.pager) as ViewPager
pager.adapter = adapter
val context = activity as Context
toolbar.setBackgroundColor(ContextCompat.getColor(context, R.color.white))
return view
}
override fun onResume() {
super.onResume()
currentCallStateCallback = CurrentCallStateCallbackImpl()
(activity as CallActivity).addCurrentCallStateListener(currentCallStateCallback!!)
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.screen_share_fragment, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.stop_screen_share -> {
Log.d(TAG, "stop_screen_share")
onSharingEvents?.onStopPreview()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
override fun onAttach(context: Context?) {
super.onAttach(context)
try {
onSharingEvents = context as OnSharingEvents?
} catch (e: ClassCastException) {
throw ClassCastException(activity?.toString() + " must implement OnSharingEvents")
}
}
override fun onDetach() {
super.onDetach()
onSharingEvents = null
}
override fun onPause() {
super.onPause()
currentCallStateCallback?.let {
(activity as CallActivity).removeCurrentCallStateListener(it)
}
}
class ImagesAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
private val images = intArrayOf(R.drawable.pres_img, R.drawable.p2p, R.drawable.group_call, R.drawable.opponents)
override fun getCount(): Int {
return images.size
}
override fun getItem(position: Int): Fragment {
return PreviewFragment.newInstance(images[position])
}
}
private inner class CurrentCallStateCallbackImpl : CallActivity.CurrentCallStateCallback {
override fun onCallStarted() {
}
override fun onCallStopped() {
}
override fun onOpponentsListUpdated(newUsers: ArrayList<QBUser>) {
}
override fun onCallTimeUpdate(time: String) {
toolbar.title = ""
val timerTextView = toolbar.findViewById<TextView>(R.id.timer_call)
timerTextView.visibility = View.VISIBLE
timerTextView.text = time
}
}
interface OnSharingEvents {
fun onStopPreview()
}
}
|
<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);
require_once "lib_new/WxPay.Api.php";
function printf_info($data)
{
foreach($data as $key=>$value){
echo "<font color='#f00;'>$key</font> : $value <br/>";
}
}
$data=array();
if(isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""){
$transaction_id = $_REQUEST["transaction_id"];
$input = new WxPayRefundQuery();
$input->SetTransaction_id($transaction_id);
$data=WxPayApi::refundQuery($input);
echo json_encode($data);die;
}
if(isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != ""){
$out_trade_no = $_REQUEST["out_trade_no"];
$input = new WxPayRefundQuery();
$input->SetOut_trade_no($out_trade_no);
$data=WxPayApi::refundQuery($input);
echo json_encode($data);die;
}
if(isset($_REQUEST["out_refund_no"]) && $_REQUEST["out_refund_no"] != ""){
$out_refund_no = $_REQUEST["out_refund_no"];
$input = new WxPayRefundQuery();
$input->SetOut_refund_no($out_refund_no);
$data=WxPayApi::refundQuery($input);
echo json_encode($data);die;
}
if(isset($_REQUEST["refund_id"]) && $_REQUEST["refund_id"] != ""){
$refund_id = $_REQUEST["refund_id"];
$input = new WxPayRefundQuery();
$input->SetRefund_id($refund_id);
$data=WxPayApi::refundQuery($input);
echo json_encode($data);die;
}
?>
|
package com.example.mrokey.besttrip.company
import com.example.mrokey.besttrip.entities.Company
import com.example.mrokey.besttrip.entities.Vehicle
import com.google.firebase.database.*
class CompanyPresenter(internal var view: CompanyContract.View) : CompanyContract.Presenter {
private var mReference: DatabaseReference? = null
private var listCompany = ArrayList<Company>()
init {
view.setPresenter(this)
mReference = FirebaseDatabase.getInstance().reference.child("company")
}
override fun getDatabase(listener: CompanyContract.View) {
mReference?.addListenerForSingleValueEvent(object: ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val size = dataSnapshot.childrenCount
for (i in 0 until size) {
val child = dataSnapshot.child(i.toString())
var listTaxi = ArrayList<Vehicle>()
for (j in 0 until child.child("vehicle").childrenCount) {
val vehicleChild = child.child("vehicle").child(j.toString())
listTaxi.add(Vehicle(
vehicleChild.child("name").value.toString(),
vehicleChild.child("number_seat").value.toString().toLong(),
vehicleChild.child("_1km").value.toString().toLong(),
vehicleChild.child("over_1km").value.toString().toDouble(),
vehicleChild.child("over_30km").value.toString().toDouble()
))
}
listCompany.add(Company(
child.child("name").value.toString(),
child.child("address").value.toString(),
child.child("phone").value.toString(),
listTaxi,
child.child("wait_time").value.toString().toLong(),
child.child("logo").value.toString()
))
}
listener.onDataChange(listCompany)
}
override fun onCancelled(p0: DatabaseError) {
}
})
}
}
|
A6_Header:
sHeaderInit ; Z80 offset is $D413
sHeaderPatch A6_Patches
sHeaderTick $01
sHeaderCh $01
sHeaderSFX $80, $C0, A6_PSG3, $1F, $05
A6_PSG3:
sNoisePSG $E7
sVolEnvPSG v16
ssModZ80 $01, $01, $F0, $17
dc.b nD4, $03, $03, $03, $03, $04
sStop
A6_Patches:
|
---
layout: post
header: Arsenal 3-1 Juventus
date: 2001-12-04
categories: champions-league
video: NLO1LwUiPz0
summary: "Arsenal beat a strong Juventus side with a double from Freddie Ljungberg"
excerpt: "Arsenal beat a strong Juventus side with a double from Freddie Ljungberg"
title: Arsenal 3-1 Juventus
redirect_from: /champions-league/2001/arsenal-3-1-juventus/
---
{% include related-champions-league-matches.html %}
|
namespace DeepSleep.OpenApi
{
using Microsoft.OpenApi.Models;
using System.Threading.Tasks;
/// <summary>
///
/// </summary>
public interface IDeepSleepOasGenerator
{
/// <summary>Generates the specified information.</summary>
/// <returns></returns>
Task<OpenApiDocument> Generate();
}
}
|
// Copyright 2020 Paul Greenberg greenpau@outlook.com
//
// 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 options
// TokenValidatorOptions provides options for TokenValidator.
type TokenValidatorOptions struct {
ValidateSourceAddress bool `json:"validate_source_address,omitempty" xml:"validate_source_address,omitempty" yaml:"validate_source_address,omitempty"`
ValidateBearerHeader bool `json:"validate_bearer_header,omitempty" xml:"validate_bearer_header,omitempty" yaml:"validate_bearer_header,omitempty"`
ValidateMethodPath bool `json:"validate_method_path,omitempty" xml:"validate_method_path,omitempty" yaml:"validate_method_path,omitempty"`
ValidateAccessListPathClaim bool `json:"validate_access_list_path_claim,omitempty" xml:"validate_access_list_path_claim,omitempty" yaml:"validate_access_list_path_claim,omitempty"`
}
// TokenGrantorOptions provides options for TokenGrantor.
type TokenGrantorOptions struct {
EnableSourceAddress bool `json:"enable_source_address,omitempty" xml:"enable_source_address,omitempty" yaml:"enable_source_address,omitempty"`
}
// NewTokenValidatorOptions returns an instance of TokenValidatorOptions
func NewTokenValidatorOptions() *TokenValidatorOptions {
return &TokenValidatorOptions{}
}
// NewTokenGrantorOptions returns an instance of TokenGrantorOptions
func NewTokenGrantorOptions() *TokenGrantorOptions {
return &TokenGrantorOptions{}
}
|
import { GLYPHS } from "../components/Icon.jsx";
import { canvasRendererFactory } from "./view/CanvasRenderer";
import createActions from "./actions";
import {
connectWorldview,
connectCanvas,
connectControlPane,
connectStatusBar,
connectMetadataViewer
} from "./connect";
import { default as lifeReducer } from "./reducer";
import { configure as configureImport } from "./import";
import { createActions as createImportActions } from "../import-lib";
import { parseRLE } from "../core/parser";
import LifeImporter from "../core/LifeImporter";
export function configure(context) {
const {
registerView,
registerNavigationItem,
changeView,
changeLocation,
addRoute,
createClock,
createFileReader,
} = context;
const lifeImporter = LifeImporter({ createFileReader, parser: parseRLE });
const navigateToLifeView = () => changeLocation(PATH);
const actions = createActions({
navigateToLifeView,
clock: createClock(),
...createImportActions(lifeImporter)
});
const Canvas = connectCanvas(actions, canvasRendererFactory);
const ControlPane = connectControlPane(actions);
const StatusBar = connectStatusBar();
const MetadataViewer = connectMetadataViewer();
const Worldview = connectWorldview(actions, { Canvas, ControlPane, StatusBar, MetadataViewer });
registerNavigationItem({
label: "Life",
path: PATH,
data: {
icon: GLYPHS.APPS
}
});
registerView(WORLDVIEW_KEY, Worldview);
addRoute(PATH, () => changeView(WORLDVIEW_KEY));
configureImport({
...context,
importFile: actions.importFile,
importFromString: actions.importFromString
});
}
export const PATH = "/life";
const WORLDVIEW_KEY = "worldview";
export { lifeReducer };
|
export declare enum RecurrencePatternEnum {
rpNone = "rpNone",
rpDaily = "rpDaily",
rpWeekly = "rpWeekly",
rpMonthly = "rpMonthly",
rpAnnually = "rpAnnually"
}
//# sourceMappingURL=RecurrencePatternEnum.d.ts.map
|
package handler
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/keptn/keptn/shipyard-controller/models"
)
type IEvaluationHandler interface {
CreateEvaluation(context *gin.Context)
}
type EvaluationHandler struct {
EvaluationManager IEvaluationManager
}
func NewEvaluationHandler(evaluationManager IEvaluationManager) *EvaluationHandler {
return &EvaluationHandler{EvaluationManager: evaluationManager}
}
// CreateEvaluation triggers a new evaluation
// @Summary Trigger a new evaluation
// @Description Trigger a new evaluation for a service within a project
// @Tags Evaluation
// @Security ApiKeyAuth
// @Accept json
// @Produce json
// @Param project path string true "Project"
// @Param stage path string true "Stage"
// @Param service path string true "Service"
// @Param evaluation body models.CreateEvaluationParams true "Evaluation"
// @Success 200 {object} models.CreateEvaluationResponse "ok"
// @Failure 400 {object} models.Error "Invalid payload"
// @Failure 500 {object} models.Error "Internal error"
// @Router /project/{project}/stage/{stage}/service/{service}/evaluation [post]
func (eh *EvaluationHandler) CreateEvaluation(c *gin.Context) {
project := c.Param("project")
stage := c.Param("stage")
service := c.Param("service")
evaluation := &models.CreateEvaluationParams{}
if err := c.ShouldBindJSON(evaluation); err != nil {
SetBadRequestErrorResponse(c, fmt.Sprintf(InvalidRequestFormatMsg, err.Error()))
return
}
evaluationContext, err := eh.EvaluationManager.CreateEvaluation(project, stage, service, evaluation)
if err != nil {
c.JSON(getHTTPStatusForError(err.Code), err)
return
}
c.JSON(http.StatusOK, evaluationContext)
}
func getHTTPStatusForError(code int) int {
switch code {
case evaluationErrServiceNotAvailable:
return http.StatusBadRequest
case evaluationErrInvalidTimeframe:
return http.StatusBadRequest
default:
return http.StatusInternalServerError
}
}
|
using System.Windows;
using frontend.CustomControls;
using Microsoft.Win32;
namespace frontend.API
{
public class UserInteractionService: IUserInteractionService
{
public string ShowSaveDialog(string filter="PDF file (*.pdf)|*.pdf")
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = filter;
var dialog = saveFileDialog.ShowDialog();
if (dialog == null || dialog == false)
return "";
return saveFileDialog.FileName;
}
public string[] ShowOpenFileDialog(string filter="JSON File (*.json)|*.json")
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = filter;
openFileDialog.Multiselect = true;
var dialog = openFileDialog.ShowDialog();
if (dialog == null || dialog == false)
return null;
return openFileDialog.FileNames;
}
public void ShowErrorMessageBox(string message,string caption="Error")
{
MessageBox.Show(message,caption);
}
}
}
|
#!/bin/bash
gunicorn app:server --bind=0.0.0.0:8000 --timeout=300
|
package routes
import (
"github.com/gin-gonic/gin"
"github.com/linkc0829/go-icsharing/internal/db/mongodb"
"github.com/linkc0829/go-icsharing/internal/handlers"
"github.com/linkc0829/go-icsharing/internal/handlers/gqlclient"
"github.com/linkc0829/go-icsharing/pkg/utils"
)
func RestAPI(cfg *utils.ServerConfig, r *gin.Engine, db *mongodb.MongoDB) {
g := r.Group(cfg.VersioningEndpoint("/user"))
g.GET("/:id", gqlclient.GetUser(cfg))
g.POST("", gqlclient.CreateUser(cfg))
g.PATCH("/:id", gqlclient.UpdateUser(cfg))
g.DELETE("/:id", gqlclient.DeleteUser(cfg))
g.PUT("addfriend/:id", gqlclient.AddFriend(cfg))
g.GET(":id/income", gqlclient.GetUserIncome(cfg))
g.GET(":id/cost", gqlclient.GetUserCost(cfg))
g.GET(":id/income/history", gqlclient.GetUserIncomeHistory(cfg))
g.GET(":id/cost/history", gqlclient.GetUserCostHistory(cfg))
in := r.Group(cfg.VersioningEndpoint("/income"))
in.POST("", gqlclient.CreateIncome(cfg))
in.PATCH(":id", gqlclient.UpdateIncome(cfg))
in.DELETE(":id", gqlclient.DeleteIncome(cfg))
in.PUT("vote/:id", gqlclient.VoteIncome(cfg))
co := r.Group(cfg.VersioningEndpoint("/cost"))
co.POST("", gqlclient.CreateCost(cfg))
co.PATCH(":id", gqlclient.UpdateCost(cfg))
co.DELETE(":id", gqlclient.DeleteCost(cfg))
co.PUT("vote/:id", gqlclient.VoteCost(cfg))
//user profile API
r.POST("/profile/:id", handlers.UserProfileHandler(cfg))
r.GET("/profile/:id", handlers.UserProfileHandler(cfg))
r.GET("/history/:id", handlers.UserHistoryHandler(cfg))
r.GET("/friends/:id", handlers.UserFriendsHandler(cfg, db))
r.GET("/followers/:id", handlers.UserFollowersHandler(cfg, db))
}
|
import socketio from 'socket.io';
// Connect Socket
export const ConnectionToSocket = (server) => {
const io = socketio(server);
return (
io.on('connection', (socket) => {
console.log('se conectaron al socket', socket.id);
socket.emit('login', {
id: socket.id,
});
socket.on('enter to room', (data) => {
socket.username = data.username;
socket.join('room '+ data.chatroom);
});
socket.on('disconnecting', () => {
let rooms = Object.keys(socket.rooms);
console.log('disconnecting', rooms);
socket.leaveAll();
rooms = Object.keys(socket.rooms);
console.log('disconnecting', rooms);
});
// when the client emits 'new message', this listens and executes
socket.on('new message', (data) => {
console.log('new message', data);
// we tell the client to execute 'new message'
socket.to('room '+ data.chatroom_id).emit('new message', data);
});
// when the user disconnects.. perform this
socket.on('disconnection', () => {
console.log('disconnection');
socket.disconnect(true);
console.log('disconnected: ', socket.disconnected);
});
})
);
};
|
import { Iterator } from "../../classes/iterator";
export declare abstract class AbstractIterable<E> implements Iterable<E> {
[index: number]: E;
abstract forEach(action: (item: E, index: number, collection: Iterable<E>) => void): void;
abstract iterator(): Iterator<E>;
[Symbol.iterator](): IterableIterator<E>;
}
|
import React, { useState, useRef } from 'react';
import './styles.css';
import { useSpring, animated } from 'react-spring';
import onClickOutside from "react-onclickoutside";
import { useLanguage } from '../../hooks/useLanguage';
import { NavLink } from 'react-router-dom';
import { GoThreeBars } from 'react-icons/go';
import { MdClose } from 'react-icons/md';
const Navbar = () => {
/** lang hook */
const [texts, setLang] = useLanguage();
/** ref for Navbar (necessary to handleClickoutside) */
const ref = useRef();
/** sidebar transition effect */
const [display, setDisplay] = useState(false);
const spring = useSpring({ right: display ? '0' : '-300px' });
Navbar.handleClickOutside = (e) => {
if(!ref.current.contains(e.target)) setDisplay(false);
}
const onLangClick = (lang) => {
setLang(lang);
setDisplay(false);
}
const { Navbar: txt } = texts;
return (<>
<button className="navbar-open-btn" onClick={() => setDisplay(true)}>
<GoThreeBars />
</button>
<animated.div className="Navbar" ref={ref} style={spring}>
<div className="container">
<button className="navbar-close-btn" onClick={() => setDisplay(false)}>
<MdClose />
</button>
<NavLink exact to="/" activeClassName="active" onClick={() => setDisplay(false)}>
{txt.home}
</NavLink>
<NavLink to="/about" activeClassName="active" onClick={() => setDisplay(false)}>
{txt.about}
</NavLink>
<NavLink to="/projects" activeClassName="active" onClick={() => setDisplay(false)}>
{txt.projects}
</NavLink>
<NavLink to="/contact" activeClassName="active" onClick={() => setDisplay(false)}>
{txt.contact}
</NavLink>
<div className="lang">
<button onClick={() => onLangClick('esp')}>
<img src='/img/spainflag.png' alt='' />
{txt.spanish}
</button>
<button onClick={() => onLangClick('eng')}>
<img src='/img/englandflag.png' alt='' />
{txt.english}
</button>
</div>
</div>
</animated.div>
</>);
}
const clickOutsideConfig = { handleClickOutside: () => Navbar.handleClickOutside };
export default onClickOutside(Navbar, clickOutsideConfig);
|
import { assign as lodashAssign } from 'lodash';
import {
CHANGE_STATE,
TOGGLE_ON_OFF,
CHANGE_VALUE,
CHANGE_MODE
} from './constants';
export const initialCompareState = {
active: false,
isCompareA: true,
mode: 'swipe',
value: 50,
activeString: 'active',
bStatesInitiated: false
};
export function compareReducer(state = initialCompareState, action) {
switch (action.type) {
case CHANGE_STATE: {
const newIsCompareA = !state.isCompareA;
return lodashAssign({}, state, {
isCompareA: newIsCompareA,
activeString: newIsCompareA ? 'active' : 'activeB'
});
}
case TOGGLE_ON_OFF:
return lodashAssign({}, state, {
active: !state.active,
bStatesInitiated: true
});
case CHANGE_MODE:
return lodashAssign({}, state, {
mode: action.mode,
value: 50
});
case CHANGE_VALUE:
return lodashAssign({}, state, {
value: action.value
});
}
return state;
}
|
require File.dirname(__FILE__) + '/../../spec_helper'
require 'matrix'
describe "Matrix#clone" do
before(:each) do
@a = Matrix[[1, 2], [3, 4], [5, 6]]
end
it "returns a shallow copy of the matrix" do
b = @a.clone
@a.should_not equal(b)
b.class.should == Matrix
b.should == @a
0.upto(@a.row_size - 1) do |i|
@a.row(i).should_not equal(b.row(i))
end
end
before(:each) do
@a = Matrix[[1, 2], [3, 4], [5, 6]]
end
quarantine! do # The test fails on MRI 1.8.6 pl 111, pl 114, MRI 1.8.7, JRuby
it "returns a copy of the matrix, but with all the references different" do
b = @a.clone
b.class.should == Matrix
b.should == @a
b.should_not === @a
0.upto(@a.row_size - 1) do |i|
0.upto(@a.column_size - 1) do |j|
b[i, j].should == @a[i, j]
b[i, j].should_not === @a[i, j]
end
end
end
end
end
|
// Copyright 2013-2015 go-diameter authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package avp
// AVP Flags. See section 4.1 of RFC 6733.
const (
Pbit = 1 << 5 // The 'P' bit, reserved for future use.
Mbit = 1 << 6 // The 'M' bit, known as the Mandatory bit.
Vbit = 1 << 7 // The 'V' bit, known as the Vendor-Specific bit.
)
|
# -*- coding: utf-8 -*-
"""
@author: 猿小天
@contact: QQ:1638245306
@Created on: 2021/6/3 003 0:30
@Remark: 用户管理
"""
import hashlib
from django.contrib.auth.hashers import make_password
from rest_framework import serializers
from dvadmin.system.models import Users
from dvadmin.utils.json_response import SuccessResponse, ErrorResponse
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.validator import CustomUniqueValidator
from dvadmin.utils.viewset import CustomModelViewSet
class UserSerializer(CustomModelSerializer):
"""
用户管理-序列化器
"""
class Meta:
model = Users
read_only_fields = ["id"]
exclude = ['password']
extra_kwargs = {
'post': {'required': False},
}
class UserCreateSerializer(CustomModelSerializer):
"""
用户新增-序列化器
"""
username = serializers.CharField(max_length=50,
validators=[CustomUniqueValidator(queryset=Users.objects.all(), message="账号必须唯一")])
password = serializers.CharField(required=False, default=make_password(
hashlib.md5('admin123456'.encode(encoding='UTF-8')).hexdigest()))
def save(self, **kwargs):
data = super().save(**kwargs)
data.post.set(self.initial_data.get('post', []))
return data
class Meta:
model = Users
fields = "__all__"
read_only_fields = ["id"]
extra_kwargs = {
'post': {'required': False},
}
class UserUpdateSerializer(CustomModelSerializer):
"""
用户修改-序列化器
"""
username = serializers.CharField(max_length=50,
validators=[CustomUniqueValidator(queryset=Users.objects.all(), message="账号必须唯一")])
password = serializers.CharField(required=False, allow_blank=True)
def save(self, **kwargs):
data = super().save(**kwargs)
data.post.set(self.initial_data.get('post', []))
return data
class Meta:
model = Users
read_only_fields = ["id"]
fields = "__all__"
extra_kwargs = {
'post': {'required': False, 'read_only': True},
}
class UserViewSet(CustomModelViewSet):
"""
用户接口
list:查询
create:新增
update:修改
retrieve:单例
destroy:删除
"""
queryset = Users.objects.exclude(is_superuser=1).all()
serializer_class = UserSerializer
create_serializer_class = UserCreateSerializer
update_serializer_class = UserUpdateSerializer
permission_classes = []
def user_info(self, request):
"""获取当前用户信息"""
user = request.user
result = {
"name": user.name,
"mobile": user.mobile,
"gender": user.gender,
"email": user.email
}
return SuccessResponse(data=result, msg="获取成功")
def update_user_info(self, request):
"""修改当前用户信息"""
user = request.user
Users.objects.filter(id=user.id).update(**request.data)
return SuccessResponse(data=None, msg="修改成功")
def change_password(self, request, *args, **kwargs):
"""密码修改"""
instance = Users.objects.filter(id=kwargs.get('pk')).first()
data = request.data
old_pwd = data.get('oldPassword')
new_pwd = data.get('newPassword')
new_pwd2 = data.get('newPassword2')
if instance:
if new_pwd != new_pwd2:
return ErrorResponse(msg="两次密码不匹配")
elif instance.check_password(old_pwd):
instance.password = make_password(new_pwd)
instance.save()
return SuccessResponse(data=None, msg="修改成功")
else:
return ErrorResponse(msg="旧密码不正确")
else:
return ErrorResponse(msg="未获取到用户")
|
require "rails_helper"
describe "admin/users" do
before do
@admin_user = FactoryGirl.create(:admin_user)
login_as(@admin_user, :scope => :admin_user)
end
describe "GET index page" do
context "authenticated admin_user" do
it "should render users index page" do
2.times { FactoryGirl.create(:user) }
visit_and_confirm("/admin/users")
end
end
end
describe "GET show page" do
context "non authenticated admin_user" do
it "should rendre user show page" do
user = FactoryGirl.create(:user)
visit_and_confirm("/admin/users/#{user.id}")
end
end
end
end
|
package kpn.server.repository
import kpn.core.database.Database
import kpn.core.database.views.planner.GraphEdgesView
import kpn.core.planner.graph.GraphEdge
import kpn.shared.NetworkType
import org.springframework.stereotype.Component
@Component
class GraphRepositoryImpl(analysisDatabase: Database) extends GraphRepository {
override def edges(networkType: NetworkType): Seq[GraphEdge] = {
GraphEdgesView.query(analysisDatabase, networkType, stale = false)
}
}
|
namespace FFXIVClientStructs.FFXIV.Client.Game.Control;
[StructLayout(LayoutKind.Explicit, Size = 0x8)]
public unsafe partial struct InputManager {
[MemberFunction("E8 ?? ?? ?? ?? 3A C3 74 0C", IsStatic = true)]
public static partial bool IsAutoRunning();
}
|
---
layout: project_single
title: "Colorado!! Honeymoon location:))"
slug: "colorado-honeymoon-location"
parent: "honeymoon-home"
---
Colorado!! Honeymoon location:))
|
package com.actionForm;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;
public class PublishingForm extends ActionForm {
private String isbn;
private String pubname;
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public void setPubname(String pubname) {
this.pubname = pubname;
}
public String getPubname() {
return pubname;
}
public ActionErrors validate(ActionMapping actionMapping,
HttpServletRequest httpServletRequest) {
/** @todo: finish this method, this is just the skeleton.*/
return null;
}
public void reset(ActionMapping actionMapping,
HttpServletRequest servletRequest) {
}
}
|
/*
* Copyright 2013 Valery Lobachev
*
* 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 biz.lobachev.annette.org_structure.impl.role
import java.util.concurrent.TimeUnit
import akka.Done
import akka.cluster.sharding.typed.scaladsl.{ClusterSharding, EntityRef}
import akka.stream.Materializer
import akka.stream.scaladsl.{Sink, Source}
import akka.util.Timeout
import biz.lobachev.annette.core.model.indexing.FindResult
import biz.lobachev.annette.org_structure.api.role._
import biz.lobachev.annette.org_structure.impl.role.dao.{OrgRoleDbDao, OrgRoleIndexDao}
import com.typesafe.config.Config
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Try
class OrgRoleEntityService(
clusterSharding: ClusterSharding,
dbDao: OrgRoleDbDao,
indexDao: OrgRoleIndexDao,
config: Config
)(implicit
ec: ExecutionContext,
val mat: Materializer
) {
implicit val timeout =
Try(config.getDuration("annette.timeout"))
.map(d => Timeout(FiniteDuration(d.toNanos, TimeUnit.NANOSECONDS)))
.getOrElse(Timeout(60.seconds))
private def refFor(id: OrgRoleId): EntityRef[OrgRoleEntity.Command] =
clusterSharding.entityRefFor(OrgRoleEntity.typeKey, id)
private def convertSuccess(id: OrgRoleId, confirmation: OrgRoleEntity.Confirmation): Done =
confirmation match {
case OrgRoleEntity.Success => Done
case OrgRoleEntity.NotFound => throw OrgRoleNotFound(id)
case OrgRoleEntity.AlreadyExist => throw OrgRoleAlreadyExist(id)
case _ => throw new RuntimeException("Match fail")
}
def createOrgRole(payload: CreateOrgRolePayload): Future[Done] =
refFor(payload.id)
.ask[OrgRoleEntity.Confirmation](OrgRoleEntity.CreateOrgRole(payload, _))
.map(res => convertSuccess(payload.id, res))
def updateOrgRole(payload: UpdateOrgRolePayload): Future[Done] =
refFor(payload.id)
.ask[OrgRoleEntity.Confirmation](OrgRoleEntity.UpdateOrgRole(payload, _))
.map(res => convertSuccess(payload.id, res))
def deleteOrgRole(payload: DeleteOrgRolePayload): Future[Done] =
refFor(payload.id)
.ask[OrgRoleEntity.Confirmation](OrgRoleEntity.DeleteOrgRole(payload, _))
.map(res => convertSuccess(payload.id, res))
def getOrgRoleById(id: OrgRoleId, fromReadSide: Boolean): Future[OrgRole] =
if (fromReadSide) getOrgRoleByIdFromReadSide(id)
else getOrgRoleById(id)
def getOrgRoleById(id: OrgRoleId): Future[OrgRole] =
refFor(id)
.ask[OrgRoleEntity.Confirmation](OrgRoleEntity.GetOrgRole(id, _))
.map {
case OrgRoleEntity.SuccessOrgRole(entity) => entity
case _ => throw OrgRoleNotFound(id)
}
def getOrgRoleByIdFromReadSide(id: OrgRoleId): Future[OrgRole] =
for {
maybeOrgRole <- dbDao.getOrgRoleById(id)
} yield maybeOrgRole match {
case Some(orgRole) => orgRole
case None => throw OrgRoleNotFound(id)
}
def getOrgRolesById(ids: Set[OrgRoleId], fromReadSide: Boolean): Future[Seq[OrgRole]] =
if (fromReadSide) dbDao.getOrgRolesById(ids)
else
Source(ids)
.mapAsync(1) { id =>
refFor(id)
.ask[OrgRoleEntity.Confirmation](OrgRoleEntity.GetOrgRole(id, _))
.map {
case OrgRoleEntity.SuccessOrgRole(entity) => Some(entity)
case _ => None
}
}
.runWith(Sink.seq)
.map(seq => seq.flatten)
def findOrgRoles(query: OrgRoleFindQuery): Future[FindResult] =
indexDao.findOrgRole(query)
}
|
// Base reporter for all Reporters. Handles generic tasks as well as adding a few string trimming functions
// (c) 2011 Matthew Kitt
// Set the name, plus passing and failing messages
var Reporter = module.exports = function Reporter() {
this.name = 'Reporter'
this.passed_message = 'passed'
this.failed_message = 'failed'
}
// Parse out either a passing or failing messages based on the status of the output
Reporter.prototype.report = function(error, stdout, stderr) {
if (error !== null) {
return this.failed(error, stdout, stderr)
}
return this.passed(error, stdout, stderr)
}
// Parse and return a passing message
Reporter.prototype.passed = function(error, stdout, stderr) {
return {msg: stdout, gmsg: this.passed_message}
}
// Parse and return a failing message
Reporter.prototype.failed = function(error, stdout, stderr) {
return {msg: error.msg, gmsg: this.failed_message}
}
/* Helpers */
// Clean up surrounding white space
Reporter.prototype.trim = function(str) {
return str.replace(/^\s+|\s+$/g,'')
}
// Clean up any ansi characters
Reporter.prototype.trimANSI = function(str) {
return str.replace(/\[\d+m/g, '')
}
// Clean up new lines
Reporter.prototype.trimNewlines = function(str) {
return str.replace(/\n/g, ' ')
}
// Clean up the last line break in a string
Reporter.prototype.trimLastNewline = function(str) {
return str.replace(/\n+$/g, '')
}
|
<?php
declare(strict_types=1);
namespace B24io\Loyalty\SDK\Bitrix24\Contacts\DTO;
use B24io\Loyalty\SDK\Users\DTO\UserId;
use B24io\Loyalty\SDK\Users\DTO\Email;
use libphonenumber\PhoneNumber;
/**
* Class Contact
*
* @package B24io\Loyalty\SDK\Bitrix24\Contacts\DTO
*/
class Contact
{
/**
* @var UserId|null
*/
private $contactId;
/**
* @var string
*/
private $name;
/**
* @var string|null
*/
private $secondName;
/**
* @var string|null
*/
private $lastName;
/**
* @var \DateTime|null
*/
private $birthday;
/**
* @var string|null
*/
private $comments;
/**
* @var \DateTime
*/
private $created;
/**
* @var \DateTime
*/
private $modified;
/**
* @var PhoneNumber|null
*/
private $mobilePhone;
/**
* @var Email|null
*/
private $email;
/**
* @var Address|null
*/
private $address;
/**
* @var string|null
*/
private $originId;
/**
* @var string|null
*/
private $originatorId;
/**
* @var UTM|null
*/
private $utm;
/**
* @var string|null
*/
private $sourceDescription;
/**
* Contact constructor.
*
* @param \DateTime $created
* @param \DateTime $modified
* @param string $name
* @param string|null $secondName
* @param string|null $lastName
* @param PhoneNumber|null $mobilePhone
* @param Email|null $email
* @param UserId|null $contactId
* @param \DateTime|null $birthday
* @param string|null $comments
* @param Address|null $address
* @param string|null $originId
* @param string|null $originatorId
* @param string|null $sourceDescription
* @param UTM|null $utm
*/
public function __construct(
\DateTime $created,
\DateTime $modified,
string $name,
?string $secondName,
?string $lastName,
?PhoneNumber $mobilePhone,
?Email $email = null,
?UserId $contactId = null,
?\DateTime $birthday = null,
?string $comments = null,
?Address $address = null,
?string $originId = null,
?string $originatorId = null,
?string $sourceDescription = null,
?UTM $utm = null
) {
$this->created = $created;
$this->modified = $modified;
$this->name = $name;
$this->secondName = $secondName;
$this->lastName = $lastName;
$this->mobilePhone = $mobilePhone;
$this->email = $email;
$this->contactId = $contactId;
$this->birthday = $birthday;
$this->comments = $comments;
$this->address = $address;
$this->originId = $originId;
$this->originatorId = $originatorId;
$this->sourceDescription = $sourceDescription;
$this->utm = $utm;
}
/**
* @return UserId|null
*/
public function getContactId(): ?UserId
{
return $this->contactId;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return string|null
*/
public function getSecondName(): ?string
{
return $this->secondName;
}
/**
* @return string|null
*/
public function getLastName(): ?string
{
return $this->lastName;
}
/**
* @return \DateTime|null
*/
public function getBirthday(): ?\DateTime
{
return $this->birthday;
}
/**
* @return string|null
*/
public function getComments(): ?string
{
return $this->comments;
}
/**
* @return \DateTime
*/
public function getCreated(): \DateTime
{
return $this->created;
}
/**
* @return \DateTime
*/
public function getModified(): \DateTime
{
return $this->modified;
}
/**
* @return PhoneNumber
*/
public function getMobilePhone(): PhoneNumber
{
return $this->mobilePhone;
}
/**
* @return Email|null
*/
public function getEmail(): ?Email
{
return $this->email;
}
/**
* @return Address|null
*/
public function getAddress(): ?Address
{
return $this->address;
}
/**
* @return string|null
*/
public function getOriginId(): ?string
{
return $this->originId;
}
/**
* @return string|null
*/
public function getOriginatorId(): ?string
{
return $this->originatorId;
}
/**
* @return UTM|null
*/
public function getUtm(): ?UTM
{
return $this->utm;
}
/**
* @return string|null
*/
public function getSourceDescription(): ?string
{
return $this->sourceDescription;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.