text
stringlengths 27
775k
|
|---|
# Azure Devops
[Azure Devops] is configured with a `azure-pipelines.yml` file in your project.
````yaml
resources:
containers:
- container: build-tools
image: buildtool/build-tools:latest
jobs:
- job: build_and_deploy
pool:
vmImage: 'Ubuntu 16.04'
container: build-tools
steps:
- script: |
build
push
name: build
env:
QUAY_PASSWORD: $(QUAY_PASSWORD)
- script: deploy staging
name: deploy_staging
condition: succeeded()
````
[azure devops]: https://azure.microsoft.com/en-us/services/devops/pipelines/
|
package edu.mitin.playground.results.repository;
import edu.mitin.playground.inter.tournaments.entity.Tournament;
import edu.mitin.playground.results.entity.Round;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface RoundRepository extends JpaRepository<Round, Long> {
List<Round> findAllByGuestNameAndTournament(String guestName, Tournament tournament);
List<Round> findAllByHostNameAndTournament(String hostName, Tournament tournament);
List<Round> findAllByTournament(Tournament tournament);
}
|
require 'multi_json'
require 'chatter/errors'
module Chatter
module Codecs
module JSON
class JSONDecodeError < Chatter::CodecError
def initialize(input, error)
@input = input
@error = error
super("could not parse #{input} as JSON")
end
attr_reader :input, :error
end
class JSONEncodeError < Chatter::CodecError
def initialize(input, error)
@input = input
@error = error
super("could dump #{input.inspect} as JSON")
end
attr_reader :input, :error
end
def self.encode(data)
raise ArgumentError.new('expected ') unless data.kind_of?(Hash)
MultiJson.dump(data)
rescue => error
raise JSONEncodeError.new(data, error)
end
def self.decode(data)
MultiJson.load(data, symbolize_keys: true)
rescue => error
raise JSONDecodeError.new(data, error)
end
end
end
end
|
import ClubhouseController from 'clubhouse/controllers/clubhouse-controller';
export default class TrainingPeopleTrainingCompletedController extends ClubhouseController {
queryParams = [ 'year' ];
}
|
import importlib.util
from os import path
from pathlib import Path
from types import ModuleType
import pytest
from airflow import DAG
from airflow.utils.dag_cycle_tester import test_cycle
DAGS_DIRECTORY = Path(__file__).parent / ".." / ".." / "dags"
DAGS_PATHS = DAGS_DIRECTORY.glob("**/*.py")
def import_module(module_name: str, module_path: Path) -> ModuleType:
spec = importlib.util.spec_from_file_location(name=module_name, location=module_path)
module = importlib.util.module_from_spec(spec=spec)
spec.loader.exec_module(module=module) # type: ignore
return module
@pytest.mark.parametrize("dag_path", DAGS_PATHS)
def test_dag_integrity(dag_path: Path) -> None:
"""Import a DAG file and check if it has a valid DAG instance."""
dag_name = path.basename(dag_path)
dag_module = import_module(dag_name, dag_path)
# Look for all DAG instancies.
dags = [var for var in vars(dag_module).values() if isinstance(var, DAG)]
# Assert that there is at least one DAG instance.
assert dags
# Test all DAG instancies for cycles.
for dag in dags:
test_cycle(dag=dag)
|
/** @jsx jsx */
import { jsx, InterpolationWithTheme } from '@emotion/core';
import { Component, FC } from 'react';
import RadioIcon from '@atlaskit/icon/glyph/radio';
import CheckboxIcon from '@atlaskit/icon/glyph/checkbox';
import { themed } from '@atlaskit/theme/components';
import { gridSize } from '@atlaskit/theme/constants';
import { ThemedValue } from '@atlaskit/theme/types';
import {
B100,
B200,
B300,
B400,
B75,
DN200,
DN10,
DN30,
N20A,
N0,
N100,
N20,
N30,
N70,
} from '@atlaskit/theme/colors';
import { token } from '@atlaskit/tokens';
import { OptionProps, OptionType } from '../types';
const getPrimitiveStyles = (
props: Omit<OptionProps, 'children' | 'innerProps' | 'innerRef'>,
): [InterpolationWithTheme<any>, string] => {
const { cx, className, getStyles, isDisabled, isFocused, isSelected } = props;
const styles = {
alignItems: 'center',
backgroundColor: isFocused
? token('color.background.transparentNeutral.hover', N20)
: 'transparent',
color: isDisabled ? token('color.text.disabled', 'inherit') : 'inherit',
display: 'flex ',
paddingBottom: 4,
paddingLeft: `${gridSize() * 2}px`,
paddingTop: 4,
boxShadow: isFocused
? `inset 2px 0px 0px ${token('color.text.selected', B400)};`
: '',
':active': {
backgroundColor: token(
'color.background.transparentNeutral.pressed',
N30,
),
},
'@media screen and (-ms-high-contrast: active)': {
borderLeft: isFocused ? '2px solid transparent' : '',
},
};
const augmentedStyles: InterpolationWithTheme<any> = {
...getStyles('option', props),
...styles,
};
const bemClasses = {
option: true,
'option--is-disabled': isDisabled,
'option--is-focused': isFocused,
'option--is-selected': isSelected,
};
// maintain react-select API
return [augmentedStyles, cx(bemClasses, className) as string];
};
// maintains function shape
const backgroundColor = themed({
light: token('color.background.subtleNeutral.resting', N0),
dark: token('color.background.subtleNeutral.resting', DN10),
});
const transparent = themed({ light: 'transparent', dark: 'transparent' });
// state of the parent option
interface ControlProps {
isActive?: boolean;
isDisabled?: boolean;
isFocused?: boolean;
isSelected?: boolean;
}
// the primary color represents the outer or background element
const getPrimaryColor = ({
isActive,
isDisabled,
isFocused,
isSelected,
...rest
}: ControlProps): string => {
let color: ThemedValue<string> = backgroundColor;
if (isDisabled && isSelected) {
color = themed({
light: token('color.background.disabled', B75),
dark: token('color.background.disabled', DN200),
});
} else if (isDisabled) {
color = themed({
light: token('color.background.disabled', N20A),
dark: token('color.background.disabled', DN10),
});
} else if (isSelected && isActive) {
color = themed({
light: token('color.background.boldBrand.pressed', B75),
dark: token('color.background.boldBrand.pressed', B200),
});
} else if (isActive) {
color = themed({
light: token('color.background.subtleBrand.pressed', B75),
dark: token('color.background.subtleBrand.pressed', B200),
});
} else if (isFocused && isSelected) {
color = themed({
light: token('color.background.boldBrand.hover', B300),
dark: token('color.background.boldBrand.hover', B75),
});
} else if (isFocused) {
color = themed({
light: token('color.background.default', N0),
dark: token('color.background.default', DN30),
});
} else if (isSelected) {
color = themed({
light: token('color.background.boldBrand.resting', B400),
dark: token('color.background.boldBrand.resting', B100),
});
}
return color(rest);
};
// the secondary color represents the radio dot or checkmark
const getSecondaryColor = ({
isActive,
isDisabled,
isSelected,
...rest
}: ControlProps): string => {
let color: ThemedValue<string> = themed({
light: token('color.background.default', N0),
dark: token('color.background.default', DN10),
});
if (isDisabled && isSelected) {
color = themed({
light: token('color.text.disabled', N70),
dark: token('color.text.disabled', DN10),
});
} else if (isActive && isSelected && !isDisabled) {
color = themed({
light: token('color.background.default', B400),
dark: token('color.background.default', DN10),
});
} else if (!isSelected) {
color = transparent;
}
return color(rest);
};
// the border color surrounds the checkbox/radio
const getBorderColor = ({
isActive,
isDisabled,
isFocused,
isSelected,
...rest
}: ControlProps): string => {
if (isDisabled && isSelected) {
return token('color.background.disabled', B400);
} else if (isDisabled) {
return token('color.background.disabled', N100);
} else if (isSelected && isActive) {
return token('color.background.boldBrand.pressed', B400);
} else if (isActive) {
return token('color.background.boldBrand.resting', B400);
} else if (isFocused && isSelected) {
return token('color.background.boldBrand.hover', B400);
} else if (isFocused) {
return token('color.border.neutral', N100);
} else if (isSelected) {
return token('color.background.boldBrand.resting', B400);
}
return token('color.border.neutral', N100);
};
interface OptionState {
isActive?: boolean;
}
class ControlOption<
Option = OptionType,
IsMulti extends boolean = false
> extends Component<OptionProps<Option, IsMulti>, OptionState> {
state: OptionState = { isActive: false };
onMouseDown = () => this.setState({ isActive: true });
onMouseUp = () => this.setState({ isActive: false });
onMouseLeave = () => this.setState({ isActive: false });
render() {
const {
getStyles,
Icon,
children,
innerProps,
innerRef,
...rest
} = this.props;
// prop assignment
const props = {
...innerProps,
onMouseDown: this.onMouseDown,
onMouseUp: this.onMouseUp,
onMouseLeave: this.onMouseLeave,
};
const [styles, classes] = getPrimitiveStyles({ getStyles, ...rest });
return (
<div css={styles} className={classes} ref={innerRef} {...props}>
<div
css={{
alignItems: 'center',
display: 'flex ',
flexShrink: 0,
paddingRight: '4px',
// Here we are adding a border to the Checkbox and Radio SVG icons
// This is an a11y fix for Select only for now but it may be rolled
// into the `@atlaskit/icon` package's Checkbox and Radio SVGs later
'& svg rect, & svg circle:first-of-type': {
stroke: getBorderColor({ ...this.props, ...this.state }),
strokeWidth: '2px',
strokeLinejoin: 'round',
},
}}
>
{!!Icon ? (
<Icon
label=""
primaryColor={getPrimaryColor({ ...this.props, ...this.state })}
secondaryColor={getSecondaryColor({
...this.props,
...this.state,
})}
/>
) : null}
</div>
<div
css={{
textOverflow: 'ellipsis',
overflowX: 'hidden',
flexGrow: 1,
whiteSpace: 'nowrap',
}}
>
{children}
</div>
</div>
);
}
}
export const CheckboxOption: FC<OptionProps<OptionType, true>> = (props) => (
<ControlOption<OptionType, true> Icon={CheckboxIcon} {...props} />
);
export const RadioOption: FC<OptionProps> = (props) => (
<ControlOption Icon={RadioIcon} {...props} />
);
|
extern crate crossbeam;
extern crate failure;
extern crate num_cpus;
extern crate regex;
extern crate reqwest;
extern crate select;
extern crate threadpool;
extern crate rayon;
use failure::Error;
use select::document::Document;
use std::fs::File;
use std::path::Path;
// use std::io::prelude::*;
use select::predicate::Name;
use std::io::BufWriter;
// use reqwest::{Client, ClientBuilder};
use std::sync::mpsc::channel;
use std::sync::Arc;
use threadpool::ThreadPool;
use std::collections::HashMap;
use rayon::prelude::*;
mod crawler;
// mod ndbc_crawler;
use crawler::Crawler;
fn filter_catalog(text: &str, href: &str) -> bool {
if text.ends_with('/') && href.ends_with(".html") {
true
} else {
false
}
}
fn get_station_info(node: select::node::Node) -> (String, &str) {
let station_id: String = node.text();
let station_href: &str = node.attr("href")
.expect("Cannot gather station's catalog href");
(station_id, station_href)
}
fn run() -> Result<(), Error> {
let root_url: &str = "https://dods.ndbc.noaa.gov/thredds/catalog/data/";
let fileserver_root_url: &str = "https://dods.ndbc.noaa.gov/thredds/fileServer/data/";
let catalog_url: &str = "https://dods.ndbc.noaa.gov/thredds/catalog/data/stdmet/catalog.html";
let catalog_ext: &str = ".html";
let nc_ext: &str = ".nc";
let to_replace: &str = "catalog.html?dataset=data/";
// let root_out: &str = "/home/meidhy/work/data/insitu/ndbc/";
let root_out: &str = "/home/ansible/tmp/datasets/insitu/ndbc/ndbc_reqw/";
let n_workers = 16;
let pool = ThreadPool::new(n_workers);
let crawl: Crawler = Crawler::with_pool_size(32);
let fpl = crawl.list_file_by_ext(catalog_url, catalog_ext)?;
println!(
">> '{}' contains '{}' '{}' files.",
catalog_url,
fpl.len(),
catalog_ext,
);
let n_jobs = fpl.len();
let arc_catalog_url = Arc::new(catalog_url);
let (tx, rx) = channel();
for fp in fpl {
let tx = tx.clone();
println!(">> '{}'", fp);
let crawl: Crawler = Crawler::with_pool_size(4);
let _catalog_url = arc_catalog_url.clone();
pool.execute(move || {
let station_url: &str = &_catalog_url.replace("/catalog.html", &format!("/{}", &fp));
// println!("{}", station_url);
tx.send({
let nc_fpl = crawl
.list_file_by_ext(station_url, nc_ext)
.expect("Fail to gather nc file list.");
let mut file_hashmap: HashMap<String, String> = HashMap::new();
// let mut file_hashmap: Vec<Vec<String, String>> = vec![vec![]];
for nc_fp in &nc_fpl {
let fin = nc_fp.replace(&to_replace, &fileserver_root_url);
let fout = nc_fp.replace(&to_replace, root_out);
file_hashmap.insert(fin, fout);
// file_hashmap.push(vec![fin, fout]);
}
Crawler::download_hashmap(file_hashmap).expect("Fail to download HashMap.");
nc_fpl
// ()
}).expect("Fail to send nc crawler.")
});
}
drop(tx);
for t in rx.iter() {
println!("{:>4} files downloaded.", t.len());
}
// rx.iter().take(n_jobs).collect::<()>();
Ok(())
}
fn main() {
run().expect("Reqwesting things doesn't work...");
let url: &str = "https://dods.ndbc.noaa.gov/thredds/fileServer/data/stdmet/ykrv2/ykrv2h2017.nc";
let fp_out: &str = "/home/meidhy/work/data/insitu/ndbc/";
// get_single_file(url, fp_out).expect("Unable to request the file.");
}
|
import pandas as pd
df = pd.read_csv("./data/dataset.txt",sep="/", names=["row"]).dropna()
print(df.head(7))
|
package jdregistry.client.internal.client
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import jdregistry.client.api.auth.Authenticate
import jdregistry.client.api.auth.DockerRegistryAuthenticationException
import jdregistry.client.api.DockerRegistryClientException
import jdregistry.client.api.DockerRegistryGetClient
import jdregistry.client.internal.http.OK
import jdregistry.client.internal.http.UNAUTHORIZED
import jdregistry.client.internal.withQuery
import jdregistry.client.payload.DockerRegistryRepositories
import jdregistry.client.payload.DockerRegistryTags
import jdregistry.client.data.RepositoryName as DockerRepositoryName
import jdregistry.client.http.IHttpGetClient
import jdregistry.client.http.IHttpResponse
import java.net.URI
/**
* Implementation of the Docker Registry Client Interface for V2 Docker Registry.
*
* @author Lukas Zimmermann
* @since 0.0.1
*
*/
internal class DefaultGetClient(
override val uri: URI,
private val client: IHttpGetClient,
private val auth: Authenticate? = null
) : DockerRegistryGetClient {
private val mapper = jacksonObjectMapper()
// Generates the V2 endpoint from Host and Port parameters
private val endpointV2 = uri.resolve("/v2/")
// Catalog URI
private val catalog = endpointV2.resolve("/v2/_catalog")
/**
* Peforms a GET request to the registry URI and tries to read the returned value when the request
* performs successfully
*
*/
private inline fun <reified T : Any> readGetResponse(uri: URI): T {
val response = client.get(uri)
val statusCode = response.statusCode
return when (statusCode) {
OK -> return mapper.readValue(response.body)
// Here we implement the protocol of the Docker Registry to solve the authentication challenge
UNAUTHORIZED -> performAuthenticationChallenge(response, uri)
else -> throw DockerRegistryClientException(
"Docker Registry has replied with status code $statusCode", statusCode, uri)
}
}
private fun bearer(token: String) = "Bearer $token"
private inline fun <reified T : Any> performAuthenticationChallenge(
response: IHttpResponse,
originalURI: URI
): T {
if (auth == null) {
throw DockerRegistryAuthenticationException(
"Docker Registry requires authentication, but username/password was not provided")
}
// Extract the Authenticate challenge from the response headers
val challenge = response.authenticate
?: throw DockerRegistryAuthenticationException(
"Docker Registry returned 401, but no authentication challenge was provided!")
// Fold the Value String of the response headers to the challenge attributes
val challengeAttributes: MutableMap<String, String> = challenge
.map(Companion::extractKeyValuePairs)
.fold(mutableMapOf()) { acc, m -> acc.putAll(m); acc }
// Get the realm and remove from the challenge attribute
val realm = challengeAttributes[REALM_KEY]?.let { URI.create(it) }
?: throw DockerRegistryAuthenticationException(
"Authenticate Header is present, but no realm was specified")
challengeAttributes.remove(REALM_KEY)
// TODO The challenge Attributes can contain advice for the charset of the Base64 encoding
val challengeResponse = this.client.get(
realm.withQuery(challengeAttributes, keepOld = true),
auth.authorization())
// If the response status is not 200, we could not get a bearer token
if (challengeResponse.statusCode != OK) {
throw DockerRegistryAuthenticationException("Failed to retrieve bearer token")
}
val token = mapper.readValue<BearerToken>(challengeResponse.body).token
// Retry the original URI with the auth token
val newReponse = this.client.get(originalURI, bearer(token))
return mapper.readValue(newReponse.body)
}
override fun listRepositories(): DockerRegistryRepositories =
readGetResponse(this.catalog)
override fun listTags(repository: DockerRepositoryName): DockerRegistryTags =
readGetResponse(this.catalog.resolve("/v2/${repository.repr}/tags/list"))
override fun implementsV2RegistryAPI() = client.get(endpointV2).statusCode == 200
companion object {
// Regex used to extract key value pairs from header strings
private val extractRegex = Regex("([a-z]+)=\"([^\"]*)\"")
private const val REALM_KEY = "realm"
private fun extractKeyValuePairs(input: String) =
extractRegex.findAll(input).map {
val groupValues = it.groupValues
groupValues[1] to groupValues[2]
}.toMap()
}
private data class BearerToken(
@JsonProperty("token")
val token: String,
@JsonProperty("expires_in")
val expires_in: Int,
@JsonProperty("issued_at")
val issued_at: String
)
}
|
using System.Collections.Generic;
using UnityEngine;
public class LocalizationManager : MonoBehaviour
{
protected LocalizationManager() { }
private static LocalizationManager _instance;
private static Dictionary<string, LocalizationLanguage> localizationLists;
public LocalizationManager GetInstance
{
get
{
SetInstance();
return _instance;
}
set
{
_instance = value;
}
}
private void SetInstance()
{
if (_instance == null)
{
_instance = this;
}
else if (_instance != gameObject)
{
Destroy(gameObject);
}
DontDestroyOnLoad(_instance);
}
private void SetLocalization()
{
Debug.LogError("SET LOCALIZATION");
localizationLists = new Dictionary<string, LocalizationLanguage>();
}
private void Awake()
{
SetInstance();
SetLocalization();
}
}
public class LocalizationLanguage : ScriptableObject
{
private Dictionary<string, string> _localTranslation;
public Dictionary<string, string> LocalTranslation
{
get
{
return _localTranslation;
}
private set
{
_localTranslation = value;
}
}
}
|
import { IssueCode } from './cspell.cache';
describe('Cache', () => {
test('IssueCode', () => {
const codes = [IssueCode.UnknownWord, IssueCode.ForbiddenWord, IssueCode.KnownIssue];
const sum = codes.reduce((a, b) => a + b, 0);
expect(sum).toBe(IssueCode.ALL);
});
});
|
package com.gnopai.ji65.config;
import com.gnopai.ji65.parser.TokenStream;
import com.gnopai.ji65.scanner.Token;
import com.gnopai.ji65.scanner.TokenType;
import lombok.Value;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.gnopai.ji65.scanner.TokenType.*;
import static java.util.stream.Collectors.toMap;
public class ConfigParser {
private final TokenStream tokenStream;
public ConfigParser(TokenStream tokenStream) {
this.tokenStream = tokenStream;
}
public List<ConfigBlock> parse() {
List<ConfigBlock> blocks = new ArrayList<>();
while (tokenStream.hasMore()) {
blocks.add(parseBlock());
}
return blocks;
}
private ConfigBlock parseBlock() {
Token identifier = tokenStream.consume(TokenType.IDENTIFIER, "Expected block identifier");
tokenStream.consume(LEFT_BRACE, "Expected block starting brace");
List<ConfigSegment> allSegments = new ArrayList<>();
while (!tokenStream.match(RIGHT_BRACE)) {
allSegments.add(parseSegment());
}
return new ConfigBlock(identifier.getLexeme(), allSegments);
}
private ConfigSegment parseSegment() {
Token identifier = tokenStream.consume(IDENTIFIER, "Expected segment identifier");
tokenStream.consume(COLON, "Expected colon");
List<Attribute> attributes = new ArrayList<>();
attributes.add(parseSingleAttribute());
while (!tokenStream.match(SEMICOLON)) {
tokenStream.match(COMMA); // optional comma between attributes
attributes.add(parseSingleAttribute());
}
Map<String, Token> attributeMap = attributes.stream()
.collect(toMap(Attribute::getIdentifier, Attribute::getValue));
return new ConfigSegment(identifier.getLexeme(), attributeMap);
}
private Attribute parseSingleAttribute() {
Token identifier = tokenStream.consume(IDENTIFIER, "Expected attribute identifier");
tokenStream.consume(EQUAL, "Expected equal sign");
Token value = consumeAttributeValue();
return new Attribute(identifier.getLexeme(), value);
}
private Token consumeAttributeValue() {
Token value = tokenStream.consume();
switch (value.getType()) {
case NUMBER:
case STRING:
case IDENTIFIER:
return value;
default:
throw tokenStream.error("Invalid attribute value");
}
}
@Value
private static class Attribute {
String identifier;
Token value;
}
}
|
/**
* Houses artifacts that help build data responses from Jira source system.
*
* @author KFK884
*
*/
package com.capitalone.dashboard.datafactory.jira;
|
make clean
make html
cp -rT _build/html ../maps/
make latexpdf
|
if [ -z "$1" ]; then
echo '请添加描述'
exit 0
fi
git add *
git commit -m "$1"
git pull
git push
|
#01. Records' Count
SELECT COUNT(`id`) AS 'count'
FROM wizzard_deposits;
#02. Longest Magic Wand
SELECT MAX(`magic_wand_size`) AS 'longest_magic_wand'
FROM `wizzard_deposits`;
#03. Longest Magic Wand per Deposit Groups
SELECT `deposit_group`, MAX(`magic_wand_size`) AS 'longest_magic_wand'
FROM `wizzard_deposits`
GROUP BY `deposit_group`
ORDER BY `longest_magic_wand` ASC, `deposit_group` ASC;
#04. Smallest Deposit Group per Magic Wand Size*
SELECT `deposit_group`
FROM `wizzard_deposits`
GROUP BY `deposit_group`
ORDER BY AVG(`magic_wand_size`) ASC
LIMIT 1;
#05. Deposits Sum
SELECT `deposit_group`, ROUND(SUM(`deposit_amount`), 2) AS 'total_sum'
FROM `wizzard_deposits`
GROUP BY `deposit_group`
ORDER BY `total_sum` ASC;
#06. Deposits Sum for Ollivander family
SELECT `deposit_group`, ROUND(SUM(`deposit_amount`), 2) AS 'total_sum'
FROM `wizzard_deposits`
WHERE `magic_wand_creator` = 'Ollivander family'
GROUP BY `deposit_group`
ORDER BY `deposit_group` ASC;
#07. Deposits Filter
SELECT `deposit_group`, ROUND(SUM(`deposit_amount`), 2) AS 'total_sum'
FROM `wizzard_deposits`
WHERE `magic_wand_creator` = 'Ollivander family'
GROUP BY `deposit_group`
HAVING `total_sum` < 150000
ORDER BY `total_sum` DESC;
#08. Deposit charge
SELECT `deposit_group`, `magic_wand_creator`, MIN(`deposit_charge`)
FROM `wizzard_deposits`
GROUP BY `deposit_group`, `magic_wand_creator`
ORDER BY `magic_wand_creator` ASC, `deposit_group` ASC;
#09. Age Groups
SELECT
CASE
WHEN `age` BETWEEN 0 AND 10 THEN '[0-10]'
WHEN `age` BETWEEN 11 AND 20 THEN '[11-20]'
WHEN `age` BETWEEN 21 AND 30 THEN '[21-30]'
WHEN `age` BETWEEN 31 AND 40 THEN '[31-40]'
WHEN `age` BETWEEN 41 AND 50 THEN '[41-50]'
WHEN `age` BETWEEN 51 AND 60 THEN '[51-60]'
ELSE '[61+]'
END AS 'age_group',
COUNT(`age`) AS 'wizard_count'
FROM
`wizzard_deposits`
GROUP BY `age_group`
ORDER BY `age_group`;
#10. First Letter
SELECT
LEFT(`first_name`, 1) AS 'first_letter'
FROM
`wizzard_deposits`
WHERE
`deposit_group` = 'Troll Chest'
GROUP BY `first_letter`
ORDER BY `first_letter`;
#11. Average Interest
SELECT
`deposit_group`, `is_deposit_expired`, AVG(`deposit_interest`)
FROM
`wizzard_deposits`
WHERE DATE(deposit_start_date) > '1985-01-01'
GROUP BY `deposit_group`, `is_deposit_expired`
ORDER BY `deposit_group` DESC;
#12. Rich Wizard, Poor Wizard*
SELECT SUM(table_with_diff.difference_between_two_deposites) AS 'sum_difference'
FROM
(
SELECT
(wd1.deposit_amount-
(
SELECT wd2.deposit_amount
FROM wizzard_deposits AS wd2
WHERE wd2.id = wd1.id + 1
)
) AS 'difference_between_two_deposites'
FROM wizzard_deposits AS wd1
) AS table_with_diff;
#13. Employees Minimum Salaries
SELECT `department_id`, MIN(`salary`) AS 'minimum_salary'
FROM `employees`
WHERE `department_id` IN (2, 5, 7) AND DATE(`hire_date`) > '2000-01-01'
GROUP BY `department_id`
ORDER BY `department_id` ASC;
#14. Employees Average Salaries
CREATE TABLE `employees_earn_30000`
SELECT * FROM `employees`
WHERE`salary` > 30000;
DELETE FROM `employees_earn_30000`
WHERE (`manager_id` = 42);
UPDATE `employees_earn_30000`
SET `salary` = `salary` + 5000
WHERE `department_id`= 1;
SELECT `department_id`, AVG(`salary`) AS `avg_salary`
FROM `employees_earn_30000`
GROUP BY `department_id`
ORDER BY `department_id` ASC;
#15. Employees Maximum Salaries
SELECT `department_id`, MAX(`salary`) AS `max_salary`
FROM `employees`
GROUP BY `department_id`
HAVING `max_salary`> 70000 OR `max_salary` < 30000
ORDER BY `department_id` ASC;
#16. Employees Count Salaries
SELECT COUNT(`salary`)
FROM `employees`
WHERE manager_id IS NULL
ORDER BY `department_id` ASC;
#17. 3rd Highest Salary*
SELECT
`department_id`,
(SELECT DISTINCT
`e2`.`salary`
FROM
`employees` AS `e2`
WHERE
`e2`.`department_id` = `e1`.`department_id`
ORDER BY `e2`.`salary` DESC
LIMIT 1 OFFSET 2) AS `third_highest_salary`
FROM
`employees` AS `e1`
GROUP BY `department_id`
HAVING `third_highest_salary` IS NOT NULL;
#18. Salary Challenge**
SELECT
`e`.`first_name`, `e`.`last_name`, `e`.`department_id`
FROM
`employees` AS `e`
JOIN
(SELECT
`department_id`, AVG(`salary`) AS 'dep_avg_salary'
FROM
`employees`
GROUP BY `department_id`) AS `avrg` ON `e`.`department_id` = `avrg`.`department_id`
WHERE
`salary` > `avrg`.`dep_avg_salary`
ORDER BY `department_id`
LIMIT 10;
#19. Departments Total Salaries
SELECT `department_id`, SUM(`salary`) AS 'total_salary'
FROM `employees`
GROUP BY `department_id`
ORDER BY `department_id` ASC;
|
namespace AspNetCore.Mvc.Extensions.FluentMetadata
{
public class PersonConfig : ModelMetadataConfiguration<Person>
{
public PersonConfig()
{
Configure(p => p.Name).Required();
Configure<string>("Name").Required();
}
}
public class Person
{
public string Name { get; set; }
}
}
|
googlechromepkg)
name="Google Chrome"
type="pkg"
#
# Note: this url acknowledges that you accept the terms of service
# https://support.google.com/chrome/a/answer/9915669
#
downloadURL="https://dl.google.com/chrome/mac/stable/accept_tos%3Dhttps%253A%252F%252Fwww.google.com%252Fintl%252Fen_ph%252Fchrome%252Fterms%252F%26_and_accept_tos%3Dhttps%253A%252F%252Fpolicies.google.com%252Fterms/googlechrome.pkg"
expectedTeamID="EQHXZ8M8AV"
updateTool="/Library/Google/GoogleSoftwareUpdate/GoogleSoftwareUpdate.bundle/Contents/Resources/GoogleSoftwareUpdateAgent.app/Contents/MacOS/GoogleSoftwareUpdateAgent"
updateToolArguments=( -runMode oneshot -userInitiated YES )
updateToolRunAsCurrentUser=1
;;
|
#!/bin/bash
declare -a files
files[1]=""
files[3]="52"
files[5]="54"
files[7]="56"
for i in "${files[@]}"
do
gcc -shared -Wall -fPIC \
`$1/bin/mod9.13 --cflags --libs` \
`pkg-config --cflags glib-2.0` \
-I/usr/include/python2.7 \
cuser_form${i}.c cuser_form${i}_wrap.c \
-o $1/modlib/modeller/_cuser_form${i}.so -lm -lmodeller
done;
|
import * as assert from '@aws-cdk/assert';
import * as lambda from '@aws-cdk/aws-lambda';
import * as ses from '@aws-cdk/aws-ses';
import * as cdk from '@aws-cdk/core';
import { EmailReceiver } from '../../src';
let stack: cdk.Stack;
beforeEach(() => {
stack = new cdk.Stack();
});
test('EmailReceiver', () => {
const fn = new lambda.Function(stack, 'Fn', {
code: lambda.Code.fromInline('export.handler=() => void;'),
runtime: lambda.Runtime.NODEJS_12_X,
handler: 'index.handler',
});
const ruleSet = ses.ReceiptRuleSet.fromReceiptRuleSetName(stack, 'RuleSet', 'rule-set');
new EmailReceiver(stack, 'EmailReceiver', {
recipients: ['support@cloudstructs.com'],
sourceWhitelist: '@amazon.com$',
function: fn,
receiptRuleSet: ruleSet,
});
expect(assert.SynthUtils.toCloudFormation(stack)).toMatchSnapshot();
});
|
#!/usr/bin/env bash
curl -LO 'http://nlp.stanford.edu/data/glove.840B.300d.zip'
unzip glove.840B.300d.zip
rm glove.840B.300d.zip
python glove2h5.py
|
ddnsclient
========
[](https://travis-ci.org/stumoss/ddnsclient)
Dynamic DNS updater which currently supports the ZoneEdit DNS service.
|
#!/bin/bash -e
#http://www.apache.org/licenses/LICENSE-2.0.txt
#
#
#Copyright 2016 Intel Corporation
#
#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.
GITVERSION=`git describe --always`
SOURCEDIR=$1
BUILDDIR=$SOURCEDIR/build
PLUGIN=`echo $SOURCEDIR | grep -oh "snap-plugin-.*"`
ROOTFS=$BUILDDIR/rootfs
BUILDCMD='go build -a -ldflags "-w"'
echo
echo "**** snap Plugin Build ****"
echo
# Disable CGO for builds
export CGO_ENABLED=0
# Clean build bin dir
rm -rf $ROOTFS/*
# Make dir
mkdir -p $ROOTFS
# Build plugin
echo "Source Dir = $SOURCEDIR"
echo "Building snap Plugin: $PLUGIN"
$BUILDCMD -o $ROOTFS/$PLUGIN
|
package twitter4j
import org.assertj.core.api.Assertions.assertThat
import org.junit.Ignore
import org.junit.Test
class BookmarksTest {
private val twitter2 by lazy { V2TestUtil.createOAuth2TwitterInstance() }
private val myId by lazy {
val me = twitter2.getMe().users[0]
// println(me)
me.id
}
@Test
@Ignore("expiration time of oauth2.accessToken is too short")
fun getBookmarks_full() {
val res = twitter2.getBookmarks(
myId,
V2DefaultFields.expansions,
10,
V2DefaultFields.mediaFields,
null,
V2DefaultFields.placeFields,
V2DefaultFields.pollFields,
V2DefaultFields.tweetFields,
V2DefaultFields.userFields
)
println(res)
// no dump
println("res.tweets.size: " + res.tweets.size)
println("res.meta.resultCount: " + res.meta?.resultCount)
assertThat(res.meta?.resultCount).isGreaterThanOrEqualTo(0)
}
@Test
@Ignore("expiration time of oauth2.accessToken is too short")
fun add_get_delete_get() {
// https://twitter.com/TwitterDevJP/status/1470916207130079239
val tweetId = 1470916207130079239L
println("addBookmark")
println("===========")
val bookmarked = twitter2.addBookmark(myId, tweetId)
assertThat(bookmarked.result).isTrue
// delay
println("delaying...")
Thread.sleep(1000)
println("getBookmarks")
println("============")
val res = twitter2.getBookmarks(
myId,
maxResults = 3,
)
println("recent bookmarks: " + res.tweets.map { it.id }.joinToString(","))
assertThat(res.tweets[0].id).isEqualTo(tweetId)
println("deleteBookmark")
println("==============")
val deleteResult = twitter2.deleteBookmark(myId, tweetId)
println(deleteResult)
assertThat(deleteResult.result).isFalse
}
}
|
package cz.levinzonr.spotie.presentation.screens.playlists
import cz.levinzonr.spotie.domain.models.Playlist
sealed interface PlaylistScreenEvent {
data class PlaylistClick(val item: Playlist): PlaylistScreenEvent
data class SearchQueryChange(val value: String): PlaylistScreenEvent
}
|
<?php
// +----------------------------------------------------------------------
// | AndOrTest.php [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2017 limingxinleo All rights reserved.
// +----------------------------------------------------------------------
// | Author: limx <715557344@qq.com> <https://github.com/limingxinleo>
// +----------------------------------------------------------------------
namespace Tests\Others;
use App\Biz\Calculater\Calculater;
use App\Biz\Objects\CallNext;
use Tests\UnitTestCase;
class FunctionTest extends UnitTestCase
{
public function testFunctionExec()
{
$res = exec(ROOT_PATH . '/echo.sh');
$this->assertEquals('Hi, limx', $res);
$res = exec(ROOT_PATH . '/echo2.sh');
$this->assertEquals('Hi, Agnes', $res);
}
public function testCalculater()
{
$params = [
1 => 1,
2 => 3,
10 => 22,
11 => 123
];
$string = '+ (1) (+ (1) (2))';
$result = Calculater::getInstance()->calculater($string, $params);
$this->assertEquals(5, $result);
$string = '+ (1) (+ (1) 2)';
$result = Calculater::getInstance()->calculater($string, $params);
$this->assertEquals(4, $result);
$string = '+ (1) (+ 1 (11))';
$result = Calculater::getInstance()->calculater($string, $params);
$this->assertEquals(125, $result);
}
public function testKnowCalculater()
{
$calculater = new \Know\Calculater\Calculater();
$string = '++ 1 4';
$this->assertEquals(7, $calculater->calculate($string, [1, 1, 1, 2, 3]));
$string = '+ 1 (4)';
$this->assertEquals(4, $calculater->calculate($string, [1, 1, 1, 2, 3]));
}
}
|
CREATE TABLE `customer` (
`customer_id` bigint(20) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`last_updated_by` varchar(25) DEFAULT NULL,
`updated` datetime NOT NULL,
`dob` datetime NOT NULL,
`email` varchar(50) NOT NULL,
`first_name` varchar(25) NOT NULL,
`last_name` varchar(25) NOT NULL,
`password` varchar(100) NOT NULL,
`customercol` varchar(45) DEFAULT NULL,
PRIMARY KEY (`customer_id`),
UNIQUE KEY `email_UNIQUE` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
CREATE TABLE `customer_order` (
`order_number` bigint(20) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`last_updated_by` varchar(25) DEFAULT NULL,
`updated` datetime NOT NULL,
`order_status` varchar(25) NOT NULL,
`order_status_reason` varchar(200) DEFAULT NULL,
`order_total` bigint(20) NOT NULL,
`customer_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`order_number`),
KEY `FKf9abd30bhiqvugayxlpq8ryq9` (`customer_id`),
CONSTRAINT `FKf9abd30bhiqvugayxlpq8ryq9` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`customer_id`)
) ENGINE=InnoDB AUTO_INCREMENT=790 DEFAULT CHARSET=utf8;
CREATE TABLE `customer_order_detail` (
`line_item_id` bigint(20) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`last_updated_by` varchar(25) DEFAULT NULL,
`updated` datetime NOT NULL,
`price` int(11) NOT NULL,
`product_code` varchar(25) NOT NULL,
`product_desc` varchar(50) NOT NULL,
`quantity` int(11) NOT NULL,
`order_number` bigint(20) DEFAULT NULL,
PRIMARY KEY (`line_item_id`),
KEY `FKovdiqxj2s9jx8b2ksdls7issw` (`order_number`),
CONSTRAINT `FKovdiqxj2s9jx8b2ksdls7issw` FOREIGN KEY (`order_number`) REFERENCES `customer_order` (`order_number`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
|
var test = require("testling")
, StreamStore = require("..")
, store = StreamStore()
test("stream store can get", function (t) {
var stream = store.get("foo")
t.ok(stream.write && stream.end, "stream is not stream")
t.end()
})
test("stream store can set", function (t) {
var bar = {}
store.set("foo", bar)
var stream = store.get("foo")
t.equal(bar, stream)
t.end()
})
test("stream store can have constructor", function (t) {
var store = StreamStore(function () {
return 42
})
var stream = store.get("foo")
t.equal(42, stream)
t.end()
})
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SongVisualizationApp.Util
{
class Utils
{
public static string GetTimeString(double secondsPassed)
{
int minutes = (int) Math.Floor(secondsPassed / 60);
int seconds = (int) Math.Floor(secondsPassed % 60);
string secondsString = seconds.ToString();
if (seconds < 10) secondsString = "0" + secondsString;
return minutes + ":" + secondsString;
}
}
}
|
{-# Language MultiParamTypeClasses #-}
{-# Language TypeSynonymInstances #-}
{-# Language FlexibleInstances #-}
--------------------------------------------------------------------------------
-- |
-- Module : Geometry.SetOperations.Merge
-- Copyright : (C) 2017 Maksymilian Owsianny
-- License : BSD-style (see LICENSE)
-- Maintainer : Maksymilian.Owsianny@gmail.com
--
-- Set Operations of Polytopes by BSP Merging.
--
--------------------------------------------------------------------------------
module Geometry.SetOperations.Merge
( BSP
, BSP3D, BSP2D
, Universe (..)
, universePlanes, universeBox
, splitRegion
, mergeBSPs
, trim
, makeBSP
, toBoundary
) where
import Protolude
import Prelude (id)
import Lens.Family (over)
import Lens.Family.Stock (both, _2)
-- import Control.Lens (over, both, _2)
import Data.Maybe (fromMaybe, fromJust)
import Linear
import Geometry.SetOperations.Types
import Geometry.SetOperations.BSP
import Geometry.SetOperations.Facet
import Geometry.SetOperations.CrossPoint
import Geometry.SetOperations.Clip
import Geometry.Plane.General
import Data.EqZero
type BSP2D = BSP Facet2D
type BSP3D = BSP Facet3D
--------------------------------------------------------------------------------
-- Arbitrary selected as sufficient by independent comity (not really).
universeSize :: Num n => n
universeSize = 500
clipPlanes :: Clip b v n => Facet b v n -> [Plane v n] -> Facet b v n
clipPlanes = foldr (\p f -> fromMaybe f $ clipFacet p f)
class Clip b v n => Universe b v n where
-- | Turn plane into a Facet by clipping it by the universe box.
makeFacet :: Plane v n -> Facet b v n
instance (Ord n, Fractional n, EqZero n) => Universe (FB2 V2 n) V2 n where
makeFacet p = clipPlanes baseFacet ps
where
baseFacet = Facet p (a, b)
Just a = makeCrossPoint (V2 p pa)
Just b = makeCrossPoint (V2 p pb)
(pa:pb:ps) = filter (not . isParallel p) universePlanes
instance (Ord n, Fractional n, EqZero n) => Universe (FB3 V3 n) V3 n where
makeFacet p = Facet p es
where
ps = filter (not . isParallel p) universePlanes
es = zipWith mkBd ps $ drop 1 $ cycle ps
mkBd a b = (fromJust . makeCrossPoint $ V3 p a b, b)
-- | Planes bounding the UniverseBox.
universePlanes :: (Applicative v, Traversable v, Num n) => [Plane v n]
universePlanes = positive ++ negative
where
toPlane v = Plane v universeSize
positive = map toPlane (basisFor $ pure 0)
negative = map flipPlane positive
-- | List of facets bounding the Universe.
universeBox :: (Universe b v n, Applicative v, Traversable v, Num n)
=> [Facet b v n]
universeBox = map makeFacet universePlanes
-- | Split a region within a Universe bounded by a list of Facets.
splitRegion :: (Universe b v n, Functor v, Num n)
=> Plane v n -> [Facet b v n] -> ([Facet b v n], [Facet b v n])
splitRegion h fs = (flipFacet lid : plusC, lid : minusC)
where
(plusC, minusC) = splitWith (splitFacet h) fs
lid = clipPlanes (makeFacet h) (map facetPlane fs)
{-
type Merge b v n =
(Universe b v n, Applicative v, Traversable v, Num n, Ord n, EqZero n)
-}
-- | Perform a given SetOperation of two BSPs by merging
mergeBSPs
:: (Universe b v n, Applicative v, Traversable v, Num n, Ord n, EqZero n)
=> SetOperation
-> BSP (Facet b v n)
-> BSP (Facet b v n)
-> BSP (Facet b v n)
mergeBSPs op (Node treeL p treeR) nodeR@(Node _ f _) =
collapse $ Node mTreeL p mTreeR
where
ff = facetPlane f
pp = facetPlane p
regions = splitRegion ff universeBox
(partL, partR) = partitionBSP regions pp nodeR
mTreeL = mergeBSPs op treeL partL
mTreeR = mergeBSPs op treeR partR
mergeBSPs op s1 s2 = setOperation op s1 s2
partitionBSP
:: (Universe b v n, Functor v, Foldable v, Num n, Ord n, EqZero n)
=> ([Facet b v n], [Facet b v n])
-> Plane v n
-> BSP (Facet b v n)
-> (BSP (Facet b v n), BSP (Facet b v n))
partitionBSP _ _ (Leaf c) = (Leaf c, Leaf c)
partitionBSP regions p (Node treeP f treeM) = case planesRelation p ff of
Parallel CoIncident CoOriented -> (treeP, treeM)
Parallel CoIncident AntiOriented -> (treeM, treeP)
othercase -> if
| null regionPR -> (Node treeP f treeML, treeMR)
| null regionMR -> (Node treePL f treeM, treePR)
| null regionPL -> (treeML, Node treeP f treeMR)
| null regionML -> (treePL, Node treePR f treeM)
| otherwise -> (Node treePL f treeML, Node treePR f treeMR)
where
ff = facetPlane f
(treePL, treePR) = partitionBSP (regionPL, regionPR) p treeP
(treeML, treeMR) = partitionBSP (regionML, regionMR) p treeM
(regionP , regionM ) = regions
(regionPL, regionPR) = splitRegion p regionP
(regionML, regionMR) = splitRegion p regionM
setOperation :: SetOperation -> BSP a -> BSP a -> BSP a
setOperation Union In set = In
setOperation Union Out set = set
setOperation Union set In = In
setOperation Union set Out = set
setOperation Intersection In set = set
setOperation Intersection Out set = Out
setOperation Intersection set In = set
setOperation Intersection set Out = Out
setOperation Difference In set = cmp set
setOperation Difference Out set = Out
setOperation Difference set In = Out
setOperation Difference set Out = set
setOperation SymmetricDifference In set = cmp set
setOperation SymmetricDifference Out set = set
setOperation SymmetricDifference set In = cmp set
setOperation SymmetricDifference set Out = set
collapse :: BSP n -> BSP n
collapse (Node In _ In ) = In
collapse (Node Out _ Out) = Out
collapse other = other
isBoundary :: Clip b v n => BSP (Facet b v n) -> Facet b v n -> Bool
isBoundary In _ = True
isBoundary Out _ = False
isBoundary (Node l s r) f = lcnd || rcnd
where
(lh, rh) = splitFacet (facetPlane s) f
lcnd = fromMaybe False (isBoundary l <$> lh)
rcnd = fromMaybe False (isBoundary r <$> rh)
-- | Optimize a resulting BSP after merging by removing superficial splitting
-- planes.
trim :: Clip b v n => BSP (Facet b v n) -> BSP (Facet b v n)
trim (Node Out f r)
| isBoundary r f = Node Out f (trim r)
| otherwise = trim r
trim (Node l f Out)
| isBoundary l f = Node (trim l) f Out
| otherwise = trim l
trim other = other
--------------------------------------------------------------------------------
-- | Make a BSP from a list of bounding facets.
makeBSP :: Clip b v n => [Facet b v n] -> BSP (Facet b v n)
makeBSP = constructBSP id
-- | Reconstruct boundary facets from the BSP.
toBoundary :: (Clip b v n, Functor v, Num n)
=> BSP (Facet b v n) -> [Facet b v n]
toBoundary bsp
= removeColors
. map (over _2 flipFacet)
. applyColors
$ destructBinaryTree bsp
where
applyColors xs = go xs bsp []
where
go [] _ = id
go fs In = foldr (\f cs -> ((True , f):) . cs) id fs
go fs Out = foldr (\f cs -> ((False, f):) . cs) id fs
go fs (Node l s r) = go ls l . go rs r
where
sp = facetPlane s
(ls, rs) = splitWith (splitFacet sp) fs
removeColors xs = go xs bsp []
where
go [] _ = id
go fs In = foldr (\(a,b) cs -> if not a then (b:) . cs else cs) id fs
go fs Out = foldr (\(a,b) cs -> if a then (b:) . cs else cs) id fs
go fs (Node l s r) = go ls l . go rs r
where
(ls, rs) = splitWith coloredSplit fs
sp = facetPlane s
coloredSplit (b, f) = over both (fmap (b,)) $ splitFacet sp f
|
#!/bin/bash
docker kill $(docker ps -a --filter name=kafka | grep -i kafka | cut -d " " -f1)
docker rm $(docker ps -a --filter name=kafka | grep -i kafka | cut -d " " -f1)
|
import { APIGatewayProxyResult } from 'aws-lambda';
class PaymentResponse implements APIGatewayProxyResult {
readonly headers = { 'Access-Control-Allow-Origin': '*' }; // CORS Support
readonly statusCode: number;
readonly body: string;
constructor(statusCode: number, body?: string) {
this.statusCode = statusCode;
this.body = JSON.stringify({ data: { sessionId: body } });
}
}
export default PaymentResponse;
|
exports.up = function(knex, Promise) {
return knex.schema.createTable(`provinces`, table => {
table.increments(`id`)
table.datetime(`registered_at`, { precision: 6 }).defaultTo(knex.fn.now(6))
table.datetime(`updated_at`, { precision: 6 }).defaultTo(knex.fn.now(6))
table.string(`name`).notNullable()
table.bigInteger(`recovered`).notNullable().defaultTo(0)
table.bigInteger(`death`).notNullable().defaultTo(0)
table.bigInteger(`positive`).notNullable().defaultTo(0)
table.datetime(`deleted_at`, { precision: 6 }).defaultTo(null)
})
}
exports.down = function(knex) {
return knex.schema.dropTable(provinces)
}
|
// @flow
import reducer from './reducer'
export { default as Breadcrumb } from './components/Breadcrumb'
export { default as InvoiceFormContainer } from './containers/InvoiceFormContainer'
export { default as InvoiceListContainer } from './containers/InvoiceListContainer'
export * from './actions'
export default reducer
|
import { expect } from 'chai'
import * as request from 'supertest'
import * as config from 'config'
import 'test/routes/expectations'
import { Paths } from 'dashboard/paths'
import { app } from 'main/app'
import * as idamServiceMock from 'test/http-mocks/idam'
import * as claimStoreServiceMock from 'test/http-mocks/claim-store'
import * as draftStoreMock from 'test/http-mocks/draft-store'
import * as data from 'test/data/entity/settlement'
import { attachDefaultHooks } from 'test/routes/hooks'
const cookieName: string = config.get<string>('session.cookieName')
const pagePath = Paths.dashboardPage.uri
const claimantContext = {
party: 'claimant',
id: claimStoreServiceMock.sampleClaimObj.submitterId,
ownMock: claimStoreServiceMock.resolveRetrieveByClaimantId,
otherMock: claimStoreServiceMock.resolveRetrieveByDefendantIdToEmptyList
}
const defendantContext = {
party: 'defendant',
id: claimStoreServiceMock.sampleClaimObj.defendantId,
ownMock: override => claimStoreServiceMock.resolveRetrieveByDefendantId(
claimStoreServiceMock.sampleClaimObj.referenceNumber,
this.id,
override
),
otherMock: claimStoreServiceMock.resolveRetrieveByClaimantIdToEmptyList
}
function testData () {
return [
{
status: 'Should show case settled when part-admit pay-by-set-date settlement reached',
claim: {
...data.claim,
...data.responses().partialAdmission,
...data.payBySetDateSettlementReachedPartyStatements()
},
claimantAssertions: [
'You’ve both signed a settlement agreement.'
],
defendantAssertions: [
'You’ve both signed a settlement agreement'
]
},
{
status: 'Should show case settled when full-admit pay-by-set-date settlement reached',
claim: {
...data.claim,
...data.responses().fullAdmission,
...data.payBySetDateSettlementReachedPartyStatements()
},
claimantAssertions: [
'You’ve both signed a settlement agreement.'
],
defendantAssertions: [
'You’ve both signed a settlement agreement'
]
},
{
status: 'Should show offer settlement reached',
claim: {
...data.claim,
...data.responses().partialAdmission,
...data.claimantResponses().acceptBySettlement,
...data.nonMonetaryOfferSettlementReachedPartyStatements()
},
claimantAssertions: [
'You’ve both signed a legal agreement.',
'The claim is now settled.'
],
defendantAssertions: [
'You’ve both signed a legal agreement.',
'The claim is now settled.'
]
},
{
status: 'Should show part-admit settlement rejected',
claim: {
...data.claim,
...data.responses().partialAdmission,
...data.claimantResponses().acceptWithNewPlan,
...data.defendantRejectsSettlementPartyStatements()
},
claimantAssertions: [
`${claimStoreServiceMock.sampleClaimObj.claim.defendants[0].name} has rejected your settlement agreement`,
'You can request a County Court Judgment against them'
],
defendantAssertions: [
'You rejected the settlement agreement'
]
},
{
status: 'Should show full-admit settlement rejected',
claim: {
...data.claim,
...data.responses().fullAdmission,
...data.claimantResponses().acceptWithNewPlan,
...data.defendantRejectsSettlementPartyStatements()
},
claimantAssertions: [
`${claimStoreServiceMock.sampleClaimObj.claim.defendants[0].name} has rejected your settlement agreement`,
'You can request a County Court Judgment against them'
],
defendantAssertions: [
'You rejected the settlement agreement'
]
},
{
status: 'Should show claimant accepted court plan part-admit settlement',
claim: {
...data.claim,
...data.responses().partialAdmission,
...data.claimantResponses().acceptsWithCourtPlan,
...data.claimantAcceptsCourtOfferPartyStatements()
},
claimantAssertions: [
'You’ve signed a settlement agreement.',
'The defendant can choose to sign it or not.'
],
defendantAssertions: [
`${claimStoreServiceMock.sampleClaimObj.claim.claimants[0].name} asked you to sign a settlement agreement`
]
},
{
status: 'Should show claimant accepted court plan full-admit settlement',
claim: {
...data.claim,
...data.responses().fullAdmission,
...data.claimantResponses().acceptsWithCourtPlan,
...data.claimantAcceptsCourtOfferPartyStatements()
},
claimantAssertions: [
'You’ve signed a settlement agreement.',
'The defendant can choose to sign it or not.'
],
defendantAssertions: [
`${claimStoreServiceMock.sampleClaimObj.claim.claimants[0].name} asked you to sign a settlement agreement`
]
}
]
}
describe('Settlement dashboard statuses dashboard', () => {
attachDefaultHooks(app)
testData().forEach(data => {
context(data.status, () => {
beforeEach(() => {
draftStoreMock.resolveFindNoDraftFound()
claimStoreServiceMock.resolveRetrievePaginationInfoEmptyList()
claimStoreServiceMock.resolveRetrievePaginationInfoEmptyList()
})
it(claimantContext.party, async () => {
claimantContext.ownMock(data.claim)
claimantContext.otherMock()
idamServiceMock.resolveRetrieveUserFor(claimantContext.id, 'citizen')
await request(app)
.get(pagePath)
.set('Cookie', `${cookieName}=ABC`)
.expect(res => expect(res).to.be.successful.withText(...data.claimantAssertions))
})
it(defendantContext.party, async () => {
defendantContext.ownMock(data.claim)
defendantContext.otherMock()
idamServiceMock.resolveRetrieveUserFor(defendantContext.id, 'citizen')
await request(app)
.get(pagePath)
.set('Cookie', `${cookieName}=ABC`)
.expect(res => expect(res).to.be.successful.withText(...data.defendantAssertions))
})
})
})
})
|
package com.appmanager.android.app;
import android.os.Bundle;
import android.text.Html;
import android.text.util.Linkify;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.appmanager.android.R;
public class LicenseActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_license);
createContent();
}
@Override
public boolean onOptionsItemSelected(final MenuItem menu) {
if (menu.getItemId() == android.R.id.home) {
finish();
return true;
}
return false;
}
private void createContent() {
LayoutInflater inflater = LayoutInflater.from(this);
LinearLayout content = (LinearLayout) findViewById(R.id.content);
String[] softwareList = getResources().getStringArray(R.array.software_list);
String[] licenseList = getResources().getStringArray(R.array.license_list);
content.addView(createHtmlTextNoMargin(getString(R.string.msg_license)));
content.addView(createItemsText(softwareList));
for (int i = 0; i < softwareList.length; i++) {
content.addView(createDivider(inflater));
content.addView(createHeader(softwareList[i]));
content.addView(createHtmlText(licenseList[i]));
}
}
private TextView createHeader(final String name) {
String s = "<big><b>" + name + "</b></big>";
return createHtmlText(s, 8);
}
private TextView createItemsText(final String... names) {
StringBuilder s = new StringBuilder();
for (String name : names) {
if (s.length() > 0) {
s.append("<br>");
}
s.append("・");
s.append(name);
}
return createHtmlText(s.toString(), 8);
}
private TextView createHtmlText(final String s) {
return createHtmlText(s, 8);
}
private TextView createHtmlTextNoMargin(final String s) {
return createHtmlText(s, 0);
}
private TextView createHtmlText(final String s, final int margin) {
TextView text = new TextView(this);
text.setAutoLinkMask(Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES);
text.setText(Html.fromHtml(s));
text.setTextColor(getResources().getColor(R.color.text_license));
LinearLayout.LayoutParams layoutParams =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
int marginPx = (0 < margin) ? (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, margin,
getResources().getDisplayMetrics()) : 0;
layoutParams.setMargins(0, marginPx, 0, marginPx);
text.setLayoutParams(layoutParams);
return text;
}
private View createDivider(final LayoutInflater inflater) {
View view = inflater.inflate(R.layout.divider, null);
int marginPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0.6f,
getResources().getDisplayMetrics());
if (marginPx < 1) {
marginPx = 1;
}
view.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
marginPx));
return view;
}
}
|
---
pid: proverb
title: 'Genre: Proverb'
label: Proverb
collection: genre_pieterbruegel
layout: genrepage_pieterbruegel
order: '05'
permalink: "/pieterbruegel/genres/proverb/"
---
|
-- =============================================
-- Author: Md Abul Kalam
-- Create date: 18 Sept, 2020
-- Description: SP for getting Year by Model
-- =============================================
CREATE PROCEDURE [dbo].[vehicles_Year_GetYearsByProductModel]
@MODELID INT
AS
SET NOCOUNT ON;
SELECT DISTINCT Y.[Description], Y.[ID]
FROM Year Y WITH (NOLOCK)
INNER JOIN ModelMaster MM WITH (NOLOCK)
ON Y.ID = MM.YearID
WHERE MM.ProductID = @MODELID
AND Y.[EffectiveDate] <= GETDATE()
ORDER BY Y.[Description] DESC;
RETURN 0
|
<?php
namespace App\Http\Controllers;
use App\Admin;
use App\Guest;
use App\User;
use Illuminate\Http\Request;
class UtilController extends Controller
{
public static function user($user)
{
switch ($user->token()->name) {
case 'User Personal Access Token':
$user = User::find($user->id);
break;
case 'Admin Personal Access Token':
$user = Admin::find($user->id);
break;
case 'Guest Personal Access Token':
$user = Guest::find($user->id);
break;
}
return $user;
}
}
|
import aiosparkapi.requests
from .api.messages import Messages
from .api.webhooks import Webhooks
from .api.people import People
from .api.memberships import Memberships
from .api.rooms import Rooms
import aiohttp
class AioSparkApi:
def __init__(self, *, access_token):
self._token = access_token
async def setup(self):
self._client = aiohttp.ClientSession()
self._requests = aiosparkapi.requests.Requests(
self._token,
self._client,
baseurl='https://api.ciscospark.com/v1')
self.messages = Messages(self._requests)
self.webhooks = Webhooks(self._requests)
self.people = People(self._requests)
self.memberships = Memberships(self._requests)
self.rooms = Rooms(self._requests)
def close(self):
self._client.close()
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, tb):
self.close()
__all__ = ['AioSparkApi']
|
<?php
namespace addons\epay\controller;
use addons\epay\library\Service;
use think\addons\Controller;
/**
* API接口控制器
*
* @package addons\epay\controller
*/
class Api extends Controller
{
protected $config = [];
public function _initialize()
{
parent::_initialize();
}
/**
* 默认方法
*/
public function index(){
$this->error();
}
/**
* 支付成功回调
*/
public function notify(){
$type = $this->request->param('type');
$pay = Service::checkNotify($type);
if (!$pay) {
echo '签名错误';
return;
}
//你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
//下面这句必须要执行,且在此之前不能有任何输出
echo $pay->success();
return;
}
/**
* 支付成功返回
*/
public function returnx()
{
$type = $this->request->param('type');
$result = Service::checkReturn($type);
if (!$result) {
$this->error('签名错误');
}
//你可以在这里定义你的提示信息,但切记不可在此编写逻辑
$this->success("恭喜你!支付成功!", addon_url("epay/index/index"));
return;
}
}
|
# launchpad ppa建立
## v101 kylin-desktop ppa
创建new ppa时,URL添加:
```shell
kylin-desktop/v101-kylin-desktop
```
其中,v101-kylin-desktop为添加的PPA仓库名,和下面的display name保持一致。
|
//
// Created by gyb on 2021/11/15.
//
#include "splc_log.hpp"
void LogLSErrorTL(int type, int line, const char *msg) {
ls_error_occur = true;
// FILE *fp = fopen(log_file_name, "a+");
// if (type == 0) {
// fprintf(fp, "Error type A at Line %d: %s\n", line, msg);
// }
// if (type == 1) {
// fprintf(fp, "Error type B at Line %d: %s\n", line, msg);
// }
// fclose(fp);
}
void LogSemanticErrorTL(int type, int line, const char *msg) {
semantic_error_occur = true;
FILE *fp = fopen(log_file_name, "a+");
fprintf(fp, "Error type %d at Line %d: %s\n", type, line, msg);
fclose(fp);
}
|
using System.ComponentModel;
using Sample.Validation;
using Spectre.Cli;
namespace Sample.Commands
{
public sealed class BuildSettings : CommandSettings
{
[ValidateProjectName] // For validating an argument in isolation.
[CommandArgument(0, "<PROJECT>")]
[Description("Specifies the project file.")]
public string Project { get; set; }
[CommandOption("-p|--password <VALUE>")]
[Description("The password to use.")]
public string Password { get; set; }
[CommandOption("--no-restore")]
[Description("Doesn't perform an implicit restore during build.")]
public bool NoRestore { get; set; }
[CommandOption("--force-restore")]
[Description("Forces a restore during build.")]
public bool ForceRestore { get; set; }
[CommandOption("--serve [PORT]")]
[DefaultValue(8080)]
[Description("Serves the content on the specified port.\nDefaults to port [grey]8080[/]")]
public FlagValue<int> Serve { get; set; }
// For validating arguments together.
public override ValidationResult Validate()
{
if (NoRestore && ForceRestore)
{
return ValidationResult.Error("Both --no-restore and --force-restore have been specified.");
}
return base.Validate();
}
}
}
|
package com.qiniudemo.baseapp
import com.hapi.refresh.SmartRecyclerView
import kotlinx.android.synthetic.main.act_smart_recy.*
abstract class CommonRecyclerFragment<T> : RecyclerFragment<T>() {
override val mSmartRecycler: SmartRecyclerView
by lazy { smartRecyclerView }
override fun getLayoutId(): Int {
return com.qiniu.baseapp.R.layout.act_smart_recy
}
}
|
import VInput from './VInput';
export { VInput };
export default VInput;
//# sourceMappingURL=index.js.map
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Nuuvify.CommonPack.Extensions.Implementation
{
public static class DistinctExtension
{
/// <summary>
/// Substitua o "and" por "duplo e comercial"
/// <example>
/// <code>
/// IEnumerable{Produto} produtosSemRepeticao =
/// produtos.Distinct((p1, p2) =>
/// p1.Nome == p2.Nome and
/// p1.CodigoNbm = p2.CodigoNbm,
/// x => x.GetHashCode()
/// );
/// </code>
/// </example>
/// </summary>
/// <param name="source"></param>
/// <param name="comparerEquals"></param>
/// <param name="comparerGetHashCode"></param>
/// <typeparam name="TSource"></typeparam>
/// <returns></returns>
public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source,
Func<TSource, TSource, bool> comparerEquals,
Func<TSource, int> comparerGetHashCode)
{
var resultDistinct = source.Distinct(
new CustomGenericComparer<TSource>(
comparerEquals,
comparerGetHashCode)
);
return resultDistinct;
}
}
}
|
import React from 'react';
import FiDataWaitSvg from '../../assets/illustrations/factory-illustration-1.svg';
import { IContentStateImages } from '../../types/react-component-input-types';
const FiDataWait: React.FC<IContentStateImages> = ({ height, width, imgHeight }) => {
return (
<>
<div className='text-center d-flex' style={{ height: height }}>
<div className='text-center m-auto'>
<img style={{ height: imgHeight, width: width }} src={FiDataWaitSvg} alt='Processing data' />
<div data-testid='page-error-message' className='mt-1'>
We have asked the financial institutions for providing your data. <br />
This page will refresh as soon as we have the data.
</div>
</div>
</div>
</>
);
};
export { FiDataWait };
|
# frozen_string_literal: true
module Dappgen
class Interpreter
def initialize(script, machine)
@script = script
@machine = machine
end
def built_script
@built_script ||= @script.built_script
end
def run!
built_script.each do |statement|
args = [
statement.first.first,
statement.first[1]
]
options = statement.to_a[1..-1].to_h
args << options unless options.empty?
@machine.public_send(*args)
end
end
end
end
|
#include "Precomp.h"
#include "DisassemblyPage.h"
#include "UObject/UClass.h"
#include "UObject/UClient.h"
#include "UI/Controls/ListView/ListView.h"
#include "ExpressionItemBuilder.h"
#include "VM/Bytecode.h"
DisassemblyPage::DisassemblyPage(View* parent) : VBoxView(parent)
{
listview = new ListView(this);
listview->setExpanding();
listview->addColumn("Expression", 500);
listview->addColumn("Name", 150);
listview->addColumn("Value", 200, true);
addClass("disassemblypage");
listview->addClass("disassemblypage-listview");
}
void DisassemblyPage::setFunction(UStruct* func)
{
listview->clearList();
if (func)
{
int index = 0;
for (Expression* expr : func->Code->Statements)
{
listview->rootItem()->add(ExpressionItemBuilder::createItem("Statement[" + std::to_string(index) + "]", expr));
index++;
}
}
}
|
<div class="sidenav">
<a href="#about">About</a>
<a href="#services">Services</a>
<a href="#clients">Clients</a>
<a href="#contact">Contact</a>
</div>
|
// Once the server start we will monitor for
function idleLogout() {
var timmer;
window.onload = resetTimer;
window.onmousemove = resetTimer;
window.onmousedown = resetTimer; // catches touchscreen presses as well
window.ontouchstart = resetTimer; // catches touchscreen swipes as well
window.onclick = resetTimer; // catches touchpad clicks as well
window.onkeydown = resetTimer;
window.addEventListener('scroll', resetTimer, true); //
async function logout() {
alert("You have been idle for 5 minutes, logging you out.")
const response = await fetch('/api/users/logout', {
method: 'post',
headers: { 'Content-Type': 'application/json' }
});
if (response.ok) {
//console.log("response of function log out good")
alert("Logging you out")
document.location.replace('/');
} else {
alert("You are already logged out")
}
}
function resetTimer() {
clearTimeout(timmer);
timmer = setTimeout(logout, 300000); // will automatically log you out in 5 minutes.
}
}
idleLogout();
|
package ledger
import (
"github.com/nknorg/nkn/core/contract/program"
"github.com/nknorg/nkn/core/transaction"
)
type HeaderInfo struct {
Version uint32 `json:"version"`
PrevBlockHash string `json:"prevBlockHash"`
TransactionsRoot string `json:"transactionsRoot"`
Timestamp int64 `json:"timestamp"`
Height uint32 `json:"height"`
ConsensusData uint64 `json:"consensusData"`
NextBookKeeper string `json:"nextBookKeeper"`
WinnerHash string `json:"winningHash"`
WinnerType byte `json:"winningHashType"`
Signer string `json:"signer"`
ChordID string `json:"chordID"`
Signature string `json:"signature"`
Program program.ProgramInfo `json:"program"`
Hash string `json:"hash"`
}
type BlocksInfo struct {
Hash string `json:"hash"`
Header *HeaderInfo `json:"header"`
Transactions []*transaction.TransactionInfo `json:"transactions"`
}
|
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
use deno_core::deno_buf;
use deno_core::{StartupData, StartupScript};
pub fn deno_isolate_init() -> StartupData {
if cfg!(feature = "no-snapshot-init") {
debug!("Deno isolate init without snapshots.");
#[cfg(not(feature = "check-only"))]
let source_bytes =
include_bytes!(concat!(env!("GN_OUT_DIR"), "/gen/bundle/main.js"));
#[cfg(feature = "check-only")]
let source_bytes = vec![];
StartupData::Script(StartupScript {
filename: "gen/bundle/main.js".to_string(),
source: std::str::from_utf8(source_bytes).unwrap().to_string(),
})
} else {
debug!("Deno isolate init with snapshots.");
#[cfg(not(any(feature = "check-only", feature = "no-snapshot-init")))]
let data =
include_bytes!(concat!(env!("GN_OUT_DIR"), "/gen/snapshot_deno.bin"));
#[cfg(any(feature = "check-only", feature = "no-snapshot-init"))]
let data = vec![];
unsafe {
StartupData::Snapshot(deno_buf::from_raw_parts(data.as_ptr(), data.len()))
}
}
}
pub fn compiler_isolate_init() -> StartupData {
if cfg!(feature = "no-snapshot-init") {
debug!("Deno isolate init without snapshots.");
#[cfg(not(feature = "check-only"))]
let source_bytes =
include_bytes!(concat!(env!("GN_OUT_DIR"), "/gen/bundle/compiler.js"));
#[cfg(feature = "check-only")]
let source_bytes = vec![];
StartupData::Script(StartupScript {
filename: "gen/bundle/compiler.js".to_string(),
source: std::str::from_utf8(source_bytes).unwrap().to_string(),
})
} else {
debug!("Deno isolate init with snapshots.");
#[cfg(not(any(feature = "check-only", feature = "no-snapshot-init")))]
let data =
include_bytes!(concat!(env!("GN_OUT_DIR"), "/gen/snapshot_compiler.bin"));
#[cfg(any(feature = "check-only", feature = "no-snapshot-init"))]
let data = vec![];
unsafe {
StartupData::Snapshot(deno_buf::from_raw_parts(data.as_ptr(), data.len()))
}
}
}
|
export default [
{
path: 'projects/:id(\\d+)',
name: 'ProjectsView',
component: () => import('@/js/views/projects/View'),
props: route => ({
id: route.params.id
})
},
{
path: 'projects',
name: 'ProjectsIndex',
component: () => import('@/js/views/projects/Index'),
}
]
|
import { ApiProperty } from '@nestjs/swagger';
import { AuditableEntity } from 'src/common/entity/auditable.entity';
import { Column, Entity } from 'typeorm';
@Entity()
export class User extends AuditableEntity {
@ApiProperty()
@Column({ type: 'varchar', length: 30 })
name: string;
@ApiProperty()
@Column({ type: 'varchar', length: 15, unique: true })
username: string;
@ApiProperty()
@Column({ type: 'varchar', length: 255 })
password: string;
}
|
package tv.codely.api_scala_http.module.course.dependency_injection
import tv.codely.api_scala_http.module.course.application.{CourseCreator, CoursesSearcher}
import tv.codely.api_scala_http.module.course.repository.InMemoryCourseRepository
final class CourseModuleDependencyContainer {
val repository = new InMemoryCourseRepository
val coursesSearcher = new CoursesSearcher(repository)
val courseCreator = new CourseCreator(repository)
}
|
<?php
header("Content-type: text/css; charset: UTF-8");
$adminTheme = erLhAbstractModelAdminTheme::fetch((int)$Params['user_parameters']['id']);
if ($adminTheme instanceof erLhAbstractModelAdminTheme) {
$tpl = erLhcoreClassTemplate::getInstance('lhtheme/admincss.tpl.php');
$tpl->set('theme',$adminTheme);
$tpl->set('cssAttributes', $adminTheme->css_attributes_array);
echo $tpl->fetch();
}
exit;
?>
|
#!/bin/bash
# This allows Python to access Fortran's internal memory!
gfortran -x f95-cpp-input -c readr.f90
f2py -c readr.f90 -m readr --opt='-O3 -x f95-cpp-input'
gfortran -x f95-cpp-input -c amr2cell_rur.f90
f2py -c amr2cell_rur.f90 -m a2c --opt='-O3 -x f95-cpp-input'
|
use num_derive::FromPrimitive;
use super::coils::Coil;
pub type Address = u16;
pub type Quantity = u16;
pub type Value = u16;
pub type Values= Vec<u16> ;
pub type Coils= Vec<Coil> ;
#[derive(FromPrimitive)]
pub enum FunctionCode{
ReadCoils = 0x01,
ReadDiscreteInputs = 0x02,
ReadHoldingRegisters = 0x03,
ReadInputRegisters = 0x04,
WriteSingleCoil = 0x05,
WriteSingleRegister = 0x06,
WriteMultipleCoils = 0x0f,
WriteMultipleRegisters = 0x10,
}
pub enum ModbusFunction<'a> {
ReadCoils(Address, Quantity),
ReadDiscreteInputs(Address, Quantity),
ReadHoldingRegisters(Address, Quantity),
ReadInputRegisters(Address, Quantity),
WriteSingleCoil(Address, Coil),
WriteSingleRegister(Address, Value),
WriteMultipleCoils(Address, &'a Coils),
WriteMultipleRegisters(Address, &'a Values),
}
|
; RUN: llc < %s -mtriple=aarch64-eabi -mattr=+v8.2a,+fullfp16 | FileCheck %s
declare <4 x half> @llvm.fma.v4f16(<4 x half>, <4 x half>, <4 x half>)
declare <8 x half> @llvm.fma.v8f16(<8 x half>, <8 x half>, <8 x half>)
define dso_local <4 x half> @t_vfma_f16(<4 x half> %a, <4 x half> %b, <4 x half> %c) {
; CHECK-LABEL: t_vfma_f16:
; CHECK: fmla v0.4h, v2.4h, v1.4h
; CHECK-NEXT: ret
entry:
%0 = tail call <4 x half> @llvm.fma.v4f16(<4 x half> %b, <4 x half> %c, <4 x half> %a)
ret <4 x half> %0
}
define dso_local <8 x half> @t_vfmaq_f16(<8 x half> %a, <8 x half> %b, <8 x half> %c) {
; CHECK-LABEL: t_vfmaq_f16:
; CHECK: fmla v0.8h, v2.8h, v1.8h
; CHECK-NEXT: ret
entry:
%0 = tail call <8 x half> @llvm.fma.v8f16(<8 x half> %b, <8 x half> %c, <8 x half> %a)
ret <8 x half> %0
}
|
<?php
use RCDE\Model\CosTecnic;
use RCDE\Translation\Escola;
require_once ROOT . '/../src/Utils/ordinal.php';
/**
* @var CosTecnic $entrenador
* @var Escola $e
*/
?>
<div class="col-lg-3 col-md-4 p-3 text-center user-card">
<div class="transform-center p-3 avatar-cos-tecnic">
<?php
$nom_entrenador = str_replace(' ', '-', mb_strtolower($entrenador->nom_complet));
if (file_exists(ROOT . "/assets/img/entrenadors/$nom_entrenador.webp")): ?>
<img src="/assets/img/entrenadors/<?= $nom_entrenador ?>.webp"
class="img-fit transform-center rounded-circle"
width="96" height="96" alt="<?= $entrenador->nom_complet ?>">
<?php else: ?>
<i class="fas fa-5x fa-user-circle mb-3 mt-2 op-50"></i>
<?php endif ?>
</div>
<h5><?= $entrenador->nom_complet ?></h5>
<h6 class="badge badge-pill badge-<?= match ($entrenador->id_rol_costecnic) {
1 => 'warning',
2 => 'primary',
3 => 'success',
} ?>"><?= $e->t($entrenador->rol_costecnic) ?></h6>
<p class="text-translucent">
<?= $e->t('season', null, ordinal($entrenador->count_temporades, locale: $_SESSION['LOCALE'])) ?>
</p>
</div>
|
package com.swengin.stardust.cafe.product;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class ProductRepository {
public List<Product> products() {
return List.of(new ProductBuilder().withName("Mocha").withPrice(3.45).build(),
new ProductBuilder().withName("Espresso").withPrice(2.75).build(),
new ProductBuilder().withName("Sandwich").withPrice(2.75).build(),
new ProductBuilder().withName("Croissant").withPrice(2.45).build(),
new ProductBuilder().withName("Cake").withPrice(2.45).build());
}
}
|
"""Implementation of the weather command."""
from mcipc.rcon.client import Client
from mcipc.rcon.commands.weather import WeatherProxy
__all__ = ['WeatherProxy', 'weather']
def weather(self: Client) -> WeatherProxy:
"""Delegates to a
:py:class:`mcipc.rcon.je.commands.weather.WeatherProxy`
"""
return WeatherProxy(self, 'weather')
|
#!/usr/bin/env bash
# The project directory path.
# Remove the scripts folder in case this bash script is being executed from the scripts folder
# instead of from the project root folder.
project_dir=$(pwd)
project_dir=${project_dir/scripts/""}
# Deploy the ipk file to the SEPP on the EM.
scp -P2223 *.ipk root@localhost:/home/root/georges/apps
|
package de.chrisward.theyworkforyou.dagger
import dagger.Module
import dagger.android.ContributesAndroidInjector
import de.chrisward.theyworkforyou.view.LordListFragment
import de.chrisward.theyworkforyou.view.MPListFragment
@Module
abstract class FragmentModule {
@ContributesAndroidInjector
abstract fun contributeMPListFragment(): MPListFragment
@ContributesAndroidInjector
abstract fun contributeLordListFragment(): LordListFragment
}
|
# -*- coding: utf-8 -*-
# @Author: zengjq
# @Date: 2020-10-21 13:48:07
# @Last Modified by: zengjq
# @Last Modified time: 2020-10-21 14:02:40
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 94 mem 100
def deleteDuplicates1(self, head):
if not head:
return
h = c = prev = head
while c.next:
c = c.next
if prev.val == c.val:
prev.next = c.next
else:
prev = c
return h
# 58 mem 100
def deleteDuplicates(self, head):
if not head:
return
c = head
while c.next:
if c.val == c.next.val:
c.next = c.next.next
else:
c = c.next
return head
if __name__ == '__main__':
l1 = ListNode(1)
l1.next = ListNode(1)
l1.next.next = ListNode(2)
l1.next.next.next = ListNode(3)
l1.next.next.next.next = ListNode(3)
l1 = ListNode(1)
l1.next = ListNode(1)
l1.next.next = ListNode(1)
s = Solution()
r = s.deleteDuplicates(l1)
print(r)
while(r):
print(r.val)
r = r.next
|
package eu.spitfire_project.ld4s.resource.link;
public class LinkReview {
private String author = null;
private double vote = 0;
private String comment = null;
private String datetime = null;
private String linkuri = null;
public LinkReview(String author, double vote, String comment, String datetime){
this.author = author;
this.vote = vote;
this.comment= comment;
this.datetime = datetime;
}
public LinkReview(){
new LinkReview(null, 0.0, null, null);
}
public void setAuthor(String author) {
this.author = author;
}
public String getAuthor() {
return author;
}
public void setVote(double vote) {
this.vote = vote;
}
public double getVote() {
return vote;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getComment() {
return comment;
}
public void setDatetime(String datetime) {
this.datetime = datetime;
}
public String getDatetime() {
return datetime;
}
public void setLink(String link) {
this.linkuri = link;
}
public String getLink() {
return linkuri;
}
}
|
module Neo4j::Driver
module Internal
module Util
class Format
def initialize
raise java.lang.UnsupportedOperationException
end
# formats map using ':' as key-value separator instead of default '='
class << self
def format_pairs(entries)
case entries.size
when 0
'{}'
when 1
"#{key_value_string(entries.first)}"
else
builder = ""
builder << "{"
builder << key_value_string(entries.first)
entries.each do |entry|
builder << ","
builder << " "
builder << key_value_string(entry)
end
builder << "}"
end
end
private def key_value_string(entry)
"#{entry.keys.first}:#{entry.values.first}"
end
end
end
end
end
end
|
# OpenMined explained in sequences
> 🖼 say more than a 💯 words
## How do I get my network trained?
The following graph shows you how **OpenMined** can be used to train a model in a decentralized way where everyone is able to contribute to AI but keep their data to themselves. The basic workflow is the following:
* Explain stuff according to docs 🤗

|
import React from "react";
import {Col} from "react-bootstrap";
import ProjectsImg from "../../assets/projects.jpg"
import BlogImg from "../../assets/blog.jpg"
import {navigate} from "gatsby";
import {PaddedRow, StyledImage, StyledButton, StyledContainer} from "../../config/styles"
const Landing = ({lang}) => (<StyledContainer>
<PaddedRow>
<Col>
<h3> {lang["mainTitle"]} </h3>
<p style={{"maxWidth": "75%"}}> {lang["mainText"]} </p>
<StyledButton onClick={() => navigate("/" + localStorage.getItem("lang").toLowerCase() + "/about")}>
{lang["btnText"]}
</StyledButton>
</Col>
</PaddedRow>
<PaddedRow>
<Col xs={6}
md={4}>
<StyledImage src={ProjectsImg}/>
</Col>
<Col xs={12}
md={8}>
<h5> {lang["projectsTitle"]} </h5>
<p> {lang["projectsText"]} </p>
<StyledButton onClick={() => navigate("/" + localStorage.getItem("lang").toLowerCase() + "/projects")}>
{lang["btnText"]}
</StyledButton>
</Col>
</PaddedRow>
<PaddedRow>
<Col xs={12}
md={8}>
<h5> {lang["blogTitle"]} </h5>
<p> {lang["blogText"]} </p>
<StyledButton onClick={() => navigate("/" + localStorage.getItem("lang").toLowerCase() + "/blog")}>
{lang["btnText"]}
</StyledButton>
</Col>
<Col xs={6}
md={4}>
<StyledImage src={BlogImg}/>
</Col>
</PaddedRow>
</StyledContainer>
);
export default Landing;
|
/*
* Counter.cpp
* MAMClient
*
* Created by Marc Addeo on 10/4/08.
* Copyright 2008 __MyCompanyName__. All rights reserved.
*
*/
#include "Counter.h"
Counter::Counter( void )
{
this->first = NULL;
this->second = NULL;
}
Counter::~Counter( void )
{
}
void Counter::reset( void )
{
this->first = NULL;
this->second = NULL;
}
void Counter::operator ++( int )
{
this->first++;
if ( this->first == 256 )
{
this->first = NULL;
this->second++;
}
if ( this->second == 256 )
this->second = NULL;
}
|
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class Sample : MonoBehaviour
{
public List<int> list = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
void Start()
{
this.list.Enqueue(10);
DebugLog("Enque(10) : ");
Debug.Log("Deque : " + this.list.Dequeue());
DebugLog("Deque : ");
Debug.Log("Peek : " + this.list.Peek());
DebugLog("Peek : ");
this.list.Push(11);
DebugLog("Push(11) : ");
Debug.Log("Pop : " + this.list.Pop());
DebugLog("Pop : ");
this.list.RemoveRange(0, 3);
DebugLog("RemoveRange(0, 3) : ");
this.list = this.list.Slice(3, 3).ToList();
DebugLog("Slice(3, 3) : ");
this.list.Shuffle();
DebugLog("Shuffle : ");
Debug.Log("Random : " + this.list.Random()
+ "-" + this.list.Random()
+ "-" + this.list.Random());
}
void DebugLog(string message)
{
foreach (var i in list) { message += i + ", "; }
Debug.Log(message);
}
}
|
module Alchemy
class FoldedPage < ActiveRecord::Base
belongs_to :page
belongs_to :user
end
end
|
---
title: "Knowledge 19's Hackthon, a personal look"
subtitle: ""
summary: ""
date: 2019-05-21T20:25:56-05:00
---
In my last post I said, "The hackathon is a great place to learn a new
feature but it's not a hackathon. They expect you to have the app
prebuilt before you get there." I just want to be very clarify in this
post.
I learned a lot from the hackathon, but what they want is not a
hackathon.
I'll recap the events up until we left.
# Week of April 22nd
I reviewed all past Knowledge hackathons I could find and aggregated
them on my
[blog](https://blog.jace.pro/post/2019-04-22-knowledge-hackathon-past/).
Trying to get some ideas for what might be a winning idea if executed
properly.
# Week of April 29th
I finally get some ideas worth anything down on paper so I don't have to
go without an idea. I am really excited about this. A past co-worker of
mine Kevin, found out he's going to K19, cause I found a unused ticket.
So that's awesome, I have a hackathon team and I have some decent ideas.
I lay out some tasks for each idea.
# May 6th
I arrive in Vegas, it's great. I meet up with some colleagues and get
checked in. Also was given access to the "HackNow" instance. Seems
security isn't that important here so all the past submissions all
exist. I'll export that and include link at the bottom.
# May 7th
I see my hackathon team mates getting coffee. We talk about the ideas
and pick one. Great. We do some morning labs and then meet up at the
CreatorCon hackathon area. Thirty minutes after the start of the event
we get our instance. Great.
The idea we are working on is this "LendIt" app. Using the new mobile
interface allows users/ groups to indicate they have things to lend out,
and if lent, who it's lent to. Pretty simple idea but you could apply
this to whatever at work or if part of group of neighbors could be
something to facilitate passing around a leaf blower, or other lawn
equipment.
Our tasks as we see them;
- Build the table for the things to be lent.
- Build a table to allow people to queue for things to be lent later.
- Build table to support who has borrowed the thing.
- Make some rules to control the availability and to process the queue
- Make a Mobile App
Now we can do a lot of this stuff at the same time and so I take on the
Mobile App stuff and the other two work out the business rules and table
structure.
## The first problem
I am working on this and creating the stuff only to find that when I
save the Mobile App nothing seems to be committing to the database. So
after about an hour and half of banging my head on the table I get up
and walk over to the "Mobile" experts and show them what's happening.
They are perplexed and bring me to another expert who has me check my
version. Low and behold we found the problem. We're not on Madrid. We're
on some beta unnamed version with a build tag of
"glide-trackhinext-12-11-2015" and a build date of "11-13-2018\_1928".
Well Madrid wasn't done then and the Mobile stuff wasn't working by
then.

## The recovery
So we export our work to [git](https://github.com/jacebenson/lendIt) and
we move to one of our Madrid PDI's. We all have a "happy hour" we have
to go to with our work stuff and that's two hours. When we all get back
we're refreshed and good to go. I've taken a sorta leader role, Kevin
and Joe have taken more of the "Can Do" attitude. We get it all working
and then one of the judges comes by to check out our work. It must be
near the end of the night, but by the time he's come by and we've given
a pretty poor explanation of this, and shown what we have. He in other
words tells us it's just the platform and not at the level of the other
teams, but he doesn't use those words. Nope, instead what we took from
it was, it was a waste of his time, and everyone else time. Looking back
on it, it reminds me to the statement made in [Billy
Madison](https://www.youtube.com/watch?v=wKjxFJfcrcA). Rightly offended,
we pack up our shit and leave.
At a bar about 20 minutes later we realize you know we got more out of
this than any other lab and it was a good experience. No reason to let
Chris get us down. So that's the last hackathon I'll be in at a
knowledge event.
## Afterword
It's been a few weeks now and I didn't want to write this while
frustrated in the moment. I still feel the same way I did the night of.
Thanks! Now I know. The **hackathon** isn't a hackathon at the knowledge
events. It's a "Did you bring something cool that we can make a product
out of" event.
[Link of Ideas](./2019-app-list.xlsx)
|
[Seamless Gravel by Soady](https://www.blendernation.com/2015/11/22/free-download-seamless-gravel-texture/)
|
module Graphiti
# Apply sorting logic to the scope.
#
# By default, sorting comes 'for free'. To specify a custom sorting proc:
#
# class PostResource < ApplicationResource
# sort do |scope, att, dir|
# int = dir == :desc ? -1 : 1
# scope.sort_by { |x| x[att] * int }
# end
# end
#
# The sorting proc will be called once for each sort att/dir requested.
# @see Resource.sort
class Scoping::Sort < Scoping::Base
# @return [Proc, Nil] The custom proc specified by Resource DSL
def custom_scope
resource.sort_all
end
# Apply default scope logic via Resource adapter
# @return the scope we are chaining/modifying
def apply_standard_scope
each_sort do |attribute, direction|
resource.get_attr!(attribute, :sortable, request: true)
sort = resource.sorts[attribute]
if sort[:only] && sort[:only] != direction
raise Errors::UnsupportedSort.new resource,
attribute, sort[:only], direction
else
if sort[:proc]
@scope = sort[:proc].call(@scope, direction)
else
@scope = resource.adapter.order(@scope, attribute, direction)
end
end
end
@scope
end
# Apply custom scoping proc configured via Resource DSL
# @return the scope we are chaining/modifying
def apply_custom_scope
each_sort do |attribute, direction|
@scope = custom_scope
.call(@scope, attribute, direction, resource.context)
end
@scope
end
private
def each_sort
sort_param.each do |sort_hash|
attribute = sort_hash.keys.first
direction = sort_hash.values.first
yield attribute, direction
end
end
def sort_param
@sort_param ||= begin
if query_hash[:sort].blank?
resource.default_sort || []
else
normalize(query_hash[:sort])
end
end
end
def normalize(sort)
return sort if sort.is_a?(Array)
sorts = sort.split(',')
sorts.map do |s|
sort_hash(s)
end
end
def sort_hash(attr)
value = attr[0] == '-' ? :desc : :asc
key = attr.sub('-', '').to_sym
{ key => value }
end
end
end
|
# Pong
Godot3 implementation of the famous retro "Pong" game
AI is unbeatable for now ☠️

## Design
- First player to score 7 goals wins 🏆
## Controls
- Use the Escape key for the **Pause** menu
- Control player 1 with: "w" key for up and "s" key for down
- Control player 2 with: "arrow_up" key for up and "arrow_down" key for down
## Todo
- [ ] Add Screen Shake on goal
- [ ] Add Power Ups
- [ ] Freeze opponent
- [ ] scale paddle up a bit
|
/*
* ModeShape (http://www.modeshape.org)
*
* 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 org.modeshape.jcr.spi.index;
import java.security.NoSuchProviderException;
import javax.jcr.RepositoryException;
import org.modeshape.jcr.spi.index.provider.IndexProvider;
import org.modeshape.jcr.spi.index.provider.IndexProviderExistsException;
/**
* An interface for programmatically adding or removing index providers and index definitions.
*
* @author Randall Hauch (rhauch@redhat.com)
*/
public interface IndexManager extends org.modeshape.jcr.api.index.IndexManager {
/**
* Get the query index provider registered with the given name.
*
* @param name the name of the query index provider; may not be null
* @return the query index provider instance, or null if there is no provider registered with the supplied name
*/
IndexProvider getProvider( String name );
/**
* Register a new already-instantiated {@link IndexProvider}.
*
* @param provider the new provider instance; may not be null
* @throws IndexProviderExistsException if there is already an existing index provider with the same name
* @throws RepositoryException if there is a problem registering the provider
*/
void register( IndexProvider provider ) throws IndexProviderExistsException, RepositoryException;
/**
* Unregister the {@link IndexProvider} with the supplied name.
*
* @param providerName the name of the query index provider; may not be null
* @throws NoSuchProviderException there is no index provider with the supplied name
* @throws RepositoryException if there is a problem unregistering the provider
*/
void unregister( String providerName ) throws NoSuchProviderException, RepositoryException;
}
|
-- +migrate Down
UPDATE releases SET badge_ratings = NULL;
-- +migrate Up
|
import {
LOGIN_START,
LOGIN_SUCCESS,
LOGIN_FAILURE,
REGISTER_START,
REGISTER_SUCCESS,
REGISTER_FAILURE,
LOGOUT,
} from "../constants/auth.constants";
const AuthReducer = (state: any, action: { type: string; payload: any }) => {
switch (action.type) {
case LOGIN_START:
return {
user: null,
isFetching: true,
error: false,
};
case LOGIN_SUCCESS:
return {
user: action.payload,
isFetching: false,
error: false,
};
case LOGIN_FAILURE:
return {
user: null,
isFetching: false,
error: true,
};
case REGISTER_START:
return {
user: null,
isFetching: true,
error: false,
};
case REGISTER_SUCCESS:
return {
user: action.payload,
isFetching: false,
error: false,
};
case REGISTER_FAILURE:
return {
user: null,
isFetching: false,
error: true,
};
case LOGOUT:
return {
user: null,
isFetching: false,
error: false,
};
default:
return {
...state,
};
}
};
export default AuthReducer;
|
using UnityEngine;
using UnityEngine.Events;
namespace lisandroct.EventSystem
{
public interface IListener { void OnEventRaised(); }
#if UNITY_2020_1_OR_NEWER
public class Listener : MonoBehaviour, IListener
{
[SerializeField]
private GameEvent _event;
private GameEvent Event => _event;
[SerializeField]
private UnityEvent _response;
private UnityEvent Response => _response;
private void OnEnable() {
if (Event != null)
{
Event.Register(this);
}
}
private void OnDisable() {
if (Event != null)
{
Event.Unregister(this);
}
}
public void OnEventRaised() => Response?.Invoke();
}
#else
public class Listener : MonoBehaviour, IListener
{
[SerializeField]
private GameEvent _event;
private GameEvent Event => _event;
[SerializeField]
private UnityEvent _response;
private UnityEvent Response => _response;
private void OnEnable() {
if (Event != null)
{
Event.Register(this);
}
}
private void OnDisable() {
if (Event != null)
{
Event.Unregister(this);
}
}
public void OnEventRaised() => Response?.Invoke();
}
#endif
}
|
package com.swift.sandhook.blacklist;
import java.lang.reflect.Member;
import java.util.HashSet;
import java.util.Set;
public class HookBlackList {
public static Set<String> methodBlackList = new HashSet<>();
public static Set<Class> classBlackList = new HashSet<>();
public static Set<String> methodUseInHookBridge = new HashSet<>();
public static Set<String> methodUseInHookStub = new HashSet<>();
static {
methodBlackList.add("java.lang.reflect.Method.invoke");
methodBlackList.add("java.lang.reflect.AccessibleObject.setAccessible");
methodUseInHookBridge.add("java.lang.Class.getDeclaredField");
methodUseInHookBridge.add("java.lang.reflect.InvocationTargetException.getCause");
methodUseInHookStub.add("java.lang.Object.equals");
methodUseInHookStub.add("java.lang.Class.isPrimitive");
}
public final static boolean canNotHook(Member origin) {
if (classBlackList.contains(origin.getDeclaringClass()))
return true;
String name = origin.getDeclaringClass().getName() + "." + origin.getName();
return methodBlackList.contains(name);
}
public final static boolean canNotHookByBridge(Member origin) {
String name = origin.getDeclaringClass().getName() + "." + origin.getName();
return methodUseInHookBridge.contains(name);
}
public final static boolean canNotHookByStub(Member origin) {
String name = origin.getDeclaringClass().getName() + "." + origin.getName();
return methodUseInHookStub.contains(name);
}
}
|
# Copyright (c) 2019 The diadem authors
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
# ========================================================
"""
Run the experiment
Important sidemark: the Agent is defined in the parameters, not in the main file!
"""
try:
import debug_settings
except:
pass
import tensorflow as tf
from tensorflow.python.util import deprecation
deprecation._PRINT_DEPRECATION_WARNINGS = False
import sys
import os
from diadem.agents import AgentContext, AgentManager
from diadem.experiment import Experiment
from diadem.experiment.visualizers import OnlineVisualizer
from diadem.summary import PandasSummary, ConsoleSummary
from diadem.common import Params
from diadem.preprocessors import Normalization
from bark_ml.library_wrappers.lib_diadem.diadem_bark_environment import DiademBarkEnvironment
from bark.runtime.commons.parameters import ParameterServer
from bark_ml.environments.single_agent_runtime import SingleAgentRuntime
from bark_ml.observers.nearest_state_observer import NearestAgentsObserver
from bark_ml.environments.blueprints import DiscreteHighwayBlueprint
# create scenario
bark_params = ParameterServer()
bp = DiscreteHighwayBlueprint(bark_params,
number_of_senarios=10,
random_seed=0,
viewer=False)
observer = NearestAgentsObserver(bark_params)
runtime = SingleAgentRuntime(blueprint=bp,
observer=observer,
render=False)
def run_dqn_algorithm(parameter_files):
exp_dir = "tmp_exp_dir"
diadem_params = Params(filename=parameter_files)
environment = DiademBarkEnvironment(runtime=runtime)
context = AgentContext(
environment=environment,
datamanager=None,
preprocessor=None,
optimizer=tf.train.AdamOptimizer,
summary_service=ConsoleSummary()
)
agent = AgentManager(
params=diadem_params,
context=context
)
exp = Experiment(
params=diadem_params['experiment'],
main_dir=exp_dir,
context=context,
agent=agent,
visualizer=None)
exp.run()
# replace second parameter file with other defaults to get categorical, standard dqn or quantile agents
if __name__ == '__main__':
# basic Double DQN with Prioritized Experience Replay
# run_dqn_algorithm(parameter_files=["examples/example_params/common_parameters.yaml",
# "examples/example_params/dqn_distributional_quantile.yaml"])
run_dqn_algorithm(parameter_files=["bark_ml/examples/example_params/dqn_basic.yaml"])
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Sach;
use App\LoaiSach;
class SachController extends Controller
{
public function getDanhSach()
{
$sach = Sach::all();
return view('admin.sach.danhsach',['sach'=>$sach]);
}
public function getThem()
{
$loaisach = LoaiSach::all();
return view('admin.sach.them',['loaisach'=>$loaisach]);
}
public function postThem(Request $req)
{
$this->validate($req,
[
'name'=>'required|unique:LoaiSach,name|min:3',
'gia'=>'required'
],
[
'name.required'=>'Tên loại sách không được bỏ trống',
'name.unique'=>'Tên này đã tồn tại',
'name.min'=>'Tên tối thiểu 3 kí tự',
'gia.required'=>'Bạn chưa điền giá sách'
]
);
$sach = new Sach;
$sach->name = $req->name;
$sach->id_loai = $req->id_loai;
$sach->mota = $req->mota;
$sach->gia = $req->gia;
if ($req->hasFile('hinh')) {
$file = $req->file('hinh');
$name = $file->getClientOriginalName();
$file->move('source/image/sach',$name);
$sach->hinh = $name;
}
else{
$sach->hinh="";
}
$sach->save();
return redirect('admin/sach/them')->with('thongbao','Bạn đã thêm thành công');
}
public function getSua($id)
{
$loaisach = LoaiSach::all();
$ttsach = Sach::find($id);
return view('admin.sach.sua',['ttsach'=>$ttsach,'loaisach'=>$loaisach]);
}
public function postSua(Request $req, $id)
{
$this->validate($req,
[
'name'=>'required|unique:LoaiSach,name|min:3',
'gia'=>'required'
],
[
'name.required'=>'Tên loại sách không được bỏ trống',
'name.unique'=>'Tên này đã tồn tại',
'name.min'=>'Tên tối thiểu 3 kí tự',
'gia.required'=>'Bạn chưa điền giá sách'
]
);
$sach = Sach::find($id);
$sach->name = $req->name;
$sach->id_loai = $req->id_loai;
$sach->mota = $req->mota;
$sach->gia = $req->gia;
if ($req->hasFile('hinh')) {
$file = $req->file('hinh');
$name = $file->getClientOriginalName();
$file->move('source/image/sach',$name);
unlink('source/image/sach/'.$sach->hinh);
$sach->hinh = $name;
}
else{
$sach->hinh="";
}
$sach->save();
return redirect('admin/sach/sua/'.$id)->with('thongbao','Bạn đã sửa thành công');
}
public function getXoa($id)
{
$sach = Sach::find($id);
$sach->delete($id);
return redirect('admin/sach/danhsach')->with('thongbao','Bạn đã xóa thành công');
}
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import json
import os
import shutil
import subprocess
import sys
import markdown
default_template = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="date" content="%date%" scheme="YYYY-MM-DD">
<meta name="viewport" content="width=device-width" />
<title>%title%</title>
<link rel="stylesheet" href="%root_path%style.css" type="text/css"
media="screen" title="no title" charset="utf-8">
<link rel="stylesheet" href="%root_path%pygmentize.css" type="text/css"
media="screen" title="no title" charset="utf-8">
</head>
<body>
%content%
</body>
</html>
"""
default_extension = ["fenced_code", "tables", "codehilite"]
vim = shutil.which("vim") and "vim" or (shutil.which("nvim") and "nvim")
if vim:
# Retrieve auto index vimwiki option
with subprocess.Popen(
[vim, "-c", "echo g:vimwiki_dir_link", "-c", ":q", "--headless"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) as proc:
auto_index = proc.stderr.read() == b"index"
else:
auto_index = False
class LinkInlineProcessor(markdown.inlinepatterns.LinkInlineProcessor):
"""Fix wiki links"""
def getLink(self, *args, **kwargs):
href, title, index, handled = super().getLink(*args, **kwargs)
if not href.startswith("http") and not href.endswith(".html"):
if auto_index and href.endswith("/"):
href += "index.html"
elif not href.endswith("/"):
href += ".html"
return href, title, index, handled
def get(l, index, default):
return l[index] if index < len(l) else default
def main():
FORCE = sys.argv[1] # noqa - not supported
SYNTAX = sys.argv[2]
EXTENSION = sys.argv[3] # noqa - not supported
OUTPUT_DIR = sys.argv[4]
INPUT_FILE = sys.argv[5]
CSS_FILE = sys.argv[6] # noqa - not supported
TEMPLATE_PATH = get(sys.argv, 7, os.getenv("VIMWIKI_TEMPLATE_PATH", ""))
TEMPLATE_DEFAULT = get(
sys.argv, 8, os.getenv("VIMWIKI_TEMPLATE_DEFAULT", "")
)
TEMPLATE_EXT = get(sys.argv, 9, os.getenv("VIMWIKI_TEMPLATE_EXT", ""))
ROOT_PATH = get(sys.argv, 10, os.getenv("VIMWIKI_ROOT_PATH", os.getcwd()))
# Only markdown is supported
if SYNTAX != "markdown":
sys.stderr.write("Unsupported syntax: " + SYNTAX)
sys.exit(1)
# Asign template
template = default_template
template_file = (
os.path.join(TEMPLATE_PATH, TEMPLATE_DEFAULT) + TEMPLATE_EXT
)
if os.path.isfile(template_file):
with open(template_file, "rb") as f:
template = f.read().decode()
# Get output filename
filename, _ = os.path.splitext(os.path.basename(INPUT_FILE))
output_file = os.path.join(OUTPUT_DIR, filename + ".html")
# parse extension into dict
extensions_env = os.getenv(
"VIMWIKI_MARKDOWN_EXTENSIONS",
"{}",
)
try:
extensions = json.loads(extensions_env)
except json.decoder.JSONDecodeError:
# backward compatible
extensions = extensions_env.split(",")
if isinstance(extensions, list):
extensions = {e: {} for e in extensions}
extension_names = default_extension + list(extensions.keys())
# Setup markdown parser
md = markdown.Markdown(
extensions=extension_names,
extension_configs=extensions,
)
md.inlinePatterns.deregister("link")
md.inlinePatterns.register(
LinkInlineProcessor(markdown.inlinepatterns.LINK_RE, md), "link", 160
)
with open(INPUT_FILE, "rb") as f:
content = ""
placeholders = {}
# Retrieve vimwiki placeholders
for line in f:
line = line.decode()[:-1]
if line.startswith("%nohtml"):
sys.exit(0)
elif line.startswith("%title"):
placeholders["%title%"] = line[7:]
elif line.startswith("%date"):
placeholders["%date%"] = line[6:]
elif line.startswith("%template"):
placeholders["template"] = line[10:]
else:
content += line + "\n"
# Set default values
if "%title%" not in placeholders:
placeholders["%title%"] = filename
if "%date%" not in placeholders:
placeholders["%date%"] = datetime.datetime.today().strftime(
"%Y-%m-%d"
)
if "template" in placeholders:
t = placeholders.pop("template")
template_file = os.path.join(TEMPLATE_PATH, t) + TEMPLATE_EXT
if os.path.isfile(template_file):
with open(template_file, "rb") as f:
template = f.read().decode()
# Parse template
for placeholder, value in placeholders.items():
template = template.replace(placeholder, value)
# use blank insted of os.getcwd() because - mean in root directory that contain css
template = template.replace(
"%root_path%", ROOT_PATH if ROOT_PATH != "-" else ""
)
# Parse content
content = md.convert(content)
# Merge template
template = template.replace("%content%", content)
with open(output_file, "wb") as o:
o.write(template.encode())
if __name__ == "__main__":
main()
|
% Als ich Künstler war *oder:* \
Von der Zähmung und Professionalisierung einer mythischen Freiheit, *oder:* \
der Künstler als Arbeiter
% Naomi Tereza Salmon
\pagebreak
\newpage
\pagestyle{headings}
## Anlagen
~~~~~ {#some-space}
~~~~~
***(separat gebunden)***
~~~~~ {#some-space}
~~~~~
*zur Dissertation:*
- Thesenpapier
- Bildtafeln
*Dokumentation Praktischer Teil:*
- KIOSK09-Katalog
- Der 5-Jahres-Plan
|
#!/bin/sh
# I don't know why, but the /usr/bin/python2.3 from Debian is a 30% slower
# than my own compiled version! 2004-08-18
python="/usr/local/bin/python2.3 -O"
writedata () {
nrows=$1
bfile=$2
worst=$3
psyco=$4
if [ "$shuffle" = "1" ]; then
shufflef="-S"
else
shufflef=""
fi
cmd="${python} search-bench.py -R ${worst} -b ${bfile} -h ${psyco} -l ${libcomp} -c ${complevel} ${shufflef} -w -n ${nrows} data.nobackup/bench-${libcomp}-${nrows}k.h5"
echo ${cmd}
${cmd}
}
readdata () {
nrows=$1
bfile=$2
worst=$3
psyco=$4
smode=$5
if [ "$smode" = "indexed" ]; then
#repeats=100
repeats=20
else
repeats=2
fi
cmd="${python} search-bench.py -R ${worst} -h -b ${bfile} ${psyco} -m ${smode} -r -k ${repeats} data.nobackup/bench-${libcomp}-${nrows}k.h5"
echo ${cmd}
${cmd}
return
}
overwrite=0
if [ $# > 1 ]; then
if [ "$1" = "-o" ]; then
overwrite=1
fi
fi
if [ $# > 2 ]; then
psyco=$2
fi
# Configuration for testing
#nrowslist="50000"
#nrowslistworst="50000"
# Normal test
#nrowslist="1 2 5 10 20 50 100 200 500 1000 2000 5000 10000 20000"
#nrowslistworst="1 2 5 10 20 50 100 200 500 1000 2000 5000 10000 20000"
nrowslist="1 2 5 10 20 50 100 200 500 1000"
nrowslistworst="1 2 5 10 20 50 100 200 500 1000"
#nrowslist="1 2 5 10"
#nrowslistworst="1 2 5 10"
# The next can be regarded as parameters
shuffle=1
for libcomp in none zlib lzo; do
#for libcomp in none lzo; do
if [ "$libcomp" = "none" ]; then
complevel=0
else
complevel=1
fi
# The name of the data bench file
bfile="worst-dbench-cl-${libcomp}-c${complevel}-S${shuffle}.h5"
# Move out a possible previous benchmark file
bn=`basename $bfile ".h5"`
mv -f ${bn}-bck2.h5 ${bn}-bck3.h5
mv -f ${bn}-bck.h5 ${bn}-bck2.h5
if [ "$overwrite" = "1" ]; then
echo "moving ${bn}.h5 to ${bn}-bck.h5"
mv -f ${bn}.h5 ${bn}-bck.h5
else
echo "copying ${bn}.h5 to ${bn}-bck.h5"
cp -f ${bn}.h5 ${bn}-bck.h5
fi
for worst in "" -t; do
#for worst in ""; do
# Write data files
if [ "$worst" = "-t" ]; then
echo
echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
echo "Entering worst case..."
echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
echo
nrowslist=$nrowslistworst
fi
# Write data file
for nrows in $nrowslist; do
echo "*************************************************************"
echo "Writing for nrows=$nrows Krows, psyco=$psyco, worst='${worst}'"
echo "*************************************************************"
writedata ${nrows} ${bfile} "${worst}" "${psyco}"
done
# Read data files
for smode in indexed inkernel standard; do
${python} cacheout.py
for nrows in $nrowslist; do
echo "***********************************************************"
echo "Searching for nrows=$nrows Krows, $smode, psyco=$psyco, worst='${worst}'"
echo "***********************************************************"
readdata ${nrows} ${bfile} "${worst}" "${psyco}" "${smode}"
done
done
# Finally, after the final search, delete the source (if desired)
# for nrows in $nrowslist; do
# rm -f data.nobackup/bench-${libcomp}-${nrows}k.h5
# done
done
echo "New data available on: $bfile"
done
exit 0
|
<!-- TITLE: dmi -->
# `dmi [addr|libname] [symname]` List symbols of target lib
```
Usage: dmi # List/Load Symbols
```
- `dmi[libname] [symname]` List symbols of target lib
- > Example: `dmi libc puts`
- `dmi*` List symbols of target lib in radare commands
- `dmi.` List closest symbol to the current address
- `dmiv` Show address of given symbol for given lib
<p hidden>dmi dmi* dmi. dmiv</p>
|
<script>
var wsServer = 'ws://112.74.182.162:9501';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {
console.log("Connected to WebSocket server.");
};
websocket.onclose = function (evt) {
console.log("Disconnected");
};
websocket.onmessage = function (evt) {
console.log('Retrieved data from server: ' + evt.data);
};
websocket.onerror = function (evt, e) {
console.log('Error occured: ' + evt.data);
};
</script>
|
// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.pgpainless.signature.consumer;
import java.util.Comparator;
import org.bouncycastle.openpgp.PGPSignature;
import org.pgpainless.signature.SignatureUtils;
/**
* Comparator which sorts signatures based on an ordering and on revocation hardness.
*
* If a list of signatures gets ordered using this comparator, hard revocations will always
* come first.
* Further, signatures are ordered by date according to the {@link SignatureCreationDateComparator.Order}.
*/
public class SignatureValidityComparator implements Comparator<PGPSignature> {
private final SignatureCreationDateComparator creationDateComparator;
/**
* Create a new {@link SignatureValidityComparator} which orders signatures the oldest first.
* Still, hard revocations will come first.
*/
public SignatureValidityComparator() {
this(SignatureCreationDateComparator.DEFAULT_ORDER);
}
/**
* Create a new {@link SignatureValidityComparator} which orders signatures following the passed ordering.
* Still, hard revocations will come first.
*/
public SignatureValidityComparator(SignatureCreationDateComparator.Order order) {
this.creationDateComparator = new SignatureCreationDateComparator(order);
}
@Override
public int compare(PGPSignature one, PGPSignature two) {
boolean oneIsHard = SignatureUtils.isHardRevocation(one);
boolean twoIsHard = SignatureUtils.isHardRevocation(two);
// both have same "hardness", so compare creation time
if (oneIsHard == twoIsHard) {
return creationDateComparator.compare(one, two);
}
// favor the "harder" signature
return oneIsHard ? -1 : 1;
}
}
|
package ba.wave.wavebackend.security.config;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.interceptor.CustomizableTraceInterceptor;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableAspectJAutoProxy
public class SpringDataExecutionLoggingConfiguration {
@Bean
public CustomizableTraceInterceptor customizableTraceInterceptor() {
CustomizableTraceInterceptor customizableTraceInterceptor = new CustomizableTraceInterceptor();
customizableTraceInterceptor.setUseDynamicLogger(true);
customizableTraceInterceptor.setExitMessage("Executed $[methodName] in $[invocationTime]");
return customizableTraceInterceptor;
}
@Bean
public Advisor advisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression("execution(public * org.springframework.data.repository.Repository+.*(..))");
return new DefaultPointcutAdvisor(pointcut, customizableTraceInterceptor());
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConApp.EventSample.EventDemo6
{
/// <summary>
/// 热水器
/// </summary>
public class Heater
{
public event EventHandler OnBoiled;
private void RasieBoiledEvent()
{
if (OnBoiled == null)
{
Console.WriteLine("加热完成处理订阅事件为空");
}
else
{
OnBoiled(this, new EventArgs());
}
}
private Thread heatThread;
public void Begin()
{
heatTime = 5;
heatThread = new Thread(new ThreadStart(Heat));
heatThread.Start();
Console.WriteLine("加热器已经开启", heatTime);
}
private int heatTime;
private void Heat()
{
while (true)
{
Console.WriteLine("加热还需{0}秒", heatTime);
if (heatTime == 0)
{
RasieBoiledEvent();
return;
}
heatTime--;
Thread.Sleep(1000);
}
}
}
}
|
use rustix::fd::FromFd;
use rustix::fs::{fcntl_add_seals, ftruncate, memfd_create, MemfdFlags, SealFlags};
use std::fs::File;
use std::io::Write;
#[test]
fn test_seals() {
let fd = memfd_create("test", MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING).unwrap();
let mut file = File::from_fd(fd.into());
writeln!(&mut file, "Hello!").unwrap();
fcntl_add_seals(&file, SealFlags::GROW).unwrap();
// We sealed growing, so this should fail.
writeln!(&mut file, "World?").unwrap_err();
// We can still shrink for now.
ftruncate(&mut file, 1).unwrap();
fcntl_add_seals(&file, SealFlags::SHRINK).unwrap();
// We sealed shrinking, so this should fail.
ftruncate(&mut file, 0).unwrap_err();
}
|
export { PostAdd } from './add';
export { PostsList } from './list';
export { PostUpdate } from './update';
|
<?php
declare(strict_types=1);
namespace Ray\MediaQuery\Explicit;
use Ray\AuraSqlModule\Pagerfanta\AuraSqlPagerInterface;
use Ray\MediaQuery\SqlQueryInterface;
use Ray\MediaQuery\TodoListInterface;
class TodoList implements TodoListInterface
{
/** @var SqlQueryInterface */
private $sqlQuery;
public function __construct(SqlQueryInterface $sqlQuery)
{
$this->sqlQuery = $sqlQuery;
}
public function __invoke(): AuraSqlPagerInterface
{
return $this->sqlQuery->getPages('todo_list', [], 10);
}
}
|
# [Intro to RSA](https://id0-rsa.pub/problem/21/)
## RSA Decryption
For ciphertext c, RSA Decryption function D(c) = c^d (mod N).
|
package main
import ("fmt")
func occurance(f []int) {
var str []int
str=append(str,f[0])
for i:=0;i<len(f);i++ {
for j:=0;j<len(str);j++ {
if f[i]==str[j] {
break
}
if j==len(str)-1{
str=append(str,f[i])
}
}
}
fmt.Println("str",str)
for i:=0;i<len(str);i++{
count:=0
for j:=0;j<len(f);j++ {
if str[i]==f[j] {
count++
}
}
fmt.Printf("the value %d is having %d occurance\n",str[i],count)
}
}
func main() {
var b,a int
var arr []int
//getting size of the array
fmt.Println("Enter the length of the array")
fmt.Scan(&a)
//getting elements for the array using for loop
fmt.Println("Enter the elements for the array")
for i:=0;i<a;i++{
fmt.Scan(&b)
arr = append(arr,b)
}
occurance(arr)
}
|
package icbm.classic.api.explosion;
/**
* Applied to blasts that exist in world and tick
* Created by Dark(DarkGuardsman, Robert) on 2/10/2019.
*/
public interface IBlastTickable extends IBlast
{
/**
* Called each tick the blast is alive.
* <p>
* Normally called from {@link #getController()}
*
* @param ticksExisted - ticks the controller is alive
* @return true to set dead
*/
boolean onBlastTick(int ticksExisted);
/**
* Should the tickable blast be controlled
* by an explosive entity
*
* @return
*/
default boolean spawnEntity()
{
//TODO consider making a method to create the ticking entity (or system) so we can have a different version per explosive
return true;
}
}
|
// script to hide bell from bar when Discord closes
const { createWriteStream } = require('fs');
const { join } = require('path');
const { pipePath } = require(join(__dirname, 'config.json'));
var wstream = createWriteStream(pipePath);
wstream.write("<fn=0></fn>\n");
wstream.end();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.