text
stringlengths 27
775k
|
|---|
import 'dart:math';
import 'package:flutter/material.dart';
/// create by 张风捷特烈 on 2020-04-19
/// contact me by email 1981462002@qq.com
/// 说明:
// {
// "widgetId": 85,
// "name": 'Align其他用法',
// "priority": 2,
// "subtitle":
// "由于Alignment对象可指定在父容器中宽高的分率位置\n"
// "可以使用Align实现一些复杂的排布需求,比如按指定的数学方程变化位置",
// }
class Ball extends StatelessWidget {
Ball({
Key? key,
this.radius = 15,
this.color = Colors.blue,
}) : super(key: key);
final double radius; //半径
final Color color; //颜色
@override
Widget build(BuildContext context) {
return Container(
width: radius * 2,
height: radius * 2,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: color,
),
);
}
}
class SinLayout extends StatefulWidget {
SinLayout({
Key? key,
}) : super(key: key);
@override
_SinLayoutState createState() => _SinLayoutState();
}
class _SinLayoutState extends State<SinLayout> {
var _x = 0.0; //Alignment坐标系上的x坐标
@override
Widget build(BuildContext context) {
var item = Container(
width: 300,
height: 120,
color: Colors.black.withAlpha(10),
child: Align(
child: Ball(
color: Colors.orangeAccent,
),
alignment: Alignment(_x, f(_x * pi)),
),
);
var slider = Slider(
max: 180,
min: -180,
divisions: 360,
label: "${_x.toStringAsFixed(2)}π",
value: _x * 180,
onChanged: (v) => setState(() => _x = v / 180));
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[slider, item],
);
}
double f(x) {
//映射函数 -- 可随意指定
double y = sin(x);
return y;
}
}
|
"""Unit tests for src/utils.py."""
from datetime import date, datetime
import pytest
from utils import chunks, extend_dictionary, json_serial
class TestJsonSerial:
"""Tests the json_serial function."""
def test_json_serial(self) -> None:
"""Tests for correct output."""
assert json_serial(date(2020, 1, 1)) == "2020-01-01"
assert json_serial(datetime(2020, 1, 1, 10, 9, 8)) == "2020-01-01T10:09:08"
def test_serialisation_error(self) -> None:
"""Test for non-datetime objects."""
with pytest.raises(TypeError):
json_serial("hello world")
with pytest.raises(TypeError):
json_serial(123)
class TestChunks:
"""Tests the chunks function."""
def test_chunks(self) -> None:
"""Tests chunks are of the correct size."""
test_list = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
for item in chunks(test_list, 4):
assert len(item) <= 4
for item in chunks(test_list, 50):
assert len(item) <= 50
class TestExtendDictionary:
"""Tests the extend_dictionary function."""
def setup_class(self) -> None:
"""Initialises sample dicts for testing."""
self.dictionary_one = {"a": 1}
self.dictionary_two = {"b": 2}
def test_extend_dictionary(self) -> None:
"""Check extension functionality is working correctly."""
output = extend_dictionary(self.dictionary_one, self.dictionary_two, "b")
assert type(output) == dict
assert "b" in output
assert list(output.keys()) == ["a", "b"]
def test_key_overwrite_warning(self) -> None:
"""Check the corect warning is being shown."""
with pytest.warns(UserWarning) as record:
extend_dictionary(self.dictionary_one, self.dictionary_two, "a")
assert len(record) == 1
assert record[0].message.args[0] == "Key 'a' already exists and will be overwritten"
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "blimp/client/core/settings/settings.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "blimp/client/core/settings/settings_observer.h"
#include "blimp/client/core/settings/settings_prefs.h"
#include "blimp/client/core/switches/blimp_client_switches.h"
#include "components/prefs/pref_registry_simple.h"
namespace blimp {
namespace client {
namespace {
const CommandLinePrefStore::BooleanSwitchToPreferenceMapEntry
boolean_switch_map[] = {
{blimp::switches::kEnableBlimp, prefs::kBlimpEnabled, true},
{blimp::switches::kDownloadWholeDocument, prefs::kRecordWholeDocument,
true},
};
} // namespace
Settings::Settings(PrefService* local_state)
: local_state_(local_state), show_network_stats_(false) {
pref_change_registrar_.Init(local_state);
pref_change_registrar_.Add(
prefs::kBlimpEnabled,
base::Bind(&Settings::OnPreferenceChanged, base::Unretained(this),
local_state, prefs::kBlimpEnabled));
pref_change_registrar_.Add(
prefs::kRecordWholeDocument,
base::Bind(&Settings::OnPreferenceChanged, base::Unretained(this),
local_state, prefs::kRecordWholeDocument));
}
Settings::~Settings() = default;
void Settings::AddObserver(SettingsObserver* observer) {
observers_.AddObserver(observer);
}
void Settings::RemoveObserver(SettingsObserver* observer) {
observers_.RemoveObserver(observer);
}
void Settings::SetShowNetworkStats(bool enable) {
if (show_network_stats_ == enable)
return;
show_network_stats_ = enable;
for (auto& observer : observers_)
observer.OnShowNetworkStatsChanged(show_network_stats_);
}
void Settings::SetEnableBlimpMode(bool enable) {
local_state_->SetBoolean(prefs::kBlimpEnabled, enable);
}
void Settings::SetRecordWholeDocument(bool enable) {
local_state_->SetBoolean(prefs::kRecordWholeDocument, enable);
}
void Settings::OnPreferenceChanged(PrefService* service,
const std::string& pref_name) {
if (pref_name == prefs::kBlimpEnabled) {
for (auto& observer : observers_) {
observer.OnBlimpModeEnabled(service->GetBoolean(pref_name));
observer.OnRestartRequired();
}
} else if (pref_name == prefs::kRecordWholeDocument) {
for (auto& observer : observers_)
observer.OnRecordWholeDocumentChanged(service->GetBoolean(pref_name));
}
}
bool Settings::IsBlimpEnabled() {
return local_state_->GetBoolean(prefs::kBlimpEnabled);
}
bool Settings::IsRecordWholeDocument() {
return local_state_->GetBoolean(prefs::kRecordWholeDocument);
}
// static
void Settings::RegisterPrefs(PrefRegistrySimple* registry) {
registry->RegisterBooleanPref(prefs::kBlimpEnabled, false);
registry->RegisterBooleanPref(prefs::kRecordWholeDocument, false);
}
// static
void Settings::ApplyBlimpSwitches(CommandLinePrefStore* store) {
store->ApplyBooleanSwitches(boolean_switch_map,
arraysize(boolean_switch_map));
}
} // namespace client
} // namespace blimp
|
-module (inets_response_bridge_tests).
-include ("test.hrl").
-export ([
build_response_test/0
]).
build_response_test() ->
B00 = simple_bridge:make_response(inets_response_bridge, undefined),
B01 = B00:status_code(200),
B02 = B01:header("header1", "value1"),
B03 = B02:header("header2", "value2"),
B04 = B03:cookie("cookie1", "value1"),
B05 = B04:cookie("cookie2", "value2"),
B06 = B05:data("This is the data."),
_Response = B06:build_response().
|
use metrics::asana::*;
use metrics::config::*;
use clap::{App, Arg};
use env_logger;
use futures::future::{join, join3, join_all};
use serde_json;
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use tokio;
fn main() {
/* Logging */
env_logger::init();
/* Command Line */
let (config_file_str, token_file_str) = process_command_line();
/*
* Config data
*/
let config_file_path = Path::new(&config_file_str)
.canonicalize()
.expect(&format!("Bad config file path: {}", &config_file_str));
let config_str = fs::read_to_string(config_file_path)
.expect(&format!("Bad config file: {}", &config_file_str));
let config: MyConfig = parse_config(&config_str);
/*
* Asana Personal Access Token -- credentials
*/
let token_file_path: PathBuf = Path::new(&token_file_str)
.canonicalize()
.expect(&format!("Bad token file path: {}", &token_file_str));
let token_str =
fs::read_to_string(token_file_path).expect(&format!("Bad token file: {}", &token_file_str));
let token_str = String::from(token_str.trim_end());
/*
* Process
*/
let mut rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(get_data(&token_str, &config));
}
fn process_command_line() -> (String, String) {
let matches = App::new("fetch")
.version("0.1.0")
.author("Parijat Mishra <parijat.mishra@gmail.com>")
.about("Scrape Asana for Kanban Metrics, write to output.json")
.arg(
Arg::with_name("config-file")
.short("c")
.long("config-file")
.takes_value(true)
.help("path to config file"),
)
.arg(
Arg::with_name("token-file")
.short("t")
.long("token-file")
.takes_value(true)
.help("path of file containing an Asana Personal Access Token"),
)
.arg(
Arg::with_name("output-file")
.short("o")
.long("output-file")
.takes_value(true)
.help("Output file (JSON data)"),
)
.get_matches();
let config_file_str = matches
.value_of("config-file")
.expect("config-file must be specified");
let token_file_str = matches
.value_of("token-file")
.expect("token-file must be specified");
return (config_file_str.to_owned(), token_file_str.to_owned());
}
pub async fn get_data(token: &str, config: &MyConfig) {
let client = AsanaClient::new(token, Some(2));
let (asana_projects, asana_project_sections, asana_project_task_gids) =
get_asana_data_projects(&client, config).await;
let task_gids: Vec<_> = asana_project_task_gids
.iter()
.flat_map(|e| &e.task_gids)
.collect();
let (asana_tasks, asana_task_stories) = get_asana_data_tasks(&client, &task_gids).await;
let user_gids: HashSet<_> = asana_tasks
.iter()
.filter(|&t| t.assignee.is_some())
.map(|t| &t.assignee.as_ref().unwrap().gid)
.collect();
let asana_users = get_asana_data_users(&client, &user_gids).await;
let data = AsanaData {
users: asana_users,
projects: asana_projects,
project_sections: asana_project_sections,
project_task_gids: asana_project_task_gids,
tasks: asana_tasks,
task_stories: asana_task_stories,
};
let output_filename = "asana_data.json";
let output_str = serde_json::to_string(&data).expect("Should convert to JSON string");
fs::write(output_filename, output_str).expect("Should write to file");
println!("Wrote output to file {}.", output_filename);
}
async fn get_asana_data_projects(
client: &AsanaClient<'_>,
config: &MyConfig,
) -> (
Vec<AsanaProject>,
Vec<AsanaProjectSections>,
Vec<AsanaProjectTaskGids>,
) {
let mut project_futures = Vec::new();
let mut project_sections_futures = Vec::new();
let mut project_task_gids_futures = Vec::new();
for (_, project_config) in &config.projects {
project_futures.push(client.get_project(&project_config.gid));
project_sections_futures.push(client.get_project_sections(&project_config.gid));
project_task_gids_futures
.push(client.get_project_task_gids(&project_config.gid, &project_config.horizon));
}
return join3(
join_all(project_futures),
join_all(project_sections_futures),
join_all(project_task_gids_futures),
)
.await;
}
async fn get_asana_data_tasks(
client: &AsanaClient<'_>,
task_gids: &Vec<&String>,
) -> (Vec<AsanaTask>, Vec<AsanaTaskStories>) {
let mut task_futures = Vec::new();
let mut task_stories_futures = Vec::new();
for task_gid in task_gids {
task_futures.push(client.get_task(&task_gid));
task_stories_futures.push(client.get_task_stories(&task_gid));
}
return join(join_all(task_futures), join_all(task_stories_futures)).await;
}
async fn get_asana_data_users(
client: &AsanaClient<'_>,
user_gids: &HashSet<&String>,
) -> Vec<AsanaUser> {
let mut user_futures = Vec::new();
for user_gid in user_gids {
user_futures.push(client.get_user(&user_gid));
}
return join_all(user_futures).await;
}
|
#!Source me
. ./.local/bin/activate
export PATH="`echo $PATH|sed 's/\([^\\]\) /\1\\\\ /g'`" #Handle spaces in PATH
export ModelSEEDDatabase="$PWD/sourcedata/ModelSEEDDatabase"
|
<?php
namespace Consilience\Laravel\MessageFlow\Observers;
/**
* This observer watches for "new" outbound messages in the MessageFlowOut
* model, and dispatches jobs to push each through the routing pipeline.
*
* The observer events must not change the message model, for risk
* of an endless loop. Instead, event actions are all dispatched
* to a separate job.
*/
use Consilience\Laravel\MessageFlow\Jobs\RoutingPipeline;
use Consilience\Laravel\MessageFlow\Models\MessageFlowOut;
class NewOutboundObserver
{
/**
* Handle the MessageFlowOut "created" event.
*
* @param MessageFlowOut $messageFlowOut
* @return void
*/
public function created(MessageFlowOut $messageFlowOut)
{
if ($messageFlowOut->isNew()) {
// Landed with the "new" status, so is ready to be pushed on.
dispatch(new RoutingPipeline($messageFlowOut));
}
}
/**
* Handle the MessageFlowOut "updated" event.
*
* @param MessageFlowOut $messageFlowOut
* @return void
*/
public function updated(MessageFlowOut $messageFlowOut)
{
// FIXME: Don't dispatch a job if no routing pipeline is defined in config.
if ($messageFlowOut->isDirty('status') && $messageFlowOut->isNew()) {
// Becomes "new" status from ny other status.
dispatch(new RoutingPipeline($messageFlowOut));
}
}
}
|
#!/bin/bash
# Copyright 2020 ETH Zurich and University of Bologna.
# Solderpad Hardware License, Version 0.51, see LICENSE for details.
# SPDX-License-Identifier: SHL-0.51
#
# Fabian Schuiki <fschuiki@iis.ee.ethz.ch>
# Andreas Kurth <akurth@iis.ee.ethz.ch>
set -e
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
[ ! -z "$VSIM" ] || VSIM=vsim
call_vsim() {
echo "log -r /*; run -all" | $VSIM -c -coverage -voptargs='+acc +cover=sbecft' "$@" | tee vsim.log 2>&1
grep "Errors: 0," vsim.log
}
call_vsim snitch_icache_l0_tb
|
import { NextApiRequest, NextApiResponse } from 'next'
import jwt from 'jsonwebtoken'
import { query as q } from 'faunadb'
import bcrypt from 'bcryptjs'
import { fauna } from '../../services/fauna'
import { signUp } from '../../libs/validators'
import { IFaunaResponse } from '../../libs/interfaces/api'
export default async (request: NextApiRequest, response: NextApiResponse) => {
if (!(await signUp.isValid(request.body)))
return response
.status(400)
.json({ error: 'Validation failed! Please check the data provided.' })
const { email } = request.body
const password = await bcrypt.hash(request.body.password, 8)
try {
const { ref, data: user } = await fauna.query<IFaunaResponse>(
q.Create(q.Collection('users'), { data: { email, password } })
)
return response.status(201).json({
email: user.email,
token: jwt.sign({ id: ref.id, email: user.email }, process.env.JWT_SECRET || '', {
expiresIn: '7d',
}),
})
} catch (error) {
const { description } = error
return response
.status(400)
.json({ message: 'Something went wrong creating user.', description })
}
}
|
package com.jpa.service;
import com.jpa.entity.User;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
@Repository
@Transactional
public class UserDAOService {
//Has all the DAO functions
@PersistenceContext
private EntityManager entityManager;
public long insert(User user)
{
entityManager.persist(user);
return user.getId();
}
public User getUserById(long id)
{
return entityManager.find(User.class,id);
}
public void updateUser(User user)
{
User new_user = getUserById(user.getId());
new_user.setName("Nidhi");
new_user.setRole("admin");
entityManager.flush();
}
public void deleteUser(long userid)
{
entityManager.remove(getUserById(userid));
}
}
|
<?php
class SeleniumTestHTMLLogger {
public function setHeaders() {
global $wgOut;
$wgOut->addHeadItem( 'selenium', '<style type="text/css">
.selenium pre {
overflow-x: auto; /* Use horizontal scroller if needed; for Firefox 2, not needed in Firefox 3 */
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
/* width: 99%; */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
.selenium-success { color: green }
</style>' );
}
public function write( $message, $mode = false ) {
global $wgOut;
$out = '';
if ( $mode == SeleniumTestSuite::RESULT_OK ) {
$out .= '<span class="selenium-success">';
}
$out .= htmlspecialchars( $message );
if ( $mode == SeleniumTestSuite::RESULT_OK ) {
$out .= '</span>';
}
if ( $mode != SeleniumTestSuite::CONTINUE_LINE ) {
$out .= '<br />';
}
$wgOut->addHTML( $out );
}
}
|
SgInfo - Space Group Info (c) 1994-96 Ralf W. Grosse-Kunstleve
Original SgInfo 1.01 from 1996. The only difference is the
new open source license.
See also:
- http://cci.lbl.gov/sginfo/
- https://github.com/rwgk/sglite # No known bugs but also no documentation.
- http://cctbx.sf.net/ # Look for sgtbx. No known bugs, but large.
# Build instructions
You can now build the sginfo library using CMake.
The following lines will build the library
```bash
mkdir -p build
cd build
cmake ..
cmake --build .
```
|
#pragma once
#include <windows.h>
#include <winnt.h>
#include <stdexcept>
#include <string>
#include <vector>
constexpr std::size_t NT_SIGNATURE_SIZE = 4;
class bitness_error : public std::runtime_error
{
public:
bitness_error() : std::runtime_error("Incompatible bitness") { }
};
class PeFile
{
public:
virtual ~PeFile();
IMAGE_DOS_HEADER& dos_header() const;
IMAGE_FILE_HEADER& pe_header() const;
std::vector<PIMAGE_SECTION_HEADER> section_headers() const;
DWORD size() const noexcept;
virtual std::string bitness() const = 0;
void write_to_file(const std::string& _filename) const;
protected:
HANDLE m_mapping{ nullptr };
unsigned char* m_view{ nullptr };
DWORD m_size{ 0 };
void init_mapping_view(const std::string& _filename);
virtual std::size_t headers_size() const noexcept = 0;
virtual bool is_file_valid() const noexcept;
};
|
define(['knockout', 'text!./panacea-browser.html', 'appConfig', 'faceted-datatable'], function (ko, view, config) {
function panaceaBrowser(params) {
var self = this;
self.model = params.model;
self.services = params.services;
self.currentService = ko.observable();
self.reference = ko.observableArray();
self.panaceaView = ko.observable();
self.selectedPanaceaStudy = params.selectedPanaceaStudy;
self.selected = params.panaceaStudyId;
self.currentStudy = ko.observable();
self.panaceaView.subscribe(function (d) {
if(self.panaceaView() == 'review'){
$.ajax({
//url: self.services()[0].url + 'panacea/getAllStudy',
url: config.services[0].url + 'panacea/getAllStudyWithLastRunTime',
method: 'GET',
success: function (d) {
self.reference(d);
}
});
}else if(self.panaceaView() == 'edit'){
/* $.ajax({
url: self.services()[0].url + 'panacea/' + self.selectedPanaceaStudy(),
method: 'GET',
success: function (d) {
self.currentStudy(d);
}
});*/
}
});
// self.selectedPanaceaStudy.subscribe(function (d) {
//
// if(self.selectedPanaceaStudy != null){
// self.panaceaView('edit');
// $.ajax({
// url: self.services()[0].url + 'panacea/' + self.selectedPanaceaStudy(),
// method: 'GET',
// success: function (d) {
// self.currentStudy(d);
// }
// });
// }else{
// self.panaceaView('review');
// }
// });
self.panaceaView('review');
self.options = {
"sDom": 'rtp',
Facets: [
// {
// 'caption': 'Start date',
// 'binding': function (o) {
// var daysSinceModification = (new Date().getTime() - new Date(o.startDate).getTime()) / 1000 / 60 / 60 / 24;
// if (daysSinceModification < 7) {
// return 'This Week';
// } else if (daysSinceModification < 14) {
// return 'Last Week';
// } else {
// return '2+ Weeks Ago';
// }
// }
// },
// {
// 'caption': 'Name',
// 'binding': function (o) {
// return o.studyName;
// }
// }
]
};
self.renderStudyNameLink = function (s, p, d) {
//return '<span class="linkish" data-bind="click: function(d) { rowClick(d); }">' + d.studyName + '</span>';
return '<span class="linkish" >' + d.studyName + '</span>';
}
self.renderStudyId = function(s, p, d) {
return d.studyId;
}
self.renderStudyCreateTime = function(s, p, d) {
return new Date(d.createTime).toLocaleDateString() + " " + new Date(d.createTime).toLocaleTimeString();
}
self.renderLastRunTime = function(s, p, d) {
if(d.lastRunTime != null){
return new Date(d.lastRunTime).toLocaleDateString() + " " + new Date(d.lastRunTime).toLocaleTimeString();
}else{
return null;
}
}
self.renderStudyResultsLink = function(s, p, d) {
if(d.lastRunTime == null){
return null;
}else{
return '<a href="#/panaceasunburstresult/' + d.studyId + '"><i class="fa fa-eye"></i></a>';
}
}
self.renderStudyCloneLink = function(s, p, d) {
return '<a href="#/panaceaclone/'+ d.studyId +'"><i class="fa fa-copy"></i></a>';
}
self.rowClick = function (d) {
self.selectedPanaceaStudy = d;
self.selected(d.studyId);
// self.panaceaView('edit');
}
self.createStudy = function () {
document.location = "#/panaceadef/undefined";
};
self.columns = [
{
title: 'Study Id',
data: 'studyId'
},
{
title: 'Name',
render: self.renderStudyNameLink
}
];
}
var component = {
viewModel: panaceaBrowser,
template: view
};
ko.components.register('panacea-browser', component);
return component;
});
|
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Tests that Win32 API prototypes can be successfully loaded (i.e. that
// lookupFunction works for all the APIs generated)
// THIS FILE IS GENERATED AUTOMATICALLY AND SHOULD NOT BE EDITED DIRECTLY.
@TestOn('windows')
import 'dart:ffi';
import 'package:ffi/ffi.dart';
import 'package:test/test.dart';
import 'package:win32/win32.dart';
void main() {
group('Test kernel32 functions', () {
test('Can instantiate ActivateActCtx', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final ActivateActCtx = kernel32.lookupFunction<
Int32 Function(IntPtr hActCtx, Pointer<IntPtr> lpCookie),
int Function(
int hActCtx, Pointer<IntPtr> lpCookie)>('ActivateActCtx');
expect(ActivateActCtx, isA<Function>());
});
test('Can instantiate AllocConsole', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final AllocConsole = kernel32
.lookupFunction<Int32 Function(), int Function()>('AllocConsole');
expect(AllocConsole, isA<Function>());
});
test('Can instantiate AttachConsole', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final AttachConsole = kernel32.lookupFunction<
Int32 Function(Uint32 dwProcessId),
int Function(int dwProcessId)>('AttachConsole');
expect(AttachConsole, isA<Function>());
});
test('Can instantiate Beep', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final Beep = kernel32.lookupFunction<
Int32 Function(Uint32 dwFreq, Uint32 dwDuration),
int Function(int dwFreq, int dwDuration)>('Beep');
expect(Beep, isA<Function>());
});
test('Can instantiate BeginUpdateResource', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final BeginUpdateResource = kernel32.lookupFunction<
IntPtr Function(
Pointer<Utf16> pFilename, Int32 bDeleteExistingResources),
int Function(Pointer<Utf16> pFilename,
int bDeleteExistingResources)>('BeginUpdateResourceW');
expect(BeginUpdateResource, isA<Function>());
});
test('Can instantiate CloseHandle', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final CloseHandle = kernel32.lookupFunction<
Int32 Function(IntPtr hObject),
int Function(int hObject)>('CloseHandle');
expect(CloseHandle, isA<Function>());
});
test('Can instantiate ClosePseudoConsole', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final ClosePseudoConsole = kernel32.lookupFunction<
Void Function(Pointer<IntPtr> hPC),
void Function(Pointer<IntPtr> hPC)>('ClosePseudoConsole');
expect(ClosePseudoConsole, isA<Function>());
});
test('Can instantiate CreateConsoleScreenBuffer', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final CreateConsoleScreenBuffer = kernel32.lookupFunction<
IntPtr Function(
Uint32 dwDesiredAccess,
Uint32 dwShareMode,
Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes,
Uint32 dwFlags,
Pointer lpScreenBufferData),
int Function(
int dwDesiredAccess,
int dwShareMode,
Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes,
int dwFlags,
Pointer lpScreenBufferData)>('CreateConsoleScreenBuffer');
expect(CreateConsoleScreenBuffer, isA<Function>());
});
test('Can instantiate CreateFile', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final CreateFile = kernel32.lookupFunction<
IntPtr Function(
Pointer<Utf16> lpFileName,
Uint32 dwDesiredAccess,
Uint32 dwShareMode,
Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes,
Uint32 dwCreationDisposition,
Uint32 dwFlagsAndAttributes,
IntPtr hTemplateFile),
int Function(
Pointer<Utf16> lpFileName,
int dwDesiredAccess,
int dwShareMode,
Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes,
int dwCreationDisposition,
int dwFlagsAndAttributes,
int hTemplateFile)>('CreateFileW');
expect(CreateFile, isA<Function>());
});
test('Can instantiate CreatePipe', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final CreatePipe = kernel32.lookupFunction<
Int32 Function(Pointer<IntPtr> hReadPipe, Pointer<IntPtr> hWritePipe,
Pointer<SECURITY_ATTRIBUTES> lpPipeAttributes, Uint32 nSize),
int Function(
Pointer<IntPtr> hReadPipe,
Pointer<IntPtr> hWritePipe,
Pointer<SECURITY_ATTRIBUTES> lpPipeAttributes,
int nSize)>('CreatePipe');
expect(CreatePipe, isA<Function>());
});
test('Can instantiate CreateProcess', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final CreateProcess = kernel32.lookupFunction<
Int32 Function(
Pointer<Utf16> lpApplicationName,
Pointer<Utf16> lpCommandLine,
Pointer<SECURITY_ATTRIBUTES> lpProcessAttributes,
Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes,
Int32 bInheritHandles,
Uint32 dwCreationFlags,
Pointer lpEnvironment,
Pointer<Utf16> lpCurrentDirectory,
Pointer lpStartupInfo,
Pointer<PROCESS_INFORMATION> lpProcessInformation),
int Function(
Pointer<Utf16> lpApplicationName,
Pointer<Utf16> lpCommandLine,
Pointer<SECURITY_ATTRIBUTES> lpProcessAttributes,
Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes,
int bInheritHandles,
int dwCreationFlags,
Pointer lpEnvironment,
Pointer<Utf16> lpCurrentDirectory,
Pointer lpStartupInfo,
Pointer<PROCESS_INFORMATION> lpProcessInformation)>(
'CreateProcessW');
expect(CreateProcess, isA<Function>());
});
test('Can instantiate CreatePseudoConsole', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final CreatePseudoConsole = kernel32.lookupFunction<
Int32 Function(Int32 size, IntPtr hInput, IntPtr hOutput,
Int32 dwFlags, Pointer<IntPtr> phPC),
int Function(int size, int hInput, int hOutput, int dwFlags,
Pointer<IntPtr> phPC)>('CreatePseudoConsole');
expect(CreatePseudoConsole, isA<Function>());
});
test('Can instantiate DeactivateActCtx', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final DeactivateActCtx = kernel32.lookupFunction<
Int32 Function(Uint32 dwFlags, IntPtr ulCookie),
int Function(int dwFlags, int ulCookie)>('DeactivateActCtx');
expect(DeactivateActCtx, isA<Function>());
});
test('Can instantiate EndUpdateResource', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final EndUpdateResource = kernel32.lookupFunction<
Int32 Function(IntPtr hUpdate, Int32 fDiscard),
int Function(int hUpdate, int fDiscard)>('EndUpdateResourceW');
expect(EndUpdateResource, isA<Function>());
});
test('Can instantiate EnumResourceNames', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final EnumResourceNames = kernel32.lookupFunction<
Int32 Function(IntPtr hModule, Pointer<Utf16> lpType,
Pointer<NativeFunction> lpEnumFunc, IntPtr lParam),
int Function(
int hModule,
Pointer<Utf16> lpType,
Pointer<NativeFunction> lpEnumFunc,
int lParam)>('EnumResourceNamesW');
expect(EnumResourceNames, isA<Function>());
});
test('Can instantiate EnumResourceTypes', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final EnumResourceTypes = kernel32.lookupFunction<
Int32 Function(IntPtr hModule, Pointer<NativeFunction> lpEnumFunc,
IntPtr lParam),
int Function(int hModule, Pointer<NativeFunction> lpEnumFunc,
int lParam)>('EnumResourceTypesW');
expect(EnumResourceTypes, isA<Function>());
});
test('Can instantiate FillConsoleOutputAttribute', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final FillConsoleOutputAttribute = kernel32.lookupFunction<
Int32 Function(
IntPtr hConsoleOutput,
Uint16 wAttribute,
Uint32 nLength,
Int32 dwWriteCoord,
Pointer<Uint32> lpNumberOfAttrsWritten),
int Function(int hConsoleOutput, int wAttribute, int nLength,
int dwWriteCoord, Pointer<Uint32> lpNumberOfAttrsWritten)>(
'FillConsoleOutputAttribute');
expect(FillConsoleOutputAttribute, isA<Function>());
});
test('Can instantiate FillConsoleOutputCharacter', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final FillConsoleOutputCharacter = kernel32.lookupFunction<
Int32 Function(
IntPtr hConsoleOutput,
Uint8 cCharacter,
Uint32 nLength,
Int32 dwWriteCoord,
Pointer<Uint32> lpNumberOfCharsWritten),
int Function(int hConsoleOutput, int cCharacter, int nLength,
int dwWriteCoord, Pointer<Uint32> lpNumberOfCharsWritten)>(
'FillConsoleOutputCharacterW');
expect(FillConsoleOutputCharacter, isA<Function>());
});
test('Can instantiate FindFirstVolume', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final FindFirstVolume = kernel32.lookupFunction<
IntPtr Function(
Pointer<Utf16> lpszVolumeName, Uint32 cchBufferLength),
int Function(Pointer<Utf16> lpszVolumeName,
int cchBufferLength)>('FindFirstVolumeW');
expect(FindFirstVolume, isA<Function>());
});
test('Can instantiate FindNextVolume', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final FindNextVolume = kernel32.lookupFunction<
Int32 Function(IntPtr hFindVolume, Pointer<Utf16> lpszVolumeName,
Uint32 cchBufferLength),
int Function(int hFindVolume, Pointer<Utf16> lpszVolumeName,
int cchBufferLength)>('FindNextVolumeW');
expect(FindNextVolume, isA<Function>());
});
test('Can instantiate FindVolumeClose', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final FindVolumeClose = kernel32.lookupFunction<
Int32 Function(IntPtr hFindVolume),
int Function(int hFindVolume)>('FindVolumeClose');
expect(FindVolumeClose, isA<Function>());
});
test('Can instantiate FlushConsoleInputBuffer', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final FlushConsoleInputBuffer = kernel32.lookupFunction<
Int32 Function(IntPtr hConsoleInput),
int Function(int hConsoleInput)>('FlushConsoleInputBuffer');
expect(FlushConsoleInputBuffer, isA<Function>());
});
test('Can instantiate FormatMessage', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final FormatMessage = kernel32.lookupFunction<
Int32 Function(
Uint32 dwFlags,
Pointer<Void> lpSource,
Uint32 dwMessageId,
Uint32 dwLanguageId,
Pointer<Utf16> lpBuffer,
Uint32 nSize,
Pointer arguments),
int Function(
int dwFlags,
Pointer<Void> lpSource,
int dwMessageId,
int dwLanguageId,
Pointer<Utf16> lpBuffer,
int nSize,
Pointer arguments)>('FormatMessageW');
expect(FormatMessage, isA<Function>());
});
test('Can instantiate FreeConsole', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final FreeConsole = kernel32
.lookupFunction<Int32 Function(), int Function()>('FreeConsole');
expect(FreeConsole, isA<Function>());
});
test('Can instantiate FreeLibrary', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final FreeLibrary = kernel32.lookupFunction<
Int32 Function(IntPtr hLibModule),
int Function(int hLibModule)>('FreeLibrary');
expect(FreeLibrary, isA<Function>());
});
test('Can instantiate GetComputerNameEx', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetComputerNameEx = kernel32.lookupFunction<
Int32 Function(
Int32 NameType, Pointer<Utf16> lpBuffer, Pointer<Uint32> nSize),
int Function(int NameType, Pointer<Utf16> lpBuffer,
Pointer<Uint32> nSize)>('GetComputerNameExW');
expect(GetComputerNameEx, isA<Function>());
});
test('Can instantiate GetConsoleCursorInfo', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetConsoleCursorInfo = kernel32.lookupFunction<
Int32 Function(IntPtr hConsoleOutput,
Pointer<CONSOLE_CURSOR_INFO> lpConsoleCursorInfo),
int Function(int hConsoleOutput,
Pointer<CONSOLE_CURSOR_INFO> lpConsoleCursorInfo)>(
'GetConsoleCursorInfo');
expect(GetConsoleCursorInfo, isA<Function>());
});
test('Can instantiate GetConsoleMode', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetConsoleMode = kernel32.lookupFunction<
Int32 Function(IntPtr hConsoleHandle, Pointer<Uint32> lpMode),
int Function(
int hConsoleHandle, Pointer<Uint32> lpMode)>('GetConsoleMode');
expect(GetConsoleMode, isA<Function>());
});
test('Can instantiate GetConsoleScreenBufferInfo', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetConsoleScreenBufferInfo = kernel32.lookupFunction<
Int32 Function(IntPtr hConsoleOutput,
Pointer<CONSOLE_SCREEN_BUFFER_INFO> lpConsoleScreenBufferInfo),
int Function(
int hConsoleOutput,
Pointer<CONSOLE_SCREEN_BUFFER_INFO>
lpConsoleScreenBufferInfo)>('GetConsoleScreenBufferInfo');
expect(GetConsoleScreenBufferInfo, isA<Function>());
});
test('Can instantiate GetConsoleSelectionInfo', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetConsoleSelectionInfo = kernel32.lookupFunction<
Int32 Function(
Pointer<CONSOLE_SELECTION_INFO> lpConsoleSelectionInfo),
int Function(
Pointer<CONSOLE_SELECTION_INFO> lpConsoleSelectionInfo)>(
'GetConsoleSelectionInfo');
expect(GetConsoleSelectionInfo, isA<Function>());
});
test('Can instantiate GetConsoleTitle', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetConsoleTitle = kernel32.lookupFunction<
Uint32 Function(Pointer<Utf16> lpConsoleTitle, Uint32 nSize),
int Function(
Pointer<Utf16> lpConsoleTitle, int nSize)>('GetConsoleTitleW');
expect(GetConsoleTitle, isA<Function>());
});
test('Can instantiate GetConsoleWindow', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetConsoleWindow =
kernel32.lookupFunction<IntPtr Function(), int Function()>(
'GetConsoleWindow');
expect(GetConsoleWindow, isA<Function>());
});
test('Can instantiate GetCurrentProcess', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetCurrentProcess =
kernel32.lookupFunction<IntPtr Function(), int Function()>(
'GetCurrentProcess');
expect(GetCurrentProcess, isA<Function>());
});
test('Can instantiate GetLargestConsoleWindowSize', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetLargestConsoleWindowSize = kernel32.lookupFunction<
Int32 Function(IntPtr hConsoleOutput),
int Function(int hConsoleOutput)>('GetLargestConsoleWindowSize');
expect(GetLargestConsoleWindowSize, isA<Function>());
});
test('Can instantiate GetLastError', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetLastError = kernel32
.lookupFunction<Uint32 Function(), int Function()>('GetLastError');
expect(GetLastError, isA<Function>());
});
test('Can instantiate GetModuleFileName', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetModuleFileName = kernel32.lookupFunction<
Int32 Function(
IntPtr hModule, Pointer<Utf16> lpFilename, Uint32 nSize),
int Function(int hModule, Pointer<Utf16> lpFilename,
int nSize)>('GetModuleFileNameW');
expect(GetModuleFileName, isA<Function>());
});
test('Can instantiate GetModuleHandle', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetModuleHandle = kernel32.lookupFunction<
IntPtr Function(Pointer<Utf16> lpModuleName),
int Function(Pointer<Utf16> lpModuleName)>('GetModuleHandleW');
expect(GetModuleHandle, isA<Function>());
});
test('Can instantiate GetNativeSystemInfo', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetNativeSystemInfo = kernel32.lookupFunction<
Void Function(Pointer<SYSTEM_INFO> lpSystemInfo),
void Function(
Pointer<SYSTEM_INFO> lpSystemInfo)>('GetNativeSystemInfo');
expect(GetNativeSystemInfo, isA<Function>());
});
test('Can instantiate GetPhysicallyInstalledSystemMemory', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetPhysicallyInstalledSystemMemory = kernel32.lookupFunction<
Int32 Function(Pointer<Uint64> TotalMemoryInKilobytes),
int Function(Pointer<Uint64> TotalMemoryInKilobytes)>(
'GetPhysicallyInstalledSystemMemory');
expect(GetPhysicallyInstalledSystemMemory, isA<Function>());
});
test('Can instantiate GetProcAddress', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetProcAddress = kernel32.lookupFunction<
IntPtr Function(IntPtr hModule, Pointer<Uint8> lpProcName),
int Function(
int hModule, Pointer<Uint8> lpProcName)>('GetProcAddress');
expect(GetProcAddress, isA<Function>());
});
test('Can instantiate GetProcessHeap', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetProcessHeap = kernel32
.lookupFunction<IntPtr Function(), int Function()>('GetProcessHeap');
expect(GetProcessHeap, isA<Function>());
});
test('Can instantiate GetProductInfo', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetProductInfo = kernel32.lookupFunction<
Int32 Function(
Uint32 dwOSMajorVersion,
Uint32 dwOSMinorVersion,
Uint32 dwSpMajorVersion,
Uint32 dwSpMinorVersion,
Pointer<Uint32> pdwReturnedProductType),
int Function(
int dwOSMajorVersion,
int dwOSMinorVersion,
int dwSpMajorVersion,
int dwSpMinorVersion,
Pointer<Uint32> pdwReturnedProductType)>('GetProductInfo');
expect(GetProductInfo, isA<Function>());
});
test('Can instantiate GetStdHandle', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetStdHandle = kernel32.lookupFunction<
IntPtr Function(Uint32 nStdHandle),
int Function(int nStdHandle)>('GetStdHandle');
expect(GetStdHandle, isA<Function>());
});
test('Can instantiate GetSystemInfo', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetSystemInfo = kernel32.lookupFunction<
Void Function(Pointer<SYSTEM_INFO> lpSystemInfo),
void Function(Pointer<SYSTEM_INFO> lpSystemInfo)>('GetSystemInfo');
expect(GetSystemInfo, isA<Function>());
});
test('Can instantiate GetSystemPowerStatus', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetSystemPowerStatus = kernel32.lookupFunction<
Int32 Function(Pointer<SYSTEM_POWER_STATUS> lpSystemPowerStatus),
int Function(Pointer<SYSTEM_POWER_STATUS> lpSystemPowerStatus)>(
'GetSystemPowerStatus');
expect(GetSystemPowerStatus, isA<Function>());
});
test('Can instantiate GetTempPath', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetTempPath = kernel32.lookupFunction<
Uint32 Function(Uint32 nBufferLength, Pointer<Utf16> lpBuffer),
int Function(
int nBufferLength, Pointer<Utf16> lpBuffer)>('GetTempPathW');
expect(GetTempPath, isA<Function>());
});
test('Can instantiate GetVersionEx', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetVersionEx = kernel32.lookupFunction<
Int32 Function(Pointer<OSVERSIONINFO> lpVersionInformation),
int Function(
Pointer<OSVERSIONINFO> lpVersionInformation)>('GetVersionExW');
expect(GetVersionEx, isA<Function>());
});
test('Can instantiate GetVolumePathNamesForVolumeName', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final GetVolumePathNamesForVolumeName = kernel32.lookupFunction<
Int32 Function(
Pointer<Utf16> lpszVolumeName,
Pointer<Utf16> lpszVolumePathNames,
Uint32 cchBufferLength,
Pointer<Uint32> lpcchReturnLength),
int Function(
Pointer<Utf16> lpszVolumeName,
Pointer<Utf16> lpszVolumePathNames,
int cchBufferLength,
Pointer<Uint32> lpcchReturnLength)>(
'GetVolumePathNamesForVolumeNameW');
expect(GetVolumePathNamesForVolumeName, isA<Function>());
});
test('Can instantiate HeapAlloc', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final HeapAlloc = kernel32.lookupFunction<
Pointer Function(IntPtr hHeap, Uint32 dwflags, Uint32 dwBytes),
Pointer Function(int hHeap, int dwflags, int dwBytes)>('HeapAlloc');
expect(HeapAlloc, isA<Function>());
});
test('Can instantiate HeapFree', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final HeapFree = kernel32.lookupFunction<
Int32 Function(IntPtr hHeap, Uint32 dwFlags, Pointer lpMem),
int Function(int hHeap, int dwFlags, Pointer lpMem)>('HeapFree');
expect(HeapFree, isA<Function>());
});
test('Can instantiate InitializeProcThreadAttributeList', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final InitializeProcThreadAttributeList = kernel32.lookupFunction<
Int32 Function(Pointer lpAttributeList, Uint32 dwAttributeCount,
Uint32 dwFlags, Pointer<IntPtr> lpSize),
int Function(
Pointer lpAttributeList,
int dwAttributeCount,
int dwFlags,
Pointer<IntPtr> lpSize)>('InitializeProcThreadAttributeList');
expect(InitializeProcThreadAttributeList, isA<Function>());
});
test('Can instantiate IsDebuggerPresent', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final IsDebuggerPresent =
kernel32.lookupFunction<Int32 Function(), int Function()>(
'IsDebuggerPresent');
expect(IsDebuggerPresent, isA<Function>());
});
test('Can instantiate LoadLibrary', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final LoadLibrary = kernel32.lookupFunction<
IntPtr Function(Pointer<Utf16> lpLibFileName),
int Function(Pointer<Utf16> lpLibFileName)>('LoadLibraryW');
expect(LoadLibrary, isA<Function>());
});
test('Can instantiate OpenProcess', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final OpenProcess = kernel32.lookupFunction<
Int32 Function(
Uint32 dwDesiredAccess, Int32 bInheritHandle, Uint32 dwProcessId),
int Function(int dwDesiredAccess, int bInheritHandle,
int dwProcessId)>('OpenProcess');
expect(OpenProcess, isA<Function>());
});
test('Can instantiate QueryDosDevice', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final QueryDosDevice = kernel32.lookupFunction<
Uint32 Function(Pointer<Utf16> lpDeviceName,
Pointer<Utf16> lpTargetPath, Uint32 ucchMax),
int Function(Pointer<Utf16> lpDeviceName, Pointer<Utf16> lpTargetPath,
int ucchMax)>('QueryDosDeviceW');
expect(QueryDosDevice, isA<Function>());
});
test('Can instantiate QueryPerformanceCounter', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final QueryPerformanceCounter = kernel32.lookupFunction<
Int32 Function(Pointer<Int64> lpPerformanceCount),
int Function(
Pointer<Int64> lpPerformanceCount)>('QueryPerformanceCounter');
expect(QueryPerformanceCounter, isA<Function>());
});
test('Can instantiate QueryPerformanceFrequency', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final QueryPerformanceFrequency = kernel32.lookupFunction<
Int32 Function(Pointer<Int64> lpPerformanceCount),
int Function(
Pointer<Int64> lpPerformanceCount)>('QueryPerformanceFrequency');
expect(QueryPerformanceFrequency, isA<Function>());
});
test('Can instantiate ReadConsole', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final ReadConsole = kernel32.lookupFunction<
Int32 Function(
IntPtr hConsoleInput,
Pointer lpBuffer,
Uint32 nNumberOfCharsToRead,
Pointer<Uint32> lpNumberOfCharsRead,
Pointer pInputControl),
int Function(
int hConsoleInput,
Pointer lpBuffer,
int nNumberOfCharsToRead,
Pointer<Uint32> lpNumberOfCharsRead,
Pointer pInputControl)>('ReadConsoleW');
expect(ReadConsole, isA<Function>());
});
test('Can instantiate ReadFile', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final ReadFile = kernel32.lookupFunction<
Int32 Function(
IntPtr hFile,
Pointer lpBuffer,
Uint32 nNumberOfBytesToRead,
Pointer<Uint32> lpNumberOfBytesRead,
Pointer lpOverlapped),
int Function(
int hFile,
Pointer lpBuffer,
int nNumberOfBytesToRead,
Pointer<Uint32> lpNumberOfBytesRead,
Pointer lpOverlapped)>('ReadFile');
expect(ReadFile, isA<Function>());
});
test('Can instantiate ReadProcessMemory', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final ReadProcessMemory = kernel32.lookupFunction<
Int32 Function(
IntPtr hProcess,
Pointer<Void> lpBaseAddress,
Pointer<Void> lpBuffer,
IntPtr nSize,
Pointer<IntPtr> lpNumberOfBytesRead),
int Function(
int hProcess,
Pointer<Void> lpBaseAddress,
Pointer<Void> lpBuffer,
int nSize,
Pointer<IntPtr> lpNumberOfBytesRead)>('ReadProcessMemory');
expect(ReadProcessMemory, isA<Function>());
});
test('Can instantiate ResizePseudoConsole', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final ResizePseudoConsole = kernel32.lookupFunction<
Int32 Function(Pointer<IntPtr> hPC, Int32 size),
int Function(Pointer<IntPtr> hPC, int size)>('ResizePseudoConsole');
expect(ResizePseudoConsole, isA<Function>());
});
test('Can instantiate ScrollConsoleScreenBuffer', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final ScrollConsoleScreenBuffer = kernel32.lookupFunction<
Int32 Function(
IntPtr hConsoleOutput,
Pointer<SMALL_RECT> lpScrollRectangle,
Pointer<SMALL_RECT> lpClipRectangle,
Int32 dwDestinationOrigin,
Pointer<CHAR_INFO> lpFill),
int Function(
int hConsoleOutput,
Pointer<SMALL_RECT> lpScrollRectangle,
Pointer<SMALL_RECT> lpClipRectangle,
int dwDestinationOrigin,
Pointer<CHAR_INFO> lpFill)>('ScrollConsoleScreenBufferW');
expect(ScrollConsoleScreenBuffer, isA<Function>());
});
test('Can instantiate SetConsoleCtrlHandler', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final SetConsoleCtrlHandler = kernel32.lookupFunction<
Int32 Function(Pointer<NativeFunction> HandlerRoutine, Int32 Add),
int Function(Pointer<NativeFunction> HandlerRoutine,
int Add)>('SetConsoleCtrlHandler');
expect(SetConsoleCtrlHandler, isA<Function>());
});
test('Can instantiate SetConsoleCursorInfo', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final SetConsoleCursorInfo = kernel32.lookupFunction<
Int32 Function(IntPtr hConsoleOutput,
Pointer<CONSOLE_CURSOR_INFO> lpConsoleCursorInfo),
int Function(int hConsoleOutput,
Pointer<CONSOLE_CURSOR_INFO> lpConsoleCursorInfo)>(
'SetConsoleCursorInfo');
expect(SetConsoleCursorInfo, isA<Function>());
});
test('Can instantiate SetConsoleCursorPosition', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final SetConsoleCursorPosition = kernel32.lookupFunction<
Int32 Function(IntPtr hConsoleOutput, Int32 dwCursorPosition),
int Function(int hConsoleOutput,
int dwCursorPosition)>('SetConsoleCursorPosition');
expect(SetConsoleCursorPosition, isA<Function>());
});
test('Can instantiate SetConsoleDisplayMode', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final SetConsoleDisplayMode = kernel32.lookupFunction<
Int32 Function(IntPtr hConsoleOutput, Uint32 dwFlags,
Pointer<COORD> lpNewScreenBufferDimensions),
int Function(int hConsoleOutput, int dwFlags,
Pointer<COORD> lpNewScreenBufferDimensions)>(
'SetConsoleDisplayMode');
expect(SetConsoleDisplayMode, isA<Function>());
});
test('Can instantiate SetConsoleMode', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final SetConsoleMode = kernel32.lookupFunction<
Int32 Function(IntPtr hConsoleHandle, Uint32 dwMode),
int Function(int hConsoleHandle, int dwMode)>('SetConsoleMode');
expect(SetConsoleMode, isA<Function>());
});
test('Can instantiate SetConsoleTextAttribute', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final SetConsoleTextAttribute = kernel32.lookupFunction<
Int32 Function(IntPtr hConsoleOutput, Uint16 wAttributes),
int Function(
int hConsoleOutput, int wAttributes)>('SetConsoleTextAttribute');
expect(SetConsoleTextAttribute, isA<Function>());
});
test('Can instantiate SetConsoleWindowInfo', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final SetConsoleWindowInfo = kernel32.lookupFunction<
Int32 Function(IntPtr hConsoleOutput, Int32 bAbsolute,
Pointer<SMALL_RECT> lpConsoleWindow),
int Function(int hConsoleOutput, int bAbsolute,
Pointer<SMALL_RECT> lpConsoleWindow)>('SetConsoleWindowInfo');
expect(SetConsoleWindowInfo, isA<Function>());
});
test('Can instantiate SetStdHandle', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final SetStdHandle = kernel32.lookupFunction<
Int32 Function(Uint32 nStdHandle, IntPtr hHandle),
int Function(int nStdHandle, int hHandle)>('SetStdHandle');
expect(SetStdHandle, isA<Function>());
});
test('Can instantiate Sleep', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final Sleep = kernel32.lookupFunction<
Void Function(Uint32 dwMilliseconds),
void Function(int dwMilliseconds)>('Sleep');
expect(Sleep, isA<Function>());
});
test('Can instantiate UpdateProcThreadAttribute', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final UpdateProcThreadAttribute = kernel32.lookupFunction<
Int32 Function(
Pointer lpAttributeList,
Uint32 dwFlags,
IntPtr Attribute,
Pointer lpValue,
IntPtr cbSize,
Pointer lpPreviousValue,
Pointer<IntPtr> lpReturnSize),
int Function(
Pointer lpAttributeList,
int dwFlags,
int Attribute,
Pointer lpValue,
int cbSize,
Pointer lpPreviousValue,
Pointer<IntPtr> lpReturnSize)>('UpdateProcThreadAttribute');
expect(UpdateProcThreadAttribute, isA<Function>());
});
test('Can instantiate UpdateResource', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final UpdateResource = kernel32.lookupFunction<
Int32 Function(
IntPtr hUpdate,
Pointer<Utf16> lpType,
Pointer<Utf16> lpName,
Uint16 wLanguage,
Pointer lpData,
Uint32 cb),
int Function(
int hUpdate,
Pointer<Utf16> lpType,
Pointer<Utf16> lpName,
int wLanguage,
Pointer lpData,
int cb)>('UpdateResourceW');
expect(UpdateResource, isA<Function>());
});
test('Can instantiate VirtualAlloc', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final VirtualAlloc = kernel32.lookupFunction<
Pointer<Void> Function(Pointer<Void> lpAddress, IntPtr dwSize,
Uint32 flAllocationType, Uint32 flProtect),
Pointer<Void> Function(Pointer<Void> lpAddress, int dwSize,
int flAllocationType, int flProtect)>('VirtualAlloc');
expect(VirtualAlloc, isA<Function>());
});
test('Can instantiate VirtualFree', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final VirtualFree = kernel32.lookupFunction<
Int32 Function(
Pointer<Void> lpAddress, IntPtr dwSize, Uint32 dwFreeType),
int Function(Pointer<Void> lpAddress, int dwSize,
int dwFreeType)>('VirtualFree');
expect(VirtualFree, isA<Function>());
});
test('Can instantiate WriteConsole', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final WriteConsole = kernel32.lookupFunction<
Int32 Function(
IntPtr hConsoleOutput,
Pointer lpBuffer,
Uint32 nNumberOfCharsToWrite,
Pointer<Uint32> lpNumberOfCharsWritten,
Pointer lpReserved),
int Function(
int hConsoleOutput,
Pointer lpBuffer,
int nNumberOfCharsToWrite,
Pointer<Uint32> lpNumberOfCharsWritten,
Pointer lpReserved)>('WriteConsoleW');
expect(WriteConsole, isA<Function>());
});
test('Can instantiate WriteFile', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final WriteFile = kernel32.lookupFunction<
Int32 Function(
IntPtr hFile,
Pointer lpBuffer,
Uint32 nNumberOfBytesToWrite,
Pointer<Uint32> lpNumberOfBytesWritten,
Pointer lpOverlapped),
int Function(
int hFile,
Pointer lpBuffer,
int nNumberOfBytesToWrite,
Pointer<Uint32> lpNumberOfBytesWritten,
Pointer lpOverlapped)>('WriteFile');
expect(WriteFile, isA<Function>());
});
test('Can instantiate WriteProcessMemory', () {
final kernel32 = DynamicLibrary.open('kernel32.dll');
final WriteProcessMemory = kernel32.lookupFunction<
Int32 Function(
IntPtr hProcess,
Pointer<Void> lpBaseAddress,
Pointer<Void> lpBuffer,
IntPtr nSize,
Pointer<IntPtr> lpNumberOfBytesWritten),
int Function(
int hProcess,
Pointer<Void> lpBaseAddress,
Pointer<Void> lpBuffer,
int nSize,
Pointer<IntPtr> lpNumberOfBytesWritten)>('WriteProcessMemory');
expect(WriteProcessMemory, isA<Function>());
});
});
group('Test user32 functions', () {
test('Can instantiate AppendMenu', () {
final user32 = DynamicLibrary.open('user32.dll');
final AppendMenu = user32.lookupFunction<
Int32 Function(IntPtr hMenu, Uint32 uFlags, IntPtr uIDNewItem,
Pointer<Utf16> lpNewItem),
int Function(int hMenu, int uFlags, int uIDNewItem,
Pointer<Utf16> lpNewItem)>('AppendMenuW');
expect(AppendMenu, isA<Function>());
});
test('Can instantiate BeginPaint', () {
final user32 = DynamicLibrary.open('user32.dll');
final BeginPaint = user32.lookupFunction<
IntPtr Function(IntPtr hWnd, Pointer<PAINTSTRUCT> lpPaint),
int Function(int hWnd, Pointer<PAINTSTRUCT> lpPaint)>('BeginPaint');
expect(BeginPaint, isA<Function>());
});
test('Can instantiate BringWindowToTop', () {
final user32 = DynamicLibrary.open('user32.dll');
final BringWindowToTop = user32.lookupFunction<
Int32 Function(IntPtr hWnd),
int Function(int hWnd)>('BringWindowToTop');
expect(BringWindowToTop, isA<Function>());
});
test('Can instantiate ClipCursor', () {
final user32 = DynamicLibrary.open('user32.dll');
final ClipCursor = user32.lookupFunction<
Int32 Function(Pointer<RECT> lpRect),
int Function(Pointer<RECT> lpRect)>('ClipCursor');
expect(ClipCursor, isA<Function>());
});
test('Can instantiate CopyIcon', () {
final user32 = DynamicLibrary.open('user32.dll');
final CopyIcon = user32.lookupFunction<IntPtr Function(IntPtr hIcon),
int Function(int hIcon)>('CopyIcon');
expect(CopyIcon, isA<Function>());
});
test('Can instantiate CreateAcceleratorTable', () {
final user32 = DynamicLibrary.open('user32.dll');
final CreateAcceleratorTable = user32.lookupFunction<
IntPtr Function(Pointer paccel, Int32 cAccel),
int Function(Pointer paccel, int cAccel)>('CreateAcceleratorTableW');
expect(CreateAcceleratorTable, isA<Function>());
});
test('Can instantiate CreateDialogIndirectParam', () {
final user32 = DynamicLibrary.open('user32.dll');
final CreateDialogIndirectParam = user32.lookupFunction<
IntPtr Function(
IntPtr hInstance,
Pointer<DLGTEMPLATE> lpTemplate,
IntPtr hWndParent,
Pointer<NativeFunction> lpDialogFunc,
IntPtr dwInitParam),
int Function(
int hInstance,
Pointer<DLGTEMPLATE> lpTemplate,
int hWndParent,
Pointer<NativeFunction> lpDialogFunc,
int dwInitParam)>('CreateDialogIndirectParamW');
expect(CreateDialogIndirectParam, isA<Function>());
});
test('Can instantiate CreateMenu', () {
final user32 = DynamicLibrary.open('user32.dll');
final CreateMenu = user32
.lookupFunction<IntPtr Function(), int Function()>('CreateMenu');
expect(CreateMenu, isA<Function>());
});
test('Can instantiate CreateWindowEx', () {
final user32 = DynamicLibrary.open('user32.dll');
final CreateWindowEx = user32.lookupFunction<
Int32 Function(
Uint32 dwExStyle,
Pointer<Utf16> lpClassName,
Pointer<Utf16> lpWindowName,
Uint32 dwStyle,
Int32 X,
Int32 Y,
Int32 nWidth,
Int32 nHeight,
IntPtr hWndParent,
IntPtr hMenu,
IntPtr hInstance,
Pointer<Void> lpParam),
int Function(
int dwExStyle,
Pointer<Utf16> lpClassName,
Pointer<Utf16> lpWindowName,
int dwStyle,
int X,
int Y,
int nWidth,
int nHeight,
int hWndParent,
int hMenu,
int hInstance,
Pointer<Void> lpParam)>('CreateWindowExW');
expect(CreateWindowEx, isA<Function>());
});
test('Can instantiate DefWindowProc', () {
final user32 = DynamicLibrary.open('user32.dll');
final DefWindowProc = user32.lookupFunction<
IntPtr Function(
IntPtr hWnd, Uint32 Msg, IntPtr wParam, IntPtr lParam),
int Function(
int hWnd, int Msg, int wParam, int lParam)>('DefWindowProcW');
expect(DefWindowProc, isA<Function>());
});
test('Can instantiate DestroyIcon', () {
final user32 = DynamicLibrary.open('user32.dll');
final DestroyIcon = user32.lookupFunction<Int32 Function(IntPtr hIcon),
int Function(int hIcon)>('DestroyIcon');
expect(DestroyIcon, isA<Function>());
});
test('Can instantiate DestroyWindow', () {
final user32 = DynamicLibrary.open('user32.dll');
final DestroyWindow = user32.lookupFunction<Int32 Function(IntPtr hWnd),
int Function(int hWnd)>('DestroyWindow');
expect(DestroyWindow, isA<Function>());
});
test('Can instantiate DialogBoxIndirectParam', () {
final user32 = DynamicLibrary.open('user32.dll');
final DialogBoxIndirectParam = user32.lookupFunction<
IntPtr Function(
IntPtr hInstance,
Pointer<DLGTEMPLATE> hDialogTemplate,
IntPtr hWndParent,
Pointer<NativeFunction> lpDialogFunc,
IntPtr dwInitParam),
int Function(
int hInstance,
Pointer<DLGTEMPLATE> hDialogTemplate,
int hWndParent,
Pointer<NativeFunction> lpDialogFunc,
int dwInitParam)>('DialogBoxIndirectParamW');
expect(DialogBoxIndirectParam, isA<Function>());
});
test('Can instantiate DispatchMessage', () {
final user32 = DynamicLibrary.open('user32.dll');
final DispatchMessage = user32.lookupFunction<
IntPtr Function(Pointer<MSG> lpMsg),
int Function(Pointer<MSG> lpMsg)>('DispatchMessageW');
expect(DispatchMessage, isA<Function>());
});
test('Can instantiate DrawIcon', () {
final user32 = DynamicLibrary.open('user32.dll');
final DrawIcon = user32.lookupFunction<
Int32 Function(IntPtr hDC, Int32 X, Int32 Y, IntPtr hIcon),
int Function(int hDC, int X, int Y, int hIcon)>('DrawIcon');
expect(DrawIcon, isA<Function>());
});
test('Can instantiate DrawText', () {
final user32 = DynamicLibrary.open('user32.dll');
final DrawText = user32.lookupFunction<
Int32 Function(IntPtr hdc, Pointer<Utf16> lpchText, Int32 cchText,
Pointer<RECT> lprc, Uint32 format),
int Function(int hdc, Pointer<Utf16> lpchText, int cchText,
Pointer<RECT> lprc, int format)>('DrawTextW');
expect(DrawText, isA<Function>());
});
test('Can instantiate EnableMenuItem', () {
final user32 = DynamicLibrary.open('user32.dll');
final EnableMenuItem = user32.lookupFunction<
Int32 Function(IntPtr hMenu, Uint32 uIDEnableItem, Uint32 uEnable),
int Function(
int hMenu, int uIDEnableItem, int uEnable)>('EnableMenuItem');
expect(EnableMenuItem, isA<Function>());
});
test('Can instantiate EndDialog', () {
final user32 = DynamicLibrary.open('user32.dll');
final EndDialog = user32.lookupFunction<
Int32 Function(IntPtr hDlg, IntPtr nResult),
int Function(int hDlg, int nResult)>('EndDialog');
expect(EndDialog, isA<Function>());
});
test('Can instantiate EndPaint', () {
final user32 = DynamicLibrary.open('user32.dll');
final EndPaint = user32.lookupFunction<
Int32 Function(IntPtr hWnd, Pointer<PAINTSTRUCT> lpPaint),
int Function(int hWnd, Pointer<PAINTSTRUCT> lpPaint)>('EndPaint');
expect(EndPaint, isA<Function>());
});
test('Can instantiate EnumDisplayMonitors', () {
final user32 = DynamicLibrary.open('user32.dll');
final EnumDisplayMonitors = user32.lookupFunction<
Int32 Function(IntPtr hdc, Pointer lprcClip,
Pointer<NativeFunction> lpfnEnum, IntPtr dwData),
int Function(
int hdc,
Pointer lprcClip,
Pointer<NativeFunction> lpfnEnum,
int dwData)>('EnumDisplayMonitors');
expect(EnumDisplayMonitors, isA<Function>());
});
test('Can instantiate EnumWindows', () {
final user32 = DynamicLibrary.open('user32.dll');
final EnumWindows = user32.lookupFunction<
Int32 Function(Pointer<NativeFunction> lpEnumFunc, IntPtr lParam),
int Function(
Pointer<NativeFunction> lpEnumFunc, int lParam)>('EnumWindows');
expect(EnumWindows, isA<Function>());
});
test('Can instantiate FillRect', () {
final user32 = DynamicLibrary.open('user32.dll');
final FillRect = user32.lookupFunction<
Int32 Function(IntPtr hDC, Pointer<RECT> lprc, IntPtr hbr),
int Function(int hDC, Pointer<RECT> lprc, int hbr)>('FillRect');
expect(FillRect, isA<Function>());
});
test('Can instantiate FindWindowEx', () {
final user32 = DynamicLibrary.open('user32.dll');
final FindWindowEx = user32.lookupFunction<
IntPtr Function(IntPtr hWndParent, IntPtr hWndChildAfter,
Pointer<Utf16> lpszClass, Pointer<Utf16> lpszWindow),
int Function(
int hWndParent,
int hWndChildAfter,
Pointer<Utf16> lpszClass,
Pointer<Utf16> lpszWindow)>('FindWindowExW');
expect(FindWindowEx, isA<Function>());
});
test('Can instantiate GetClientRect', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetClientRect = user32.lookupFunction<
Int32 Function(IntPtr hwnd, Pointer<RECT> lpRect),
int Function(int hwnd, Pointer<RECT> lpRect)>('GetClientRect');
expect(GetClientRect, isA<Function>());
});
test('Can instantiate GetCursor', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetCursor =
user32.lookupFunction<IntPtr Function(), int Function()>('GetCursor');
expect(GetCursor, isA<Function>());
});
test('Can instantiate GetCursorPos', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetCursorPos = user32.lookupFunction<
Int32 Function(Pointer<POINT> lpPoint),
int Function(Pointer<POINT> lpPoint)>('GetCursorPos');
expect(GetCursorPos, isA<Function>());
});
test('Can instantiate GetDC', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetDC = user32.lookupFunction<IntPtr Function(IntPtr hwnd),
int Function(int hwnd)>('GetDC');
expect(GetDC, isA<Function>());
});
test('Can instantiate GetDialogBaseUnits', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetDialogBaseUnits =
user32.lookupFunction<Int32 Function(), int Function()>(
'GetDialogBaseUnits');
expect(GetDialogBaseUnits, isA<Function>());
});
test('Can instantiate GetDlgItem', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetDlgItem = user32.lookupFunction<
IntPtr Function(IntPtr hDlg, Int32 nIDDlgItem),
int Function(int hDlg, int nIDDlgItem)>('GetDlgItem');
expect(GetDlgItem, isA<Function>());
});
test('Can instantiate GetDlgItemInt', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetDlgItemInt = user32.lookupFunction<
Uint32 Function(IntPtr hDlg, Int32 nIDDlgItem,
Pointer<Int32> lpTranslated, Int32 bSigned),
int Function(int hDlg, int nIDDlgItem, Pointer<Int32> lpTranslated,
int bSigned)>('GetDlgItemInt');
expect(GetDlgItemInt, isA<Function>());
});
test('Can instantiate GetDlgItemText', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetDlgItemText = user32.lookupFunction<
Uint32 Function(IntPtr hDlg, Int32 nIDDlgItem,
Pointer<Utf16> lpString, Int32 cchMax),
int Function(int hDlg, int nIDDlgItem, Pointer<Utf16> lpString,
int cchMax)>('GetDlgItemTextW');
expect(GetDlgItemText, isA<Function>());
});
test('Can instantiate GetDpiForSystem', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetDpiForSystem = user32
.lookupFunction<Int32 Function(), int Function()>('GetDpiForSystem');
expect(GetDpiForSystem, isA<Function>());
});
test('Can instantiate GetForegroundWindow', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetForegroundWindow =
user32.lookupFunction<IntPtr Function(), int Function()>(
'GetForegroundWindow');
expect(GetForegroundWindow, isA<Function>());
});
test('Can instantiate GetMessage', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetMessage = user32.lookupFunction<
Int32 Function(Pointer<MSG> lpMsg, IntPtr hWnd, Uint32 wMsgFilterMin,
Uint32 wMsgFilterMax),
int Function(Pointer<MSG> lpMsg, int hWnd, int wMsgFilterMin,
int wMsgFilterMax)>('GetMessageW');
expect(GetMessage, isA<Function>());
});
test('Can instantiate GetMonitorInfo', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetMonitorInfo = user32.lookupFunction<
Int32 Function(IntPtr hMonitor, Pointer<MONITORINFO> lpmi),
int Function(
int hMonitor, Pointer<MONITORINFO> lpmi)>('GetMonitorInfoW');
expect(GetMonitorInfo, isA<Function>());
});
test('Can instantiate GetNextDlgGroupItem', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetNextDlgGroupItem = user32.lookupFunction<
IntPtr Function(IntPtr hDlg, IntPtr hCtl, Int32 bPrevious),
int Function(
int hDlg, int hCtl, int bPrevious)>('GetNextDlgGroupItem');
expect(GetNextDlgGroupItem, isA<Function>());
});
test('Can instantiate GetNextDlgTabItem', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetNextDlgTabItem = user32.lookupFunction<
IntPtr Function(IntPtr hDlg, IntPtr hCtl, Int32 bPrevious),
int Function(int hDlg, int hCtl, int bPrevious)>('GetNextDlgTabItem');
expect(GetNextDlgTabItem, isA<Function>());
});
test('Can instantiate GetParent', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetParent = user32.lookupFunction<IntPtr Function(IntPtr hWnd),
int Function(int hWnd)>('GetParent');
expect(GetParent, isA<Function>());
});
test('Can instantiate GetScrollInfo', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetScrollInfo = user32.lookupFunction<
Int32 Function(IntPtr hwnd, Int32 nBar, Pointer<SCROLLINFO> lpsi),
int Function(
int hwnd, int nBar, Pointer<SCROLLINFO> lpsi)>('GetScrollInfo');
expect(GetScrollInfo, isA<Function>());
});
test('Can instantiate GetShellWindow', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetShellWindow = user32
.lookupFunction<IntPtr Function(), int Function()>('GetShellWindow');
expect(GetShellWindow, isA<Function>());
});
test('Can instantiate GetSysColor', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetSysColor = user32.lookupFunction<Uint32 Function(Int32 nIndex),
int Function(int nIndex)>('GetSysColor');
expect(GetSysColor, isA<Function>());
});
test('Can instantiate GetSystemDpiForProcess', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetSystemDpiForProcess = user32.lookupFunction<
Uint32 Function(IntPtr hProcess),
int Function(int hProcess)>('GetSystemDpiForProcess');
expect(GetSystemDpiForProcess, isA<Function>());
});
test('Can instantiate GetSystemMenu', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetSystemMenu = user32.lookupFunction<
IntPtr Function(IntPtr hWnd, Int32 bRevert),
int Function(int hWnd, int bRevert)>('GetSystemMenu');
expect(GetSystemMenu, isA<Function>());
});
test('Can instantiate GetSystemMetrics', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetSystemMetrics = user32.lookupFunction<
Int32 Function(Int32 nIndex),
int Function(int nIndex)>('GetSystemMetrics');
expect(GetSystemMetrics, isA<Function>());
});
test('Can instantiate GetWindow', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetWindow = user32.lookupFunction<
IntPtr Function(IntPtr hWnd, Uint32 uCmd),
int Function(int hWnd, int uCmd)>('GetWindow');
expect(GetWindow, isA<Function>());
});
test('Can instantiate GetWindowTextLength', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetWindowTextLength = user32.lookupFunction<
Int32 Function(IntPtr hWnd),
int Function(int hWnd)>('GetWindowTextLengthW');
expect(GetWindowTextLength, isA<Function>());
});
test('Can instantiate GetWindowText', () {
final user32 = DynamicLibrary.open('user32.dll');
final GetWindowText = user32.lookupFunction<
Int32 Function(IntPtr hWnd, Pointer<Utf16> lpString, Int32 nMaxCount),
int Function(int hWnd, Pointer<Utf16> lpString,
int nMaxCount)>('GetWindowTextW');
expect(GetWindowText, isA<Function>());
});
test('Can instantiate InvalidateRect', () {
final user32 = DynamicLibrary.open('user32.dll');
final InvalidateRect = user32.lookupFunction<
Int32 Function(IntPtr hWnd, Pointer<RECT> lpRect, Int32 bErase),
int Function(
int hWnd, Pointer<RECT> lpRect, int bErase)>('InvalidateRect');
expect(InvalidateRect, isA<Function>());
});
test('Can instantiate IsClipboardFormatAvailable', () {
final user32 = DynamicLibrary.open('user32.dll');
final IsClipboardFormatAvailable = user32.lookupFunction<
Int32 Function(Uint32 format),
int Function(int format)>('IsClipboardFormatAvailable');
expect(IsClipboardFormatAvailable, isA<Function>());
});
test('Can instantiate IsDialogMessage', () {
final user32 = DynamicLibrary.open('user32.dll');
final IsDialogMessage = user32.lookupFunction<
Int32 Function(IntPtr hDlg, Pointer<MSG> lpMsg),
int Function(int hDlg, Pointer<MSG> lpMsg)>('IsDialogMessageW');
expect(IsDialogMessage, isA<Function>());
});
test('Can instantiate IsWindowVisible', () {
final user32 = DynamicLibrary.open('user32.dll');
final IsWindowVisible = user32.lookupFunction<Int32 Function(IntPtr hWnd),
int Function(int hWnd)>('IsWindowVisible');
expect(IsWindowVisible, isA<Function>());
});
test('Can instantiate KillTimer', () {
final user32 = DynamicLibrary.open('user32.dll');
final KillTimer = user32.lookupFunction<
Int32 Function(IntPtr hWnd, IntPtr uIDEvent),
int Function(int hWnd, int uIDEvent)>('KillTimer');
expect(KillTimer, isA<Function>());
});
test('Can instantiate LoadCursor', () {
final user32 = DynamicLibrary.open('user32.dll');
final LoadCursor = user32.lookupFunction<
IntPtr Function(IntPtr hInstance, Pointer<Utf16> lpCursorName),
int Function(
int hInstance, Pointer<Utf16> lpCursorName)>('LoadCursorW');
expect(LoadCursor, isA<Function>());
});
test('Can instantiate LoadIcon', () {
final user32 = DynamicLibrary.open('user32.dll');
final LoadIcon = user32.lookupFunction<
IntPtr Function(IntPtr hInstance, Pointer<Utf16> lpIconName),
int Function(int hInstance, Pointer<Utf16> lpIconName)>('LoadIconW');
expect(LoadIcon, isA<Function>());
});
test('Can instantiate LoadImage', () {
final user32 = DynamicLibrary.open('user32.dll');
final LoadImage = user32.lookupFunction<
IntPtr Function(IntPtr hInst, Pointer<Utf16> name, Uint32 type,
Int32 cx, Int32 cy, Uint32 fuLoad),
int Function(int hInst, Pointer<Utf16> name, int type, int cx, int cy,
int fuLoad)>('LoadImageW');
expect(LoadImage, isA<Function>());
});
test('Can instantiate LockWorkStation', () {
final user32 = DynamicLibrary.open('user32.dll');
final LockWorkStation = user32
.lookupFunction<Int32 Function(), int Function()>('LockWorkStation');
expect(LockWorkStation, isA<Function>());
});
test('Can instantiate MapDialogRect', () {
final user32 = DynamicLibrary.open('user32.dll');
final MapDialogRect = user32.lookupFunction<
Int32 Function(IntPtr hDlg, Pointer<RECT> lpRect),
int Function(int hDlg, Pointer<RECT> lpRect)>('MapDialogRect');
expect(MapDialogRect, isA<Function>());
});
test('Can instantiate MessageBox', () {
final user32 = DynamicLibrary.open('user32.dll');
final MessageBox = user32.lookupFunction<
Int32 Function(IntPtr hWnd, Pointer<Utf16> lpText,
Pointer<Utf16> lpCaption, Uint32 uType),
int Function(int hWnd, Pointer<Utf16> lpText,
Pointer<Utf16> lpCaption, int uType)>('MessageBoxW');
expect(MessageBox, isA<Function>());
});
test('Can instantiate MonitorFromPoint', () {
final user32 = DynamicLibrary.open('user32.dll');
final MonitorFromPoint = user32.lookupFunction<
IntPtr Function(Int64 pt, Uint32 dwFlags),
int Function(int pt, int dwFlags)>('MonitorFromPoint');
expect(MonitorFromPoint, isA<Function>());
});
test('Can instantiate MonitorFromWindow', () {
final user32 = DynamicLibrary.open('user32.dll');
final MonitorFromWindow = user32.lookupFunction<
IntPtr Function(IntPtr hwnd, Uint32 dwFlags),
int Function(int hwnd, int dwFlags)>('MonitorFromWindow');
expect(MonitorFromWindow, isA<Function>());
});
test('Can instantiate MoveWindow', () {
final user32 = DynamicLibrary.open('user32.dll');
final MoveWindow = user32.lookupFunction<
Int32 Function(IntPtr hWnd, Int32 X, Int32 Y, Int32 nWidth,
Int32 nHeight, Int32 bRepaint),
int Function(int hWnd, int X, int Y, int nWidth, int nHeight,
int bRepaint)>('MoveWindow');
expect(MoveWindow, isA<Function>());
});
test('Can instantiate MsgWaitForMultipleObjects', () {
final user32 = DynamicLibrary.open('user32.dll');
final MsgWaitForMultipleObjects = user32.lookupFunction<
Uint32 Function(Uint32 nCount, Pointer<IntPtr> pHandles,
Int32 fWaitAll, Uint32 dwMilliseconds, Uint32 dwWakeMask),
int Function(int nCount, Pointer<IntPtr> pHandles, int fWaitAll,
int dwMilliseconds, int dwWakeMask)>('MsgWaitForMultipleObjects');
expect(MsgWaitForMultipleObjects, isA<Function>());
});
test('Can instantiate PeekMessage', () {
final user32 = DynamicLibrary.open('user32.dll');
final PeekMessage = user32.lookupFunction<
Int32 Function(Pointer<MSG> lpMsg, IntPtr hWnd, Uint32 wMsgFilterMin,
Uint32 wMsgFilterMax, Uint32 wRemoveMsg),
int Function(Pointer<MSG> lpMsg, int hWnd, int wMsgFilterMin,
int wMsgFilterMax, int wRemoveMsg)>('PeekMessageW');
expect(PeekMessage, isA<Function>());
});
test('Can instantiate PostQuitMessage', () {
final user32 = DynamicLibrary.open('user32.dll');
final PostQuitMessage = user32.lookupFunction<
Void Function(Int32 nExitCode),
void Function(int nExitCode)>('PostQuitMessage');
expect(PostQuitMessage, isA<Function>());
});
test('Can instantiate RegisterClass', () {
final user32 = DynamicLibrary.open('user32.dll');
final RegisterClass = user32.lookupFunction<
Int16 Function(Pointer<WNDCLASS> lpWndClass),
int Function(Pointer<WNDCLASS> lpWndClass)>('RegisterClassW');
expect(RegisterClass, isA<Function>());
});
test('Can instantiate RegisterWindowMessage', () {
final user32 = DynamicLibrary.open('user32.dll');
final RegisterWindowMessage = user32.lookupFunction<
Uint32 Function(Pointer<Utf16> lpString),
int Function(Pointer<Utf16> lpString)>('RegisterWindowMessageW');
expect(RegisterWindowMessage, isA<Function>());
});
test('Can instantiate ReleaseDC', () {
final user32 = DynamicLibrary.open('user32.dll');
final ReleaseDC = user32.lookupFunction<
Int32 Function(IntPtr hWnd, IntPtr hDC),
int Function(int hWnd, int hDC)>('ReleaseDC');
expect(ReleaseDC, isA<Function>());
});
test('Can instantiate ScrollWindow', () {
final user32 = DynamicLibrary.open('user32.dll');
final ScrollWindow = user32.lookupFunction<
Int32 Function(IntPtr hWnd, Int32 XAmount, Int32 YAmount,
Pointer<RECT> lpRect, Pointer<RECT> lpClipRect),
int Function(int hWnd, int XAmount, int YAmount, Pointer<RECT> lpRect,
Pointer<RECT> lpClipRect)>('ScrollWindow');
expect(ScrollWindow, isA<Function>());
});
test('Can instantiate SendDlgItemMessage', () {
final user32 = DynamicLibrary.open('user32.dll');
final SendDlgItemMessage = user32.lookupFunction<
IntPtr Function(IntPtr hDlg, Int32 nIDDlgItem, Uint32 Msg,
IntPtr wParam, IntPtr lParam),
int Function(int hDlg, int nIDDlgItem, int Msg, int wParam,
int lParam)>('SendDlgItemMessageW');
expect(SendDlgItemMessage, isA<Function>());
});
test('Can instantiate SendInput', () {
final user32 = DynamicLibrary.open('user32.dll');
final SendInput = user32.lookupFunction<
Uint32 Function(Uint32 cInputs, Pointer<INPUT> pInputs, Int32 cbSize),
int Function(
int cInputs, Pointer<INPUT> pInputs, int cbSize)>('SendInput');
expect(SendInput, isA<Function>());
});
test('Can instantiate SendMessage', () {
final user32 = DynamicLibrary.open('user32.dll');
final SendMessage = user32.lookupFunction<
IntPtr Function(
IntPtr hWnd, Uint32 Msg, IntPtr wParam, IntPtr lParam),
int Function(
int hWnd, int Msg, int wParam, int lParam)>('SendMessageW');
expect(SendMessage, isA<Function>());
});
test('Can instantiate SetCursorPos', () {
final user32 = DynamicLibrary.open('user32.dll');
final SetCursorPos = user32.lookupFunction<
Int32 Function(Int32 X, Int32 Y),
int Function(int X, int Y)>('SetCursorPos');
expect(SetCursorPos, isA<Function>());
});
test('Can instantiate SetDlgItemInt', () {
final user32 = DynamicLibrary.open('user32.dll');
final SetDlgItemInt = user32.lookupFunction<
Int32 Function(
IntPtr hDlg, Int32 nIDDlgItem, Uint32 uValue, Int32 bSigned),
int Function(int hDlg, int nIDDlgItem, int uValue,
int bSigned)>('SetDlgItemInt');
expect(SetDlgItemInt, isA<Function>());
});
test('Can instantiate SetDlgItemText', () {
final user32 = DynamicLibrary.open('user32.dll');
final SetDlgItemText = user32.lookupFunction<
Int32 Function(
IntPtr hDlg, Int32 nIDDlgItem, Pointer<Utf16> lpString),
int Function(int hDlg, int nIDDlgItem,
Pointer<Utf16> lpString)>('SetDlgItemTextW');
expect(SetDlgItemText, isA<Function>());
});
test('Can instantiate SetFocus', () {
final user32 = DynamicLibrary.open('user32.dll');
final SetFocus = user32.lookupFunction<IntPtr Function(IntPtr hWnd),
int Function(int hWnd)>('SetFocus');
expect(SetFocus, isA<Function>());
});
test('Can instantiate SetMenuInfo', () {
final user32 = DynamicLibrary.open('user32.dll');
final SetMenuInfo = user32.lookupFunction<
Int32 Function(IntPtr hMenu, Pointer<MENUINFO> lpMenuInfo),
int Function(int hMenu, Pointer<MENUINFO> lpMenuInfo)>('SetMenuInfo');
expect(SetMenuInfo, isA<Function>());
});
test('Can instantiate SetMenuItemInfo', () {
final user32 = DynamicLibrary.open('user32.dll');
final SetMenuItemInfo = user32.lookupFunction<
Int32 Function(IntPtr hmenu, Uint32 item, Int32 fByPositon,
Pointer<MENUITEMINFO> lpmii),
int Function(int hmenu, int item, int fByPositon,
Pointer<MENUITEMINFO> lpmii)>('SetMenuItemInfoW');
expect(SetMenuItemInfo, isA<Function>());
});
test('Can instantiate SetParent', () {
final user32 = DynamicLibrary.open('user32.dll');
final SetParent = user32.lookupFunction<
IntPtr Function(IntPtr hWndChild, IntPtr hWndNewParent),
int Function(int hWndChild, int hWndNewParent)>('SetParent');
expect(SetParent, isA<Function>());
});
test('Can instantiate SetProcessDPIAware', () {
final user32 = DynamicLibrary.open('user32.dll');
final SetProcessDPIAware =
user32.lookupFunction<Int32 Function(), int Function()>(
'SetProcessDPIAware');
expect(SetProcessDPIAware, isA<Function>());
});
test('Can instantiate SetScrollInfo', () {
final user32 = DynamicLibrary.open('user32.dll');
final SetScrollInfo = user32.lookupFunction<
Int32 Function(
IntPtr hwnd, Int32 nBar, Pointer<SCROLLINFO> lpsi, Int32 redraw),
int Function(int hwnd, int nBar, Pointer<SCROLLINFO> lpsi,
int redraw)>('SetScrollInfo');
expect(SetScrollInfo, isA<Function>());
});
test('Can instantiate SetTimer', () {
final user32 = DynamicLibrary.open('user32.dll');
final SetTimer = user32.lookupFunction<
IntPtr Function(IntPtr hWnd, IntPtr nIDEvent, Uint32 uElapse,
Pointer<NativeFunction> lpTimerFunc),
int Function(int hWnd, int nIDEvent, int uElapse,
Pointer<NativeFunction> lpTimerFunc)>('SetTimer');
expect(SetTimer, isA<Function>());
});
test('Can instantiate SetWindowLongPtr', () {
final user32 = DynamicLibrary.open('user32.dll');
final SetWindowLongPtr = user32.lookupFunction<
IntPtr Function(IntPtr hWnd, Int32 nIndex, IntPtr dwNewLong),
int Function(
int hWnd, int nIndex, int dwNewLong)>('SetWindowLongPtrW');
expect(SetWindowLongPtr, isA<Function>());
});
test('Can instantiate SetWindowPos', () {
final user32 = DynamicLibrary.open('user32.dll');
final SetWindowPos = user32.lookupFunction<
Int32 Function(IntPtr hWnd, IntPtr hWndInsertAfter, Int32 X, Int32 Y,
Int32 cx, Int32 cy, Uint32 uFlags),
int Function(int hWnd, int hWndInsertAfter, int X, int Y, int cx,
int cy, int uFlags)>('SetWindowPos');
expect(SetWindowPos, isA<Function>());
});
test('Can instantiate SetWindowText', () {
final user32 = DynamicLibrary.open('user32.dll');
final SetWindowText = user32.lookupFunction<
Int32 Function(IntPtr hWnd, Pointer<Utf16> lpString),
int Function(int hWnd, Pointer<Utf16> lpString)>('SetWindowTextW');
expect(SetWindowText, isA<Function>());
});
test('Can instantiate ShowCursor', () {
final user32 = DynamicLibrary.open('user32.dll');
final ShowCursor = user32.lookupFunction<Int32 Function(Int32 bShow),
int Function(int bShow)>('ShowCursor');
expect(ShowCursor, isA<Function>());
});
test('Can instantiate ShowWindow', () {
final user32 = DynamicLibrary.open('user32.dll');
final ShowWindow = user32.lookupFunction<
Int32 Function(IntPtr hWnd, Int32 nCmdShow),
int Function(int hWnd, int nCmdShow)>('ShowWindow');
expect(ShowWindow, isA<Function>());
});
test('Can instantiate ShowWindowAsync', () {
final user32 = DynamicLibrary.open('user32.dll');
final ShowWindowAsync = user32.lookupFunction<
Int32 Function(IntPtr hWnd, Int32 nCmdShow),
int Function(int hWnd, int nCmdShow)>('ShowWindowAsync');
expect(ShowWindowAsync, isA<Function>());
});
test('Can instantiate SystemParametersInfo', () {
final user32 = DynamicLibrary.open('user32.dll');
final SystemParametersInfo = user32.lookupFunction<
Int32 Function(
Uint32 uiAction, Uint32 uiParam, Pointer pvParam, Uint32 fWinIni),
int Function(int uiAction, int uiParam, Pointer pvParam,
int fWinIni)>('SystemParametersInfoW');
expect(SystemParametersInfo, isA<Function>());
});
test('Can instantiate TranslateAccelerator', () {
final user32 = DynamicLibrary.open('user32.dll');
final TranslateAccelerator = user32.lookupFunction<
Int32 Function(IntPtr hWnd, IntPtr hAccTable, Pointer<MSG> lpMsg),
int Function(int hWnd, int hAccTable,
Pointer<MSG> lpMsg)>('TranslateAcceleratorW');
expect(TranslateAccelerator, isA<Function>());
});
test('Can instantiate TranslateMessage', () {
final user32 = DynamicLibrary.open('user32.dll');
final TranslateMessage = user32.lookupFunction<
Int32 Function(Pointer<MSG> lpMsg),
int Function(Pointer<MSG> lpMsg)>('TranslateMessage');
expect(TranslateMessage, isA<Function>());
});
test('Can instantiate UpdateWindow', () {
final user32 = DynamicLibrary.open('user32.dll');
final UpdateWindow = user32.lookupFunction<Int32 Function(IntPtr hWnd),
int Function(int hWnd)>('UpdateWindow');
expect(UpdateWindow, isA<Function>());
});
test('Can instantiate WindowFromPhysicalPoint', () {
final user32 = DynamicLibrary.open('user32.dll');
final WindowFromPhysicalPoint = user32.lookupFunction<
IntPtr Function(Int64 Point),
int Function(int Point)>('WindowFromPhysicalPoint');
expect(WindowFromPhysicalPoint, isA<Function>());
});
test('Can instantiate WindowFromPoint', () {
final user32 = DynamicLibrary.open('user32.dll');
final WindowFromPoint = user32.lookupFunction<
IntPtr Function(Int64 Point),
int Function(int Point)>('WindowFromPoint');
expect(WindowFromPoint, isA<Function>());
});
});
group('Test bthprops functions', () {
test('Can instantiate BluetoothAuthenticateDeviceEx', () {
final bthprops = DynamicLibrary.open('bthprops.cpl');
final BluetoothAuthenticateDeviceEx = bthprops.lookupFunction<
Uint32 Function(
IntPtr hwndParentIn,
IntPtr hRadioIn,
Pointer<BLUETOOTH_DEVICE_INFO> pbtdiInout,
IntPtr pbtOobData,
Int32 authenticationRequirement),
int Function(
int hwndParentIn,
int hRadioIn,
Pointer<BLUETOOTH_DEVICE_INFO> pbtdiInout,
int pbtOobData,
int authenticationRequirement)>('BluetoothAuthenticateDeviceEx');
expect(BluetoothAuthenticateDeviceEx, isA<Function>());
});
test('Can instantiate BluetoothFindDeviceClose', () {
final bthprops = DynamicLibrary.open('bthprops.cpl');
final BluetoothFindDeviceClose = bthprops.lookupFunction<
Int32 Function(IntPtr hFind),
int Function(int hFind)>('BluetoothFindDeviceClose');
expect(BluetoothFindDeviceClose, isA<Function>());
});
test('Can instantiate BluetoothFindFirstDevice', () {
final bthprops = DynamicLibrary.open('bthprops.cpl');
final BluetoothFindFirstDevice = bthprops.lookupFunction<
Int32 Function(Pointer<BLUETOOTH_DEVICE_SEARCH_PARAMS> pbtsp,
Pointer<BLUETOOTH_DEVICE_INFO> pbtdi),
int Function(Pointer<BLUETOOTH_DEVICE_SEARCH_PARAMS> pbtsp,
Pointer<BLUETOOTH_DEVICE_INFO> pbtdi)>(
'BluetoothFindFirstDevice');
expect(BluetoothFindFirstDevice, isA<Function>());
});
test('Can instantiate BluetoothFindFirstRadio', () {
final bthprops = DynamicLibrary.open('bthprops.cpl');
final BluetoothFindFirstRadio = bthprops.lookupFunction<
IntPtr Function(Pointer<BLUETOOTH_FIND_RADIO_PARAMS> pbtfrp,
Pointer<IntPtr> phRadio),
int Function(Pointer<BLUETOOTH_FIND_RADIO_PARAMS> pbtfrp,
Pointer<IntPtr> phRadio)>('BluetoothFindFirstRadio');
expect(BluetoothFindFirstRadio, isA<Function>());
});
test('Can instantiate BluetoothFindNextDevice', () {
final bthprops = DynamicLibrary.open('bthprops.cpl');
final BluetoothFindNextDevice = bthprops.lookupFunction<
Int32 Function(IntPtr hFind, Pointer<BLUETOOTH_DEVICE_INFO> pbtdi),
int Function(int hFind,
Pointer<BLUETOOTH_DEVICE_INFO> pbtdi)>('BluetoothFindNextDevice');
expect(BluetoothFindNextDevice, isA<Function>());
});
test('Can instantiate BluetoothFindNextRadio', () {
final bthprops = DynamicLibrary.open('bthprops.cpl');
final BluetoothFindNextRadio = bthprops.lookupFunction<
Int32 Function(IntPtr hFind, Pointer<IntPtr> phRadio),
int Function(
int hFind, Pointer<IntPtr> phRadio)>('BluetoothFindNextRadio');
expect(BluetoothFindNextRadio, isA<Function>());
});
test('Can instantiate BluetoothFindRadioClose', () {
final bthprops = DynamicLibrary.open('bthprops.cpl');
final BluetoothFindRadioClose = bthprops.lookupFunction<
Int32 Function(IntPtr hFind),
int Function(int hFind)>('BluetoothFindRadioClose');
expect(BluetoothFindRadioClose, isA<Function>());
});
test('Can instantiate BluetoothIsConnectable', () {
final bthprops = DynamicLibrary.open('bthprops.cpl');
final BluetoothIsConnectable = bthprops.lookupFunction<
Int32 Function(IntPtr hRadio),
int Function(int hRadio)>('BluetoothIsConnectable');
expect(BluetoothIsConnectable, isA<Function>());
});
test('Can instantiate BluetoothIsDiscoverable', () {
final bthprops = DynamicLibrary.open('bthprops.cpl');
final BluetoothIsDiscoverable = bthprops.lookupFunction<
Int32 Function(IntPtr hRadio),
int Function(int hRadio)>('BluetoothIsDiscoverable');
expect(BluetoothIsDiscoverable, isA<Function>());
});
test('Can instantiate BluetoothUpdateDeviceRecord', () {
final bthprops = DynamicLibrary.open('bthprops.cpl');
final BluetoothUpdateDeviceRecord = bthprops.lookupFunction<
Uint32 Function(Pointer<BLUETOOTH_DEVICE_INFO> pbtdi),
int Function(Pointer<BLUETOOTH_DEVICE_INFO> pbtdi)>(
'BluetoothUpdateDeviceRecord');
expect(BluetoothUpdateDeviceRecord, isA<Function>());
});
});
group('Test powrprof functions', () {
test('Can instantiate CallNtPowerInformation', () {
final powrprof = DynamicLibrary.open('powrprof.dll');
final CallNtPowerInformation = powrprof.lookupFunction<
Int32 Function(
Int32 InformationLevel,
Pointer InputBuffer,
Uint32 InputBufferLength,
Pointer OutputBuffer,
Uint32 OutputBufferLength),
int Function(
int InformationLevel,
Pointer InputBuffer,
int InputBufferLength,
Pointer OutputBuffer,
int OutputBufferLength)>('CallNtPowerInformation');
expect(CallNtPowerInformation, isA<Function>());
});
});
group('Test comdlg32 functions', () {
test('Can instantiate ChooseColor', () {
final comdlg32 = DynamicLibrary.open('comdlg32.dll');
final ChooseColor = comdlg32.lookupFunction<
Int32 Function(Pointer<CHOOSECOLOR> lpcc),
int Function(Pointer<CHOOSECOLOR> lpcc)>('ChooseColorW');
expect(ChooseColor, isA<Function>());
});
test('Can instantiate ChooseFont', () {
final comdlg32 = DynamicLibrary.open('comdlg32.dll');
final ChooseFont = comdlg32.lookupFunction<
Int32 Function(Pointer<CHOOSEFONT> lpcf),
int Function(Pointer<CHOOSEFONT> lpcf)>('ChooseFontW');
expect(ChooseFont, isA<Function>());
});
test('Can instantiate FindText', () {
final comdlg32 = DynamicLibrary.open('comdlg32.dll');
final FindText = comdlg32.lookupFunction<
IntPtr Function(Pointer<FINDREPLACE> Arg1),
int Function(Pointer<FINDREPLACE> Arg1)>('FindTextW');
expect(FindText, isA<Function>());
});
test('Can instantiate GetOpenFileName', () {
final comdlg32 = DynamicLibrary.open('comdlg32.dll');
final GetOpenFileName = comdlg32.lookupFunction<
Int32 Function(Pointer<OPENFILENAME> arg1),
int Function(Pointer<OPENFILENAME> arg1)>('GetOpenFileNameW');
expect(GetOpenFileName, isA<Function>());
});
test('Can instantiate GetSaveFileName', () {
final comdlg32 = DynamicLibrary.open('comdlg32.dll');
final GetSaveFileName = comdlg32.lookupFunction<
Int32 Function(Pointer<OPENFILENAME> arg1),
int Function(Pointer<OPENFILENAME> arg1)>('GetSaveFileNameW');
expect(GetSaveFileName, isA<Function>());
});
test('Can instantiate ReplaceText', () {
final comdlg32 = DynamicLibrary.open('comdlg32.dll');
final ReplaceText = comdlg32.lookupFunction<
IntPtr Function(Pointer<FINDREPLACE> Arg1),
int Function(Pointer<FINDREPLACE> Arg1)>('ReplaceTextW');
expect(ReplaceText, isA<Function>());
});
});
group('Test ole32 functions', () {
test('Can instantiate CLSIDFromString', () {
final ole32 = DynamicLibrary.open('ole32.dll');
final CLSIDFromString = ole32.lookupFunction<
Int32 Function(Pointer<Utf16> lpsz, Pointer<GUID> pclsid),
int Function(
Pointer<Utf16> lpsz, Pointer<GUID> pclsid)>('CLSIDFromString');
expect(CLSIDFromString, isA<Function>());
});
test('Can instantiate CoCreateGuid', () {
final ole32 = DynamicLibrary.open('ole32.dll');
final CoCreateGuid = ole32.lookupFunction<
Int32 Function(Pointer<GUID> pguid),
int Function(Pointer<GUID> pguid)>('CoCreateGuid');
expect(CoCreateGuid, isA<Function>());
});
test('Can instantiate CoCreateInstance', () {
final ole32 = DynamicLibrary.open('ole32.dll');
final CoCreateInstance = ole32.lookupFunction<
Int32 Function(Pointer<GUID> rclsid, Pointer<IntPtr> pUnkOuter,
Uint32 dwClsContext, Pointer<GUID> riid, Pointer<COMObject> ppv),
int Function(
Pointer<GUID> rclsid,
Pointer<IntPtr> pUnkOuter,
int dwClsContext,
Pointer<GUID> riid,
Pointer<COMObject> ppv)>('CoCreateInstance');
expect(CoCreateInstance, isA<Function>());
});
test('Can instantiate CoGetClassObject', () {
final ole32 = DynamicLibrary.open('ole32.dll');
final CoGetClassObject = ole32.lookupFunction<
Int32 Function(Pointer<GUID> rclsid, Uint32 dwClsContext,
Pointer pvReserved, Pointer<GUID> riid, Pointer<COMObject> ppv),
int Function(
Pointer<GUID> rclsid,
int dwClsContext,
Pointer pvReserved,
Pointer<GUID> riid,
Pointer<COMObject> ppv)>('CoGetClassObject');
expect(CoGetClassObject, isA<Function>());
});
test('Can instantiate CoInitializeEx', () {
final ole32 = DynamicLibrary.open('ole32.dll');
final CoInitializeEx = ole32.lookupFunction<
Int32 Function(Pointer<Void> pvReserved, Uint32 dwCoInit),
int Function(
Pointer<Void> pvReserved, int dwCoInit)>('CoInitializeEx');
expect(CoInitializeEx, isA<Function>());
});
test('Can instantiate CoInitializeSecurity', () {
final ole32 = DynamicLibrary.open('ole32.dll');
final CoInitializeSecurity = ole32.lookupFunction<
Int32 Function(
Pointer<SECURITY_DESCRIPTOR> pSecDesc,
Int32 cAuthSvc,
Pointer<SOLE_AUTHENTICATION_SERVICE> asAuthSvc,
Pointer<Void> pReserved1,
Uint32 dwAuthnLevel,
Uint32 dwImpLevel,
Pointer<Void> pAuthList,
Uint32 dwCapabilities,
Pointer<Void> pReserved3),
int Function(
Pointer<SECURITY_DESCRIPTOR> pSecDesc,
int cAuthSvc,
Pointer<SOLE_AUTHENTICATION_SERVICE> asAuthSvc,
Pointer<Void> pReserved1,
int dwAuthnLevel,
int dwImpLevel,
Pointer<Void> pAuthList,
int dwCapabilities,
Pointer<Void> pReserved3)>('CoInitializeSecurity');
expect(CoInitializeSecurity, isA<Function>());
});
test('Can instantiate CoSetProxyBlanket', () {
final ole32 = DynamicLibrary.open('ole32.dll');
final CoSetProxyBlanket = ole32.lookupFunction<
Int32 Function(
Pointer pProxy,
Uint32 dwAuthnSvc,
Uint32 dwAuthzSvc,
Pointer<Utf16> pServerPrincName,
Uint32 dwAuthnLevel,
Uint32 dwImpLevel,
Pointer<Void> pAuthInfo,
Uint32 dwCapabilities),
int Function(
Pointer pProxy,
int dwAuthnSvc,
int dwAuthzSvc,
Pointer<Utf16> pServerPrincName,
int dwAuthnLevel,
int dwImpLevel,
Pointer<Void> pAuthInfo,
int dwCapabilities)>('CoSetProxyBlanket');
expect(CoSetProxyBlanket, isA<Function>());
});
test('Can instantiate CoTaskMemFree', () {
final ole32 = DynamicLibrary.open('ole32.dll');
final CoTaskMemFree = ole32.lookupFunction<Void Function(Pointer pv),
void Function(Pointer pv)>('CoTaskMemFree');
expect(CoTaskMemFree, isA<Function>());
});
test('Can instantiate CoUninitialize', () {
final ole32 = DynamicLibrary.open('ole32.dll');
final CoUninitialize = ole32
.lookupFunction<Void Function(), void Function()>('CoUninitialize');
expect(CoUninitialize, isA<Function>());
});
test('Can instantiate IIDFromString', () {
final ole32 = DynamicLibrary.open('ole32.dll');
final IIDFromString = ole32.lookupFunction<
Int32 Function(Pointer<Utf16> lpsz, Pointer<GUID> lpiid),
int Function(
Pointer<Utf16> lpsz, Pointer<GUID> lpiid)>('IIDFromString');
expect(IIDFromString, isA<Function>());
});
});
group('Test gdi32 functions', () {
test('Can instantiate CreateFontIndirect', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final CreateFontIndirect = gdi32.lookupFunction<
IntPtr Function(Pointer<LOGFONT> lplf),
int Function(Pointer<LOGFONT> lplf)>('CreateFontIndirectW');
expect(CreateFontIndirect, isA<Function>());
});
test('Can instantiate CreatePen', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final CreatePen = gdi32.lookupFunction<
IntPtr Function(Int32 iStyle, Int32 cWidth, Int32 color),
int Function(int iStyle, int cWidth, int color)>('CreatePen');
expect(CreatePen, isA<Function>());
});
test('Can instantiate CreateSolidBrush', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final CreateSolidBrush = gdi32.lookupFunction<
IntPtr Function(Int32 color),
int Function(int color)>('CreateSolidBrush');
expect(CreateSolidBrush, isA<Function>());
});
test('Can instantiate DeleteObject', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final DeleteObject =
gdi32.lookupFunction<Int32 Function(IntPtr ho), int Function(int ho)>(
'DeleteObject');
expect(DeleteObject, isA<Function>());
});
test('Can instantiate EnumFontFamiliesEx', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final EnumFontFamiliesEx = gdi32.lookupFunction<
Int32 Function(IntPtr hdc, Pointer<LOGFONT> lpLogFont,
Pointer<NativeFunction> lpProc, IntPtr lParam, Uint32 dwFlags),
int Function(
int hdc,
Pointer<LOGFONT> lpLogFont,
Pointer<NativeFunction> lpProc,
int lParam,
int dwFlags)>('EnumFontFamiliesExW');
expect(EnumFontFamiliesEx, isA<Function>());
});
test('Can instantiate ExtCreatePen', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final ExtCreatePen = gdi32.lookupFunction<
IntPtr Function(Uint32 iPenStyle, Uint32 cWidth,
Pointer<LOGFONT> plBrush, Uint32 cStyle, Pointer<Uint32> pStyle),
int Function(int iPenStyle, int cWidth, Pointer<LOGFONT> plBrush,
int cStyle, Pointer<Uint32> pStyle)>('ExtCreatePen');
expect(ExtCreatePen, isA<Function>());
});
test('Can instantiate GetObject', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final GetObject = gdi32.lookupFunction<
Int32 Function(IntPtr h, Int32 c, Pointer pv),
int Function(int h, int c, Pointer pv)>('GetObjectW');
expect(GetObject, isA<Function>());
});
test('Can instantiate GetStockObject', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final GetStockObject =
gdi32.lookupFunction<IntPtr Function(Int32 i), int Function(int i)>(
'GetStockObject');
expect(GetStockObject, isA<Function>());
});
test('Can instantiate GetTextMetrics', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final GetTextMetrics = gdi32.lookupFunction<
Int32 Function(IntPtr hdc, Pointer<TEXTMETRIC> lptm),
int Function(int hdc, Pointer<TEXTMETRIC> lptm)>('GetTextMetricsW');
expect(GetTextMetrics, isA<Function>());
});
test('Can instantiate LineTo', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final LineTo = gdi32.lookupFunction<
Int32 Function(IntPtr hdc, Int32 x, Int32 y),
int Function(int hdc, int x, int y)>('LineTo');
expect(LineTo, isA<Function>());
});
test('Can instantiate MoveToEx', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final MoveToEx = gdi32.lookupFunction<
Int32 Function(IntPtr hdc, Int32 x, Int32 y, Pointer<POINT> lppt),
int Function(int hdc, int x, int y, Pointer<POINT> lppt)>('MoveToEx');
expect(MoveToEx, isA<Function>());
});
test('Can instantiate PolyBezier', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final PolyBezier = gdi32.lookupFunction<
Int32 Function(IntPtr hdc, Pointer<POINT> apt, Uint32 cpt),
int Function(int hdc, Pointer<POINT> apt, int cpt)>('PolyBezier');
expect(PolyBezier, isA<Function>());
});
test('Can instantiate Rectangle', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final Rectangle = gdi32.lookupFunction<
Int32 Function(
IntPtr hdc, Int32 left, Int32 top, Int32 right, Int32 bottom),
int Function(
int hdc, int left, int top, int right, int bottom)>('Rectangle');
expect(Rectangle, isA<Function>());
});
test('Can instantiate SaveDC', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final SaveDC = gdi32.lookupFunction<Int32 Function(IntPtr hdc),
int Function(int hdc)>('SaveDC');
expect(SaveDC, isA<Function>());
});
test('Can instantiate SelectObject', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final SelectObject = gdi32.lookupFunction<
IntPtr Function(IntPtr hdc, IntPtr h),
int Function(int hdc, int h)>('SelectObject');
expect(SelectObject, isA<Function>());
});
test('Can instantiate SetBkColor', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final SetBkColor = gdi32.lookupFunction<
Int32 Function(IntPtr hdc, Int32 color),
int Function(int hdc, int color)>('SetBkColor');
expect(SetBkColor, isA<Function>());
});
test('Can instantiate SetBkMode', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final SetBkMode = gdi32.lookupFunction<
Int32 Function(IntPtr hdc, Int32 mode),
int Function(int hdc, int mode)>('SetBkMode');
expect(SetBkMode, isA<Function>());
});
test('Can instantiate SetMapMode', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final SetMapMode = gdi32.lookupFunction<
Int32 Function(IntPtr hdc, Int32 iMode),
int Function(int hdc, int iMode)>('SetMapMode');
expect(SetMapMode, isA<Function>());
});
test('Can instantiate SetPixel', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final SetPixel = gdi32.lookupFunction<
Int32 Function(IntPtr hdc, Int32 x, Int32 y, Int32 color),
int Function(int hdc, int x, int y, int color)>('SetPixel');
expect(SetPixel, isA<Function>());
});
test('Can instantiate SetTextColor', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final SetTextColor = gdi32.lookupFunction<
Int32 Function(IntPtr hdc, Int32 color),
int Function(int hdc, int color)>('SetTextColor');
expect(SetTextColor, isA<Function>());
});
test('Can instantiate SetViewportExtEx', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final SetViewportExtEx = gdi32.lookupFunction<
Int32 Function(IntPtr hdc, Int32 x, Int32 y, Pointer<SIZE> lpsz),
int Function(
int hdc, int x, int y, Pointer<SIZE> lpsz)>('SetViewportExtEx');
expect(SetViewportExtEx, isA<Function>());
});
test('Can instantiate SetViewportOrgEx', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final SetViewportOrgEx = gdi32.lookupFunction<
Int32 Function(IntPtr hdc, Int32 x, Int32 y, Pointer<POINT> lppt),
int Function(
int hdc, int x, int y, Pointer<POINT> lppt)>('SetViewportOrgEx');
expect(SetViewportOrgEx, isA<Function>());
});
test('Can instantiate SetWindowExtEx', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final SetWindowExtEx = gdi32.lookupFunction<
Int32 Function(IntPtr hdc, Int32 x, Int32 y, Pointer<SIZE> lpsz),
int Function(
int hdc, int x, int y, Pointer<SIZE> lpsz)>('SetWindowExtEx');
expect(SetWindowExtEx, isA<Function>());
});
test('Can instantiate StretchDIBits', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final StretchDIBits = gdi32.lookupFunction<
Int32 Function(
IntPtr hdc,
Int32 xDest,
Int32 yDest,
Int32 DestWidth,
Int32 DestHeight,
Int32 xSrc,
Int32 ySrc,
Int32 SrcWidth,
Int32 SrcHeight,
Pointer<Void> lpBits,
Pointer<BITMAPINFO> lpbmi,
Uint32 iUsage,
Uint32 rop),
int Function(
int hdc,
int xDest,
int yDest,
int DestWidth,
int DestHeight,
int xSrc,
int ySrc,
int SrcWidth,
int SrcHeight,
Pointer<Void> lpBits,
Pointer<BITMAPINFO> lpbmi,
int iUsage,
int rop)>('StretchDIBits');
expect(StretchDIBits, isA<Function>());
});
test('Can instantiate TextOut', () {
final gdi32 = DynamicLibrary.open('gdi32.dll');
final TextOut = gdi32.lookupFunction<
Int32 Function(
IntPtr hdc, Int32 x, Int32 y, Pointer<Utf16> lpString, Int32 c),
int Function(int hdc, int x, int y, Pointer<Utf16> lpString,
int c)>('TextOutW');
expect(TextOut, isA<Function>());
});
});
group('Test advapi32 functions', () {
test('Can instantiate CredDelete', () {
final advapi32 = DynamicLibrary.open('advapi32.dll');
final CredDelete = advapi32.lookupFunction<
Int32 Function(Pointer<Utf16> TargetName, Uint32 Type, Uint32 Flags),
int Function(
Pointer<Utf16> TargetName, int Type, int Flags)>('CredDeleteW');
expect(CredDelete, isA<Function>());
});
test('Can instantiate CredFree', () {
final advapi32 = DynamicLibrary.open('advapi32.dll');
final CredFree = advapi32.lookupFunction<Void Function(Pointer Buffer),
void Function(Pointer Buffer)>('CredFree');
expect(CredFree, isA<Function>());
});
test('Can instantiate CredRead', () {
final advapi32 = DynamicLibrary.open('advapi32.dll');
final CredRead = advapi32.lookupFunction<
Int32 Function(Pointer<Utf16> TargetName, Uint32 Type, Uint32 Flags,
Pointer<Pointer<CREDENTIAL>> Credential),
int Function(Pointer<Utf16> TargetName, int Type, int Flags,
Pointer<Pointer<CREDENTIAL>> Credential)>('CredReadW');
expect(CredRead, isA<Function>());
});
test('Can instantiate CredWrite', () {
final advapi32 = DynamicLibrary.open('advapi32.dll');
final CredWrite = advapi32.lookupFunction<
Int32 Function(Pointer<CREDENTIAL> Credential, Uint32 Flags),
int Function(
Pointer<CREDENTIAL> Credential, int Flags)>('CredWriteW');
expect(CredWrite, isA<Function>());
});
test('Can instantiate RegCloseKey', () {
final advapi32 = DynamicLibrary.open('advapi32.dll');
final RegCloseKey = advapi32.lookupFunction<Int32 Function(IntPtr hKey),
int Function(int hKey)>('RegCloseKey');
expect(RegCloseKey, isA<Function>());
});
test('Can instantiate RegOpenKeyEx', () {
final advapi32 = DynamicLibrary.open('advapi32.dll');
final RegOpenKeyEx = advapi32.lookupFunction<
Int32 Function(IntPtr hKey, Pointer<Utf16> lpSubKey, Uint32 ulOptions,
Int32 samDesired, Pointer<IntPtr> phkResult),
int Function(int hKey, Pointer<Utf16> lpSubKey, int ulOptions,
int samDesired, Pointer<IntPtr> phkResult)>('RegOpenKeyExW');
expect(RegOpenKeyEx, isA<Function>());
});
test('Can instantiate RegQueryValueEx', () {
final advapi32 = DynamicLibrary.open('advapi32.dll');
final RegQueryValueEx = advapi32.lookupFunction<
Int32 Function(
IntPtr hKey,
Pointer<Utf16> lpValueName,
Pointer<Uint32> lpReserved,
Pointer<Uint32> lpType,
Pointer<Uint8> lpData,
Pointer<Uint32> lpcbData),
int Function(
int hKey,
Pointer<Utf16> lpValueName,
Pointer<Uint32> lpReserved,
Pointer<Uint32> lpType,
Pointer<Uint8> lpData,
Pointer<Uint32> lpcbData)>('RegQueryValueExW');
expect(RegQueryValueEx, isA<Function>());
});
});
group('Test dxva2 functions', () {
test('Can instantiate DestroyPhysicalMonitor', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final DestroyPhysicalMonitor = dxva2.lookupFunction<
Int32 Function(IntPtr hMonitor),
int Function(int hMonitor)>('DestroyPhysicalMonitor');
expect(DestroyPhysicalMonitor, isA<Function>());
});
test('Can instantiate DestroyPhysicalMonitors', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final DestroyPhysicalMonitors = dxva2.lookupFunction<
Int32 Function(
Uint32 dwPhysicalMonitorArraySize, Pointer pPhysicalMonitorArray),
int Function(int dwPhysicalMonitorArraySize,
Pointer pPhysicalMonitorArray)>('DestroyPhysicalMonitors');
expect(DestroyPhysicalMonitors, isA<Function>());
});
test('Can instantiate GetMonitorBrightness', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final GetMonitorBrightness = dxva2.lookupFunction<
Int32 Function(
IntPtr hMonitor,
Pointer<Uint32> pdwMinimumBrightness,
Pointer<Uint32> pdwCurrentBrightness,
Pointer<Uint32> pdwMaximumBrightness),
int Function(
int hMonitor,
Pointer<Uint32> pdwMinimumBrightness,
Pointer<Uint32> pdwCurrentBrightness,
Pointer<Uint32> pdwMaximumBrightness)>('GetMonitorBrightness');
expect(GetMonitorBrightness, isA<Function>());
});
test('Can instantiate GetMonitorCapabilities', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final GetMonitorCapabilities = dxva2.lookupFunction<
Int32 Function(
IntPtr hMonitor,
Pointer<Uint32> pdwMonitorCapabilities,
Pointer<Uint32> pdwSupportedColorTemperatures),
int Function(int hMonitor, Pointer<Uint32> pdwMonitorCapabilities,
Pointer<Uint32> pdwSupportedColorTemperatures)>(
'GetMonitorCapabilities');
expect(GetMonitorCapabilities, isA<Function>());
});
test('Can instantiate GetMonitorColorTemperature', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final GetMonitorColorTemperature = dxva2.lookupFunction<
Int32 Function(
IntPtr hMonitor, Pointer<Int32> pctCurrentColorTemperature),
int Function(
int hMonitor, Pointer<Int32> pctCurrentColorTemperature)>(
'GetMonitorColorTemperature');
expect(GetMonitorColorTemperature, isA<Function>());
});
test('Can instantiate GetMonitorContrast', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final GetMonitorContrast = dxva2.lookupFunction<
Int32 Function(
IntPtr hMonitor,
Pointer<Uint32> pdwMinimumContrast,
Pointer<Uint32> pdwCurrentContrast,
Pointer<Uint32> pdwMaximumContrast),
int Function(
int hMonitor,
Pointer<Uint32> pdwMinimumContrast,
Pointer<Uint32> pdwCurrentContrast,
Pointer<Uint32> pdwMaximumContrast)>('GetMonitorContrast');
expect(GetMonitorContrast, isA<Function>());
});
test('Can instantiate GetMonitorDisplayAreaPosition', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final GetMonitorDisplayAreaPosition = dxva2.lookupFunction<
Int32 Function(
IntPtr hMonitor,
Int32 ptPositionType,
Pointer<Uint32> pdwMinimumPosition,
Pointer<Uint32> pdwCurrentPosition,
Pointer<Uint32> pdwMaximumPosition),
int Function(
int hMonitor,
int ptPositionType,
Pointer<Uint32> pdwMinimumPosition,
Pointer<Uint32> pdwCurrentPosition,
Pointer<Uint32> pdwMaximumPosition)>(
'GetMonitorDisplayAreaPosition');
expect(GetMonitorDisplayAreaPosition, isA<Function>());
});
test('Can instantiate GetMonitorDisplayAreaSize', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final GetMonitorDisplayAreaSize = dxva2.lookupFunction<
Int32 Function(
IntPtr hMonitor,
Int32 stSizeType,
Pointer<Uint32> pdwMinimumWidthOrHeight,
Pointer<Uint32> pdwCurrentWidthOrHeight,
Pointer<Uint32> pdwMaximumWidthOrHeight),
int Function(
int hMonitor,
int stSizeType,
Pointer<Uint32> pdwMinimumWidthOrHeight,
Pointer<Uint32> pdwCurrentWidthOrHeight,
Pointer<Uint32> pdwMaximumWidthOrHeight)>(
'GetMonitorDisplayAreaSize');
expect(GetMonitorDisplayAreaSize, isA<Function>());
});
test('Can instantiate GetMonitorRedGreenOrBlueDrive', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final GetMonitorRedGreenOrBlueDrive = dxva2.lookupFunction<
Int32 Function(
IntPtr hMonitor,
Int32 dtDriveType,
Pointer<Uint32> pdwMinimumDrive,
Pointer<Uint32> pdwCurrentDrive,
Pointer<Uint32> pdwMaximumDrive),
int Function(
int hMonitor,
int dtDriveType,
Pointer<Uint32> pdwMinimumDrive,
Pointer<Uint32> pdwCurrentDrive,
Pointer<Uint32> pdwMaximumDrive)>(
'GetMonitorRedGreenOrBlueDrive');
expect(GetMonitorRedGreenOrBlueDrive, isA<Function>());
});
test('Can instantiate GetMonitorRedGreenOrBlueGain', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final GetMonitorRedGreenOrBlueGain = dxva2.lookupFunction<
Int32 Function(
IntPtr hMonitor,
Int32 gtGainType,
Pointer<Uint32> pdwMinimumGain,
Pointer<Uint32> pdwCurrentGain,
Pointer<Uint32> pdwMaximumGain),
int Function(
int hMonitor,
int gtGainType,
Pointer<Uint32> pdwMinimumGain,
Pointer<Uint32> pdwCurrentGain,
Pointer<Uint32> pdwMaximumGain)>('GetMonitorRedGreenOrBlueGain');
expect(GetMonitorRedGreenOrBlueGain, isA<Function>());
});
test('Can instantiate GetMonitorTechnologyType', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final GetMonitorTechnologyType = dxva2.lookupFunction<
Int32 Function(
IntPtr hMonitor, Pointer<Int32> pdtyDisplayTechnologyType),
int Function(
int hMonitor, Pointer<Int32> pdtyDisplayTechnologyType)>(
'GetMonitorTechnologyType');
expect(GetMonitorTechnologyType, isA<Function>());
});
test('Can instantiate GetNumberOfPhysicalMonitorsFromHMONITOR', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final GetNumberOfPhysicalMonitorsFromHMONITOR = dxva2.lookupFunction<
Int32 Function(
IntPtr hMonitor, Pointer<Uint32> pdwNumberOfPhysicalMonitors),
int Function(
int hMonitor, Pointer<Uint32> pdwNumberOfPhysicalMonitors)>(
'GetNumberOfPhysicalMonitorsFromHMONITOR');
expect(GetNumberOfPhysicalMonitorsFromHMONITOR, isA<Function>());
});
test('Can instantiate GetPhysicalMonitorsFromHMONITOR', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final GetPhysicalMonitorsFromHMONITOR = dxva2.lookupFunction<
Int32 Function(IntPtr hMonitor, Uint32 dwPhysicalMonitorArraySize,
Pointer pPhysicalMonitorArray),
int Function(int hMonitor, int dwPhysicalMonitorArraySize,
Pointer pPhysicalMonitorArray)>(
'GetPhysicalMonitorsFromHMONITOR');
expect(GetPhysicalMonitorsFromHMONITOR, isA<Function>());
});
test('Can instantiate SaveCurrentMonitorSettings', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final SaveCurrentMonitorSettings = dxva2.lookupFunction<
Int32 Function(IntPtr hMonitor),
int Function(int hMonitor)>('SaveCurrentMonitorSettings');
expect(SaveCurrentMonitorSettings, isA<Function>());
});
test('Can instantiate SetMonitorBrightness', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final SetMonitorBrightness = dxva2.lookupFunction<
Int32 Function(IntPtr hMonitor, Uint32 dwNewBrightness),
int Function(
int hMonitor, int dwNewBrightness)>('SetMonitorBrightness');
expect(SetMonitorBrightness, isA<Function>());
});
test('Can instantiate SetMonitorColorTemperature', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final SetMonitorColorTemperature = dxva2.lookupFunction<
Int32 Function(IntPtr hMonitor, Int32 ctCurrentColorTemperature),
int Function(int hMonitor,
int ctCurrentColorTemperature)>('SetMonitorColorTemperature');
expect(SetMonitorColorTemperature, isA<Function>());
});
test('Can instantiate SetMonitorContrast', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final SetMonitorContrast = dxva2.lookupFunction<
Int32 Function(IntPtr hMonitor, Uint32 dwNewContrast),
int Function(int hMonitor, int dwNewContrast)>('SetMonitorContrast');
expect(SetMonitorContrast, isA<Function>());
});
test('Can instantiate SetMonitorDisplayAreaPosition', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final SetMonitorDisplayAreaPosition = dxva2.lookupFunction<
Int32 Function(
IntPtr hMonitor, Int32 ptPositionType, Uint32 dwNewPosition),
int Function(int hMonitor, int ptPositionType,
int dwNewPosition)>('SetMonitorDisplayAreaPosition');
expect(SetMonitorDisplayAreaPosition, isA<Function>());
});
test('Can instantiate SetMonitorDisplayAreaSize', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final SetMonitorDisplayAreaSize = dxva2.lookupFunction<
Int32 Function(IntPtr hMonitor, Int32 stSizeType,
Uint32 dwNewDisplayAreaWidthOrHeight),
int Function(int hMonitor, int stSizeType,
int dwNewDisplayAreaWidthOrHeight)>('SetMonitorDisplayAreaSize');
expect(SetMonitorDisplayAreaSize, isA<Function>());
});
test('Can instantiate SetMonitorRedGreenOrBlueDrive', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final SetMonitorRedGreenOrBlueDrive = dxva2.lookupFunction<
Int32 Function(IntPtr hMonitor, Int32 dtDriveType, Uint32 dwNewDrive),
int Function(int hMonitor, int dtDriveType,
int dwNewDrive)>('SetMonitorRedGreenOrBlueDrive');
expect(SetMonitorRedGreenOrBlueDrive, isA<Function>());
});
test('Can instantiate SetMonitorRedGreenOrBlueGain', () {
final dxva2 = DynamicLibrary.open('dxva2.dll');
final SetMonitorRedGreenOrBlueGain = dxva2.lookupFunction<
Int32 Function(IntPtr hMonitor, Int32 gtGainType, Uint32 dwNewGain),
int Function(int hMonitor, int gtGainType,
int dwNewGain)>('SetMonitorRedGreenOrBlueGain');
expect(SetMonitorRedGreenOrBlueGain, isA<Function>());
});
});
group('Test comctl32 functions', () {
test('Can instantiate DrawStatusText', () {
final comctl32 = DynamicLibrary.open('comctl32.dll');
final DrawStatusText = comctl32.lookupFunction<
Void Function(IntPtr hdc, Pointer<RECT> lprc, Pointer<Utf16> pszText,
Uint32 uFlags),
void Function(int hdc, Pointer<RECT> lprc, Pointer<Utf16> pszText,
int uFlags)>('DrawStatusTextW');
expect(DrawStatusText, isA<Function>());
});
test('Can instantiate InitCommonControlsEx', () {
final comctl32 = DynamicLibrary.open('comctl32.dll');
final InitCommonControlsEx = comctl32.lookupFunction<
Int32 Function(Pointer<INITCOMMONCONTROLSEX> picce),
int Function(
Pointer<INITCOMMONCONTROLSEX> picce)>('InitCommonControlsEx');
expect(InitCommonControlsEx, isA<Function>());
});
});
group('Test psapi functions', () {
test('Can instantiate EnumProcesses', () {
final psapi = DynamicLibrary.open('psapi.dll');
final EnumProcesses = psapi.lookupFunction<
Int32 Function(Pointer<Uint32> lpidProcess, Uint32 cb,
Pointer<Uint32> lpcbNeeded),
int Function(Pointer<Uint32> lpidProcess, int cb,
Pointer<Uint32> lpcbNeeded)>('EnumProcesses');
expect(EnumProcesses, isA<Function>());
});
test('Can instantiate EnumProcessModules', () {
final psapi = DynamicLibrary.open('psapi.dll');
final EnumProcessModules = psapi.lookupFunction<
Int32 Function(IntPtr hProcess, Pointer<IntPtr> lphModule, Uint32 cb,
Pointer<Uint32> lpcbNeeded),
int Function(int hProcess, Pointer<IntPtr> lphModule, int cb,
Pointer<Uint32> lpcbNeeded)>('EnumProcessModules');
expect(EnumProcessModules, isA<Function>());
});
test('Can instantiate EnumProcessModulesEx', () {
final psapi = DynamicLibrary.open('psapi.dll');
final EnumProcessModulesEx = psapi.lookupFunction<
Int32 Function(IntPtr hProcess, Pointer<IntPtr> lphModule, Uint32 cb,
Pointer<Uint32> lpcbNeeded, Uint32 dwFilterFlag),
int Function(
int hProcess,
Pointer<IntPtr> lphModule,
int cb,
Pointer<Uint32> lpcbNeeded,
int dwFilterFlag)>('EnumProcessModulesEx');
expect(EnumProcessModulesEx, isA<Function>());
});
test('Can instantiate GetModuleBaseName', () {
final psapi = DynamicLibrary.open('psapi.dll');
final GetModuleBaseName = psapi.lookupFunction<
Uint32 Function(IntPtr hProcess, IntPtr hModule,
Pointer<Utf16> lpBaseName, Uint32 nSize),
int Function(int hProcess, int hModule, Pointer<Utf16> lpBaseName,
int nSize)>('GetModuleBaseNameW');
expect(GetModuleBaseName, isA<Function>());
});
test('Can instantiate GetModuleFileNameEx', () {
final psapi = DynamicLibrary.open('psapi.dll');
final GetModuleFileNameEx = psapi.lookupFunction<
Uint32 Function(IntPtr hProcess, IntPtr hModule,
Pointer<Utf16> lpFilename, Uint32 nSize),
int Function(int hProcess, int hModule, Pointer<Utf16> lpFilename,
int nSize)>('GetModuleFileNameExW');
expect(GetModuleFileNameEx, isA<Function>());
});
});
group('Test shell32 functions', () {
test('Can instantiate FindExecutable', () {
final shell32 = DynamicLibrary.open('shell32.dll');
final FindExecutable = shell32.lookupFunction<
IntPtr Function(Pointer<Utf16> lpFile, Pointer<Utf16> lpDirectory,
Pointer<Utf16> lpResult),
int Function(Pointer<Utf16> lpFile, Pointer<Utf16> lpDirectory,
Pointer<Utf16> lpResult)>('FindExecutableW');
expect(FindExecutable, isA<Function>());
});
test('Can instantiate ShellAbout', () {
final shell32 = DynamicLibrary.open('shell32.dll');
final ShellAbout = shell32.lookupFunction<
Int32 Function(IntPtr hWnd, Pointer<Utf16> szApp,
Pointer<Utf16> szOtherStuff, IntPtr hIcon),
int Function(int hWnd, Pointer<Utf16> szApp,
Pointer<Utf16> szOtherStuff, int hIcon)>('ShellAboutW');
expect(ShellAbout, isA<Function>());
});
test('Can instantiate ShellExecuteEx', () {
final shell32 = DynamicLibrary.open('shell32.dll');
final ShellExecuteEx = shell32.lookupFunction<
Int32 Function(Pointer<SHELLEXECUTEINFO> pExecuteInfo),
int Function(
Pointer<SHELLEXECUTEINFO> pExecuteInfo)>('ShellExecuteExW');
expect(ShellExecuteEx, isA<Function>());
});
test('Can instantiate ShellExecute', () {
final shell32 = DynamicLibrary.open('shell32.dll');
final ShellExecute = shell32.lookupFunction<
IntPtr Function(
IntPtr hwnd,
Pointer<Utf16> lpOperation,
Pointer<Utf16> lpFile,
Pointer<Utf16> lpParameters,
Pointer<Utf16> lpDirectory,
Int32 nShowCmd),
int Function(
int hwnd,
Pointer<Utf16> lpOperation,
Pointer<Utf16> lpFile,
Pointer<Utf16> lpParameters,
Pointer<Utf16> lpDirectory,
int nShowCmd)>('ShellExecuteW');
expect(ShellExecute, isA<Function>());
});
test('Can instantiate SHCreateItemFromParsingName', () {
final shell32 = DynamicLibrary.open('shell32.dll');
final SHCreateItemFromParsingName = shell32.lookupFunction<
Int32 Function(Pointer<Utf16> pszPath, Pointer pbc,
Pointer<GUID> riid, Pointer<COMObject> ppv),
int Function(Pointer<Utf16> pszPath, Pointer pbc, Pointer<GUID> riid,
Pointer<COMObject> ppv)>('SHCreateItemFromParsingName');
expect(SHCreateItemFromParsingName, isA<Function>());
});
test('Can instantiate SHEmptyRecycleBin', () {
final shell32 = DynamicLibrary.open('shell32.dll');
final SHEmptyRecycleBin = shell32.lookupFunction<
Int32 Function(
IntPtr hwnd, Pointer<Utf16> pszRootPath, Uint32 dwFlags),
int Function(int hwnd, Pointer<Utf16> pszRootPath,
int dwFlags)>('SHEmptyRecycleBinW');
expect(SHEmptyRecycleBin, isA<Function>());
});
test('Can instantiate SHGetDiskFreeSpaceEx', () {
final shell32 = DynamicLibrary.open('shell32.dll');
final SHGetDiskFreeSpaceEx = shell32.lookupFunction<
Int32 Function(
Pointer<Utf16> pszDirectoryName,
Pointer<Uint64> pulFreeBytesAvailableToCaller,
Pointer<Uint64> pulTotalNumberOfBytes,
Pointer<Uint64> pulTotalNumberOfFreeBytes),
int Function(
Pointer<Utf16> pszDirectoryName,
Pointer<Uint64> pulFreeBytesAvailableToCaller,
Pointer<Uint64> pulTotalNumberOfBytes,
Pointer<Uint64> pulTotalNumberOfFreeBytes)>(
'SHGetDiskFreeSpaceExW');
expect(SHGetDiskFreeSpaceEx, isA<Function>());
});
test('Can instantiate SHGetDriveMedia', () {
final shell32 = DynamicLibrary.open('shell32.dll');
final SHGetDriveMedia = shell32.lookupFunction<
Int32 Function(
Pointer<Utf16> pszDrive, Pointer<Uint32> pdwMediaContent),
int Function(Pointer<Utf16> pszDrive,
Pointer<Uint32> pdwMediaContent)>('SHGetDriveMedia');
expect(SHGetDriveMedia, isA<Function>());
});
test('Can instantiate SHGetFolderPath', () {
final shell32 = DynamicLibrary.open('shell32.dll');
final SHGetFolderPath = shell32.lookupFunction<
Int32 Function(IntPtr hwnd, Int32 csidl, IntPtr hToken,
Uint32 dwFlags, Pointer<Utf16> pszPath),
int Function(int hwnd, int csidl, int hToken, int dwFlags,
Pointer<Utf16> pszPath)>('SHGetFolderPathW');
expect(SHGetFolderPath, isA<Function>());
});
test('Can instantiate SHGetKnownFolderPath', () {
final shell32 = DynamicLibrary.open('shell32.dll');
final SHGetKnownFolderPath = shell32.lookupFunction<
Int32 Function(Pointer<GUID> rfid, Uint32 dwFlags, IntPtr hToken,
Pointer<IntPtr> ppszPath),
int Function(Pointer<GUID> rfid, int dwFlags, int hToken,
Pointer<IntPtr> ppszPath)>('SHGetKnownFolderPath');
expect(SHGetKnownFolderPath, isA<Function>());
});
test('Can instantiate SHQueryRecycleBin', () {
final shell32 = DynamicLibrary.open('shell32.dll');
final SHQueryRecycleBin = shell32.lookupFunction<
Int32 Function(Pointer<Utf16> pszRootPath,
Pointer<SHQUERYRBINFO> pSHQueryRBInfo),
int Function(Pointer<Utf16> pszRootPath,
Pointer<SHQUERYRBINFO> pSHQueryRBInfo)>('SHQueryRecycleBinW');
expect(SHQueryRecycleBin, isA<Function>());
});
});
group('Test shcore functions', () {
test('Can instantiate GetDpiForMonitor', () {
final shcore = DynamicLibrary.open('shcore.dll');
final GetDpiForMonitor = shcore.lookupFunction<
IntPtr Function(IntPtr hMonitor, Int32 dpiType, Pointer<Int32> dpiX,
Pointer<Int32> dpiY),
int Function(int hMonitor, int dpiType, Pointer<Int32> dpiX,
Pointer<Int32> dpiY)>('GetDpiForMonitor');
expect(GetDpiForMonitor, isA<Function>());
});
test('Can instantiate GetProcessDpiAwareness', () {
final shcore = DynamicLibrary.open('shcore.dll');
final GetProcessDpiAwareness = shcore.lookupFunction<
IntPtr Function(IntPtr hprocess, Pointer<Int32> value),
int Function(
int hprocess, Pointer<Int32> value)>('GetProcessDpiAwareness');
expect(GetProcessDpiAwareness, isA<Function>());
});
test('Can instantiate SetProcessDpiAwareness', () {
final shcore = DynamicLibrary.open('shcore.dll');
final SetProcessDpiAwareness = shcore.lookupFunction<
IntPtr Function(Int32 value),
int Function(int value)>('SetProcessDpiAwareness');
expect(SetProcessDpiAwareness, isA<Function>());
});
});
group('Test version functions', () {
test('Can instantiate GetFileVersionInfoEx', () {
final version = DynamicLibrary.open('version.dll');
final GetFileVersionInfoEx = version.lookupFunction<
Int32 Function(Uint32 dwFlags, Pointer<Utf16> lpwstrFilename,
Uint32 dwHandle, Uint32 dwLen, Pointer lpData),
int Function(int dwFlags, Pointer<Utf16> lpwstrFilename, int dwHandle,
int dwLen, Pointer lpData)>('GetFileVersionInfoExW');
expect(GetFileVersionInfoEx, isA<Function>());
});
test('Can instantiate GetFileVersionInfoSizeEx', () {
final version = DynamicLibrary.open('version.dll');
final GetFileVersionInfoSizeEx = version.lookupFunction<
Uint32 Function(Uint32 dwFlags, Pointer<Utf16> lpwstrFilename,
Pointer<Uint32> lpdwHandle),
int Function(int dwFlags, Pointer<Utf16> lpwstrFilename,
Pointer<Uint32> lpdwHandle)>('GetFileVersionInfoSizeExW');
expect(GetFileVersionInfoSizeEx, isA<Function>());
});
test('Can instantiate GetFileVersionInfoSize', () {
final version = DynamicLibrary.open('version.dll');
final GetFileVersionInfoSize = version.lookupFunction<
Uint32 Function(
Pointer<Utf16> lptstrFilename, Pointer<Uint32> lpdwHandle),
int Function(Pointer<Utf16> lptstrFilename,
Pointer<Uint32> lpdwHandle)>('GetFileVersionInfoSizeW');
expect(GetFileVersionInfoSize, isA<Function>());
});
test('Can instantiate GetFileVersionInfo', () {
final version = DynamicLibrary.open('version.dll');
final GetFileVersionInfo = version.lookupFunction<
Int32 Function(Pointer<Utf16> lptstrFilename, Uint32 dwHandle,
Uint32 dwLen, Pointer lpData),
int Function(Pointer<Utf16> lptstrFilename, int dwHandle, int dwLen,
Pointer lpData)>('GetFileVersionInfoW');
expect(GetFileVersionInfo, isA<Function>());
});
test('Can instantiate VerFindFile', () {
final version = DynamicLibrary.open('version.dll');
final VerFindFile = version.lookupFunction<
Uint32 Function(
Uint32 uFlags,
Pointer<Utf16> szFilename,
Pointer<Utf16> szWinDir,
Pointer<Utf16> szAppDir,
Pointer<Utf16> szCurDir,
Pointer<Uint32> puCurDirLen,
Pointer<Utf16> szDestDir,
Pointer<Uint32> puDestDirLen),
int Function(
int uFlags,
Pointer<Utf16> szFilename,
Pointer<Utf16> szWinDir,
Pointer<Utf16> szAppDir,
Pointer<Utf16> szCurDir,
Pointer<Uint32> puCurDirLen,
Pointer<Utf16> szDestDir,
Pointer<Uint32> puDestDirLen)>('VerFindFileW');
expect(VerFindFile, isA<Function>());
});
test('Can instantiate VerInstallFile', () {
final version = DynamicLibrary.open('version.dll');
final VerInstallFile = version.lookupFunction<
Uint32 Function(
Uint32 dwFlags,
Pointer<Utf16> szSrcFileName,
Pointer<Utf16> szDestFileName,
Pointer<Utf16> szSrcDir,
Pointer<Utf16> szDestDir,
Pointer<Utf16> szCurDir,
Pointer<Utf16> szTmpFile,
Pointer<Uint32> puTmpFileLen),
int Function(
int dwFlags,
Pointer<Utf16> szSrcFileName,
Pointer<Utf16> szDestFileName,
Pointer<Utf16> szSrcDir,
Pointer<Utf16> szDestDir,
Pointer<Utf16> szCurDir,
Pointer<Utf16> szTmpFile,
Pointer<Uint32> puTmpFileLen)>('VerInstallFileW');
expect(VerInstallFile, isA<Function>());
});
test('Can instantiate VerLanguageName', () {
final version = DynamicLibrary.open('version.dll');
final VerLanguageName = version.lookupFunction<
Uint32 Function(Uint32 wLang, Pointer<Utf16> szLang, Uint32 cchLang),
int Function(int wLang, Pointer<Utf16> szLang,
int cchLang)>('VerLanguageNameW');
expect(VerLanguageName, isA<Function>());
});
test('Can instantiate VerQueryValue', () {
final version = DynamicLibrary.open('version.dll');
final VerQueryValue = version.lookupFunction<
Int32 Function(Pointer pBlock, Pointer<Utf16> lpSubBlock,
Pointer<IntPtr> lplpBuffer, Pointer<Uint32> puLen),
int Function(
Pointer pBlock,
Pointer<Utf16> lpSubBlock,
Pointer<IntPtr> lplpBuffer,
Pointer<Uint32> puLen)>('VerQueryValueW');
expect(VerQueryValue, isA<Function>());
});
});
group('Test winmm functions', () {
test('Can instantiate mciGetDeviceID', () {
final winmm = DynamicLibrary.open('winmm.dll');
final mciGetDeviceID = winmm.lookupFunction<
Uint32 Function(Pointer<Utf16> lpszDevice),
int Function(Pointer<Utf16> lpszDevice)>('mciGetDeviceIDW');
expect(mciGetDeviceID, isA<Function>());
});
test('Can instantiate mciGetDeviceIDFromElementID', () {
final winmm = DynamicLibrary.open('winmm.dll');
final mciGetDeviceIDFromElementID = winmm.lookupFunction<
Uint32 Function(Uint32 dwElementID, Pointer<Utf16> lpstrType),
int Function(int dwElementID,
Pointer<Utf16> lpstrType)>('mciGetDeviceIDFromElementIDW');
expect(mciGetDeviceIDFromElementID, isA<Function>());
});
test('Can instantiate mciGetErrorString', () {
final winmm = DynamicLibrary.open('winmm.dll');
final mciGetErrorString = winmm.lookupFunction<
Int32 Function(Uint32 fdwError, Pointer<Utf16> lpszErrorText,
Uint32 cchErrorText),
int Function(int fdwError, Pointer<Utf16> lpszErrorText,
int cchErrorText)>('mciGetErrorStringW');
expect(mciGetErrorString, isA<Function>());
});
test('Can instantiate mciSendCommand', () {
final winmm = DynamicLibrary.open('winmm.dll');
final mciSendCommand = winmm.lookupFunction<
Uint32 Function(
Uint32 IDDevice, Uint32 uMsg, IntPtr fdwCommand, IntPtr dwParam),
int Function(int IDDevice, int uMsg, int fdwCommand,
int dwParam)>('mciSendCommandW');
expect(mciSendCommand, isA<Function>());
});
test('Can instantiate mciSendString', () {
final winmm = DynamicLibrary.open('winmm.dll');
final mciSendString = winmm.lookupFunction<
Uint32 Function(
Pointer<Utf16> lpszCommand,
Pointer<Utf16> lpszReturnString,
Uint32 cchReturn,
IntPtr hwndCallback),
int Function(
Pointer<Utf16> lpszCommand,
Pointer<Utf16> lpszReturnString,
int cchReturn,
int hwndCallback)>('mciSendStringW');
expect(mciSendString, isA<Function>());
});
test('Can instantiate midiOutGetNumDevs', () {
final winmm = DynamicLibrary.open('winmm.dll');
final midiOutGetNumDevs =
winmm.lookupFunction<Uint32 Function(), int Function()>(
'midiOutGetNumDevs');
expect(midiOutGetNumDevs, isA<Function>());
});
test('Can instantiate PlaySound', () {
final winmm = DynamicLibrary.open('winmm.dll');
final PlaySound = winmm.lookupFunction<
Int32 Function(Pointer<Utf16> pszSound, IntPtr hmod, Uint32 fdwSound),
int Function(
Pointer<Utf16> pszSound, int hmod, int fdwSound)>('PlaySoundW');
expect(PlaySound, isA<Function>());
});
});
group('Test ntdll functions', () {
test('Can instantiate NtResumeProcess', () {
final ntdll = DynamicLibrary.open('ntdll.dll');
final NtResumeProcess = ntdll.lookupFunction<Void Function(IntPtr hWnd),
void Function(int hWnd)>('NtResumeProcess');
expect(NtResumeProcess, isA<Function>());
});
test('Can instantiate NtSuspendProcess', () {
final ntdll = DynamicLibrary.open('ntdll.dll');
final NtSuspendProcess = ntdll.lookupFunction<Void Function(IntPtr hWnd),
void Function(int hWnd)>('NtSuspendProcess');
expect(NtSuspendProcess, isA<Function>());
});
});
group('Test oleaut32 functions', () {
test('Can instantiate SysAllocString', () {
final oleaut32 = DynamicLibrary.open('oleaut32.dll');
final SysAllocString = oleaut32.lookupFunction<
Pointer Function(Pointer<Utf16> psz),
Pointer Function(Pointer<Utf16> psz)>('SysAllocString');
expect(SysAllocString, isA<Function>());
});
test('Can instantiate SysFreeString', () {
final oleaut32 = DynamicLibrary.open('oleaut32.dll');
final SysFreeString = oleaut32.lookupFunction<
Void Function(Pointer bstrString),
void Function(Pointer bstrString)>('SysFreeString');
expect(SysFreeString, isA<Function>());
});
test('Can instantiate SysStringByteLen', () {
final oleaut32 = DynamicLibrary.open('oleaut32.dll');
final SysStringByteLen = oleaut32.lookupFunction<
Uint32 Function(Pointer bstr),
int Function(Pointer bstr)>('SysStringByteLen');
expect(SysStringByteLen, isA<Function>());
});
test('Can instantiate SysStringLen', () {
final oleaut32 = DynamicLibrary.open('oleaut32.dll');
final SysStringLen = oleaut32.lookupFunction<
Uint32 Function(Pointer pbstr),
int Function(Pointer pbstr)>('SysStringLen');
expect(SysStringLen, isA<Function>());
});
test('Can instantiate VariantClear', () {
final oleaut32 = DynamicLibrary.open('oleaut32.dll');
final VariantClear = oleaut32.lookupFunction<
Int32 Function(Pointer pvarg),
int Function(Pointer pvarg)>('VariantClear');
expect(VariantClear, isA<Function>());
});
test('Can instantiate VariantInit', () {
final oleaut32 = DynamicLibrary.open('oleaut32.dll');
final VariantInit = oleaut32.lookupFunction<Void Function(Pointer pvarg),
void Function(Pointer pvarg)>('VariantInit');
expect(VariantInit, isA<Function>());
});
});
}
|
'use strict';
var Constants = require('Constants');
var Object3DUtil = require('geo/Object3DUtil');
var Picker = require('controls/Picker');
var _ = require('util/util');
/**
* Utility functions for identifying attachments
* @module Attachments
*/
var Attachments = {};
/**
* Attachment information
* @typedef Attachment
* @type {object}
* @property {THREE.Object3D} child
* @property {model.ModelInstance} childInst
* @property {THREE.Object3D} parent
* @property {model.ModelInstance} parentInst
* @property {THREE.Vector3} parentSurfaceNorm
* @property {int} childWorldBBFaceIndex
* @property {geo.Intersect} parentAttachment
* @property {model.AttachmentPoint} childAttachment
*/
/**
* Wrapper object containing a model instance with attachment points
* @typedef ModelInstanceWithAttachmentPoints
* @type {object}
* @property {ModelInstance} modelInstance
* @property {model.AttachmentPoint[]} attachments
*/
/**
* Identify and score attachments
* @param parents
* @param modelInstWithCandidates
* @param opts {object} Additional options
* @param [opts.includeCandidates] {boolean} Whether all candidates should be returned or just the best
* @param [opts.maxCandidates] {int} Maximum number of candidates to track
* @param [opts.maxCandidatesToCheck] {int} Max candidates to check per attachment
* @param [opts.deltaContactDistThreshold] {number}
* @param [opts.contactDistThreshold] {number}
* @param [opts.sameModelCost] {number}
* @param [opts.disallowSameModelHorizontalAttachment] {boolean}
* @param [opts.checkOpposite] {boolean}
* @param [opts.aggregatedSceneStatistics]
* @returns {{best: Attachment, candidates: Attachment[]}}
*/
function identifyAttachments(parents, modelInstWithCandidates, opts) {
// Options
// sameModelCost - Cost for same model
// contactDistThreshold - Contact dist threshold
// includeAllCandidates - Returns array of all candidates within threshold
opts = opts || {};
var debug = opts.debug;
if (debug) {
console.log('identifyAttachments opts', opts);
}
var maxCandidates = opts.maxCandidates || Infinity; // max candidate to track
var maxCandidatesToCheckPerAttachment = opts.maxCandidatesToCheck || maxCandidates; // Max candidates to check per attachment
var deltaContactDistThresholdPerAttachment = (opts.deltaContactDistThreshold != undefined)? opts.deltaContactDistThreshold : (0.02 * Constants.metersToVirtualUnit); // maximum distance from closest attachment to furthest
var contactDistThreshold = (opts.contactDistThreshold != undefined)? opts.contactDistThreshold : (0.10 * Constants.metersToVirtualUnit); // maximum distance from attachment point to support
var modelInstance = modelInstWithCandidates.modelInstance;
var candidatesAttachments = modelInstWithCandidates.attachments;
var childModelId = modelInstance? modelInstance.model.info.fullId : null;
var childObjectId = modelInstance? modelInstance.object3D.userData.id : null;
if (debug) {
var childBBox = modelInstance.getBBox();
//var childFaceDims = childBBox.getFaceDims();
console.log('Child bbox', childBBox);
console.log('Candidate parent bboxes', parents.map(function (p) {
return Object3DUtil.getBoundingBox(p);
}));
}
function getRoomIds(object3D) {
var roomIds = _.get(object3D, ['userData', 'roomIds']);
if (roomIds) { return roomIds; }
var roomId = _.get(object3D, ['userData', 'roomId']);
if (roomId != undefined) {
return [roomId];
} else {
return [];
}
}
function hasCommonRoomId(roomIds1, roomIds2) {
var intersection = _.intersection(roomIds1, roomIds2);
return intersection.length > 0;
}
var childRoomIds = modelInstance? getRoomIds(modelInstance.object3D) : [];
function isBetter(cand, best, debug) {
var intersected = cand.parentAttachment;
//console.log('compare', cand, best);
if (intersected.distance > contactDistThreshold) {
return false;
}
if (!best) {
return true;
}
var modelIdSameCostBest = 0;
var modelIdSameCostCurr = 0;
if (opts.sameModelCost > 0) {
// Check if the two models are the same
var bestModelInst = best.parentInst;
var currentModelInst = cand.parentInst;
var parentModelIdBest = bestModelInst? bestModelInst.model.info.fullId : null;
var parentModelIdCurr = currentModelInst? currentModelInst.model.info.fullId : null;
var modelIdSameBest = parentModelIdBest? parentModelIdBest === childModelId : false;
modelIdSameCostBest = modelIdSameBest? opts.sameModelCost : 0;
var modelIdSameCurr = parentModelIdCurr? parentModelIdCurr === childModelId : false;
modelIdSameCostCurr = modelIdSameCurr? opts.sameModelCost : 0;
//if (debug) console.log('modelIdSameCosts: ', modelIdSameCostBest, modelIdSameCostCurr);
}
if (Math.abs(intersected.distance - best.parentAttachment.distance) < contactDistThreshold*0.75) {
if (Math.abs(intersected.normSim - best.parentAttachment.normSim) < 0.01) {
if (opts.aggregatedSceneStatistics) {
var ss = opts.aggregatedSceneStatistics;
// Determine preferred normal and attachment based on object id/type (curtain to windows, etc)
// Get parent child statistics for the object types
var childIdAttachmentCounts = ss.getObjectIdChildAttachmentCounts();
var counter = childIdAttachmentCounts.get([childModelId]);
var total = counter? counter.sum : 0;
var modelCats = modelInstance ? modelInstance.model.getCategories() : [];
var selectedCat = null;
while (total < 20 && modelCats.length) {
var cat = modelCats[modelCats.length - 1];
var childTypeAttachmentCounts = ss.getObjectTypeChildAttachmentCounts();
counter = childTypeAttachmentCounts.get([cat]);
total = counter? counter.sum : 0;
selectedCat = cat;
}
if (total > 50) {
var countThreshold = total * 0.1;
var candAttachmentFace = ss.bbfaceIndexToAttachmentTypeIndex(cand.childAttachment.bbfaceIndex);
var bestAttachmentFace = ss.bbfaceIndexToAttachmentTypeIndex(best.childAttachment.bbfaceIndex);
var candCount = counter.get(candAttachmentFace);
var bestCount = counter.get(bestAttachmentFace);
//if (debug) console.log('got attachment priors for object', childObjectId, 'model', childModelId, selectedCat,
// 'total', total, 'threshold', countThreshold,
// 'cand', ss.getAttachmentType(candAttachmentFace), candCount,
// 'best', ss.getAttachmentType(bestAttachmentFace), bestCount);
if (candCount > (bestCount + countThreshold)) {
//if (debug) console.log('select cand', childObjectId);
return true;
} else if (bestCount > (candCount + countThreshold)) {
//if (debug) console.log('select best', childObjectId);
return false;
}
}
}
// Check normal
if (intersected.normal.dot(best.parentSurfaceNormal) > 0.9) {
// Prefer correct room
// Check candidate and best rooms
var candRoomIds = getRoomIds(cand.parent);
var bestRoomIds = getRoomIds(best.parent);
//if (debug) console.log('check room ids', childRoomIds, candRoomIds, bestRoomIds);
var candInSameRoom = hasCommonRoomId(childRoomIds, candRoomIds);
var bestInSameRoom = hasCommonRoomId(childRoomIds, bestRoomIds);
if (candInSameRoom !== bestInSameRoom) {
return candInSameRoom; // Favor candidate
} else {
// TODO: Do we want to do other checks here - maybe favor smaller parent surface?
return false;
}
} else {
// Favor big flat surfaces (of the child bounding box)
var candBBFaceDims = _.get(cand, ['childAttachment', 'world', 'faceDims']);
var bestBBFaceDims = _.get(best, ['childAttachment', 'world', 'faceDims']);
var candFaceMin = candBBFaceDims ? Math.min(candBBFaceDims.x, candBBFaceDims.y) : 0;
var bestFaceMin = bestBBFaceDims ? Math.min(bestBBFaceDims.x, bestBBFaceDims.y) : 0;
//if (debug) console.log('compare faces', childModelId, cand, candFaceMin, best, bestFaceMin);
if (candFaceMin > bestFaceMin*5) {
return true;
} else if (bestFaceMin > candFaceMin*5) {
return false;
}
// prefer world bottom attachment
if (intersected.normal.dot(Constants.worldUp) > 0.99) {
return true;
} else if (best.parentSurfaceNormal.dot(Constants.worldUp) > 0.99) {
return false;
} else if (intersected.normal.dot(Constants.worldUp) < -0.99) {
return false;
} else if (best.parentSurfaceNormal.dot(Constants.worldUp) < -0.99) {
return true;
} else {
var candFaceArea = candBBFaceDims? candBBFaceDims.x * candBBFaceDims.y : 0;
var bestFaceArea = bestBBFaceDims? bestBBFaceDims.x * bestBBFaceDims.y : 0;
//if (debug) console.log('compare faces', childModelId, cand, candFaceArea, best, bestFaceArea);
if (candFaceArea > bestFaceArea*2) {
return true;
} else if (bestFaceArea > candFaceArea*2) {
return false;
}
}
}
} else {
return (intersected.normSim > best.parentAttachment.normSim);
}
}
return (modelIdSameCostCurr < modelIdSameCostBest || intersected.distance < best.parentAttachment.distance);
}
// Raytrace out from candidate attachments
var picker = new Picker();
var raycaster = new THREE.Raycaster();
var raycasterOpposite = new THREE.Raycaster();
var best = null;
var candidates = [];
for (var i = 0; i < candidatesAttachments.length; i++) {
var candidate = candidatesAttachments[i];
//console.log('candidate', candidate);
raycaster.ray.origin.copy(candidate.world.pos);
// Go back just a little
var s = candidate.world.size;
//var s = Math.abs(bbdims.x * candidate.world.out.x) + Math.abs(bbdims.y * candidate.world.out.y) + Math.abs(bbdims.z * candidate.world.out.z);
//console.log('compare', s, candidate.world.size);
var offset = 0.2*s;
raycaster.ray.origin.addScaledVector(candidate.world.out, -offset);
raycaster.ray.direction.copy(candidate.world.out);
var intersected = picker.getIntersectedForRay(raycaster, parents);
// Select the closest parent (favoring attachment with parent surface normal up)
if (debug) {
console.log('intersected', deltaContactDistThresholdPerAttachment, intersected, raycaster.ray.origin, raycaster.ray.direction);
}
if (intersected.length > 0) {
_.forEach(intersected, function(i) { i.distance = Math.max(i.distance - offset, 0); }); // subtract offset from distance
if (debug) {
console.log('intersected revised distances', deltaContactDistThresholdPerAttachment, intersected, raycaster.ray.origin, raycaster.ray.direction);
}
var closest = intersected[0];
if (closest.distance > contactDistThreshold) {
if (debug) {
console.log('Skipping intersected since closest is too far', closest.distance, contactDistThreshold);
}
continue; // Skip
}
var distThreshold = Math.min(contactDistThreshold, closest.distance + deltaContactDistThresholdPerAttachment);
var intersectedWithinThreshold = intersected.filter( function(x) {
return x.distance <= distThreshold;
});
if (debug) {
console.log('closest', childObjectId, closest, intersectedWithinThreshold);
}
// Don't remember what this is for - decide if this is still useful
// Check if there is a better intersection slightly before this one
if (opts.checkOpposite && intersectedWithinThreshold.length > 1) {
raycasterOpposite.ray.origin.copy(closest.point);
raycasterOpposite.ray.direction.copy(candidate.world.out);
raycasterOpposite.ray.direction.negate();
var intersectedOpposite = picker.getIntersectedForRay(raycasterOpposite, parents);
if (intersectedOpposite.length > 0) {
if (debug) {
console.log('intersectedOpposite', intersectedOpposite);
}
for (var j = 1; j < intersectedWithinThreshold.length; j++) {
var intersect1 = intersectedWithinThreshold[j];
for (var k = 0; k < intersectedOpposite.length; k++) {
var intersect2 = intersectedOpposite[k];
if (intersect2.distance < contactDistThreshold) {
if (intersect2.object === intersect1.object) {
if (debug) {
console.log('Using intersectedOpposite', intersect1, intersect2);
}
closest = intersect1;
break;
}
} else {
break;
}
}
}
}
}
if (debug) {
console.log('closest', childObjectId, closest, intersectedWithinThreshold);
}
// Compute normSim
var candidateNormOut = candidate.world.out.clone().negate();
for (var j = 0; j < intersectedWithinThreshold.length; j++) {
var c = intersectedWithinThreshold[j];
c.order = j;
var norm = picker.getIntersectedNormal(c);
if (c.normSim == undefined) {
c.normSim = candidateNormOut.dot(norm);
}
}
if (opts.disallowSameModelHorizontalAttachment && childModelId != null) {
intersectedWithinThreshold = _.filter(intersectedWithinThreshold, function(intersect) {
var parentInst = Object3DUtil.getModelInstance(intersect.object, true);
if (parentInst && parentInst.model.info.fullId === childModelId) {
if (childWorldBBFaceIndex === Constants.BBoxFaces.TOP || childWorldBBFaceIndex === Constants.BBoxFaces.BOTTOM) {
return true;
} else {
console.log('filtering out potential support due to disallowSameModelHorizontalAttachment for ' + childObjectId + ' and ' + intersect.object.userData.id);
return false;
}
} else {
return true;
}
});
}
// Group by object id
var groupedByObjectId = _.groupBy(intersectedWithinThreshold, function(x) { return x.object.uuid; });
var objectIds = _.keys(groupedByObjectId);
objectIds = _.sortBy(objectIds, function(id) { return groupedByObjectId[id][0].order; });
// Update acceptable candidates (next to)
var nCandidates = Math.min(objectIds.length, maxCandidates);
for (var k = 0; k < nCandidates; k++) {
var objectId = objectIds[k];
if (debug) {
console.log('Check ' + objectId);
}
var intersectsForObject = groupedByObjectId[objectId];
for (var j = 0; j < intersectsForObject.length; j++) {
var c = intersectsForObject[j];
var norm = picker.getIntersectedNormal(c);
var childWorldBBFaceIndex = Object3DUtil.findClosestBBFaceByInNormal(norm);
//childWorldBBFaceDims = bbox.getFaceDims()[childWorldBBFaceIndex];
var parentInst = Object3DUtil.getModelInstance(c.object, true);
var candidateToCheck = {
child: modelInstance ? modelInstance.object3D : undefined,
childInst: modelInstance ? modelInstance : undefined,
parent: c.object,
parentInst: parentInst,
parentSurfaceNormal: norm,
childWorldBBFaceIndex: childWorldBBFaceIndex,
//childWorldBBFaceDims: childWorldBBFaceDims,
parentAttachment: c,
childAttachment: candidate // Candidate attachment point
};
if (k < maxCandidatesToCheckPerAttachment && isBetter(candidateToCheck, best, false)) {
best = candidateToCheck;
if (debug) {
console.log('updating best', childObjectId, best.parent.userData.id, best);
}
}
if (opts.includeCandidates) {
candidates.push(candidateToCheck);
}
}
}
}
}
var res = {
best: best
};
if (opts.includeCandidates) {
candidates.sort(function(a,b) { return isBetter(a,b,false)? -1 : 1; }); // NOTE this compare is not necessarily valid
res.candidates = candidates;
}
return res;
}
Attachments.identifyAttachments = identifyAttachments;
function identifyAttachment(parents, candidatesAttachments, opts) {
// Returns best attachment
var attachments = identifyAttachments(parents, candidatesAttachments, opts);
if (attachments.best) {
return attachments.best;
}
}
Attachments.identifyAttachment = identifyAttachment;
// Exports
module.exports = Attachments;
|
import Categories from './routes/categories/Index.vue'
import Posts from './routes/posts/Index.vue'
import PostTags from './routes/post-tags/Index.vue'
import Tags from './routes/tags/Index.vue'
let blogRoutes = [
{
path: 'categories',
name: 'blog-categories',
component: Categories,
},
{
path: 'posts',
name: 'blog-posts',
component: Posts,
},
{
path: 'post-tags',
name: 'blog-post-tags',
component: PostTags,
},
{
path: 'tags',
name: 'blog-tags',
component: Tags,
},
]
export default blogRoutes
|
package com.outr.lucene4s.query
import com.outr.lucene4s._
import com.outr.lucene4s.facet.FacetField
import org.apache.lucene.search.TopFieldCollector
import org.apache.lucene.search.highlight.{Highlighter, QueryScorer, SimpleHTMLFormatter}
case class QueryBuilder[T] private[lucene4s](lucene: Lucene,
facets: Set[FacetQuery] = Set.empty,
offset: Int = 0,
limit: Int = 10,
sorting: List[Sort] = Nil,
scoreDocs: Boolean = false,
scoreMax: Boolean = false,
searchTerms: List[SearchTerm] = Nil,
conversion: SearchResult => T,
highlighting: Option[Highlighting] = None) {
def offset(v: Int): QueryBuilder[T] = copy(offset = v)
def limit(v: Int): QueryBuilder[T] = copy(limit = v)
def convert[V](conversion: SearchResult => V): QueryBuilder[V] = copy[V](conversion = conversion)
def facet(field: FacetField,
limit: Int = 10,
path: List[String] = Nil): QueryBuilder[T] = {
copy(facets = facets + FacetQuery(field, limit, path))
}
def scoreDocs(b: Boolean = true): QueryBuilder[T] = copy(scoreDocs = b)
def scoreMax(b: Boolean = true): QueryBuilder[T] = copy(scoreMax = b)
def filter(searchTerms: SearchTerm*): QueryBuilder[T] = copy(searchTerms = this.searchTerms ::: searchTerms.toList)
def highlight(preTag: String = "<em>", postTag: String = "</em>"): QueryBuilder[T] = copy(highlighting = Some(Highlighting(preTag, postTag)))
def sort(sort: Sort*): QueryBuilder[T] = {
copy(sorting = sorting ::: sort.toList)
}
def replaceSort(sort: Sort*): QueryBuilder[T] = {
copy(sorting = sort.toList)
}
def search(): PagedResults[T] = {
val baseQuery = searchTerms match {
case Nil => MatchAllSearchTerm
case st :: Nil => st
case _ => grouped(searchTerms.map(_ -> Condition.Must): _*)
}
val q = SearchTerm.toLucene(baseQuery, lucene)
// TODO: support really high offsets via multiple jumps via searchAfter to avoid memory issues
val manager = new DocumentCollector(lucene, this)
lucene.withSearcherAndTaxonomy { instance =>
val searchResults: SearchResults = instance.searcher.search(q, manager)
if (scoreDocs) {
TopFieldCollector.populateScores(searchResults.topDocs.scoreDocs, instance.searcher, q)
}
val highlighter = highlighting.map {
case Highlighting(preTag, postTag) => {
val highlightFormatter = new SimpleHTMLFormatter(preTag, postTag)
new Highlighter(highlightFormatter, new QueryScorer(q))
}
}
new PagedResults(lucene, this, offset, searchResults, highlighter)
}
}
def delete(): Unit = {
val query = searchTerms match {
case Nil => MatchAllSearchTerm
case st :: Nil => st
case _ => grouped(searchTerms.map(_ -> Condition.Must): _*)
}
lucene.delete(query)
}
}
case class Highlighting(preTag: String, postTag: String)
|
use amiquip::{
Channel, ConfirmSmoother, Connection, Exchange, Publish, QueueDeclareOptions, Result,
};
fn publish_messages_with_confirmation(
channel: &Channel,
// queue to publish to
target_queue: &str,
// number of messages to publish before waiting for confirms
group_size: usize,
// number of groups to send before returning
num_groups: usize,
) -> Result<()> {
let exchange = Exchange::direct(channel);
// register a pub confirm listener before putting the channel into confirm mode
let confirm_listener = channel.listen_for_publisher_confirms()?;
// put channel in confirm mode
channel.enable_publisher_confirms()?;
// create a confirm smoother so we can process perfectly sequential confirmations
let mut confirm_smoother = ConfirmSmoother::new();
for i in 0..num_groups {
// publish group_size messages
println!("publishing {} messages (group {})", group_size, i);
for _ in 0..group_size {
exchange.publish(Publish::new(b"hello", target_queue))?;
}
// wait for confirmation from the server for those 10 messages
let mut confirmed = 0;
while confirmed < group_size {
let confirm = match confirm_listener.recv() {
Ok(confirm) => confirm,
Err(_) => {
// sender is gone - something has gone wrong with the channel;
// we'll see that error when we try to publish again or close it
break;
}
};
println!("got raw confirm {:?} from server", confirm);
for confirm in confirm_smoother.process(confirm) {
println!("got smoothed confirm {:?}", confirm);
confirmed += 1;
}
}
}
Ok(())
}
// Use technique discussed on Connection::close to capture connection errors
fn use_connection(connection: &mut Connection) -> Result<()> {
let channel = connection.open_channel(None)?;
// create an anonymous queue for us to publish to; we're not going to consume
// from this, but we want it to be deleted once the example is done.
let queue = channel.queue_declare(
"",
QueueDeclareOptions {
exclusive: true,
..QueueDeclareOptions::default()
},
)?;
// publish 3 groups of 10 messages, waiting for confirms between each group
publish_messages_with_confirmation(&channel, queue.name(), 10, 3)?;
channel.close()
}
fn main() -> Result<()> {
let mut connection = Connection::insecure_open("amqp://guest:guest@localhost:5672")?;
let result = use_connection(&mut connection);
connection.close()?;
result
}
|
namespace Kala.Models
{
public enum ScreensaverTypes
{
Clock = 0,
Images = 1,
};
}
|
package nl.jolanrensen.efficientlyDiscoveringTernaryLaggedCorrelations.stampPearson
import nl.jolanrensen.efficientlyDiscoveringTernaryLaggedCorrelations.invoke
import nl.jolanrensen.efficientlyDiscoveringTernaryLaggedCorrelations.nextPowerOf2
import nl.jolanrensen.efficientlyDiscoveringTernaryLaggedCorrelations.sliceFlat
import nl.jolanrensen.efficientlyDiscoveringTernaryLaggedCorrelations.stampPearson.StampArrayCache.Slot.*
import org.jetbrains.bio.viktor.F64FlatArray
import java.io.Serializable
/**
*
* Array cache used by [StampPearson], [StampPearson3ts], [StampPearson3tsWithSkipping]
* This makes sure that no new memory needs to be allocated for a second stamp run.
* It does make it so that one stamp instance cannot run in parallel.
*
* @param maxSize usually largest time series size
*
*/
class StampArrayCache(
private val maxSize: Int = 100,
private val slotManager: SlotManager = SlotsWithReuse,
) : Serializable {
enum class Slot : Serializable {
A, // used in slidingDotProducts
B, // used in slidingDotProducts
B1, // queryCTimeSeriesASlidingDotProducts
B2, // queryCTimeSeriesBSlidingDotProducts
B3, // QT
B4, // TQaSumsSlidingDots
C, // cacheQueryCTimeSeriesASlidingDotProducts
D, // cacheQueryCTimeSeriesBSlidingDotProducts
E, // cacheQueryBTimeSeriesASlidingDotProducts
F, // timeSeriesASlidingMeans
G, // timeSeriesASlidingStds
H, // timeSeriesASlidingMeansAggQC
I, // timeSeriesASlidingStdsAggQC
J, // timeSeriesBSlidingMeans
K, // timeSeriesBSlidingMeans
L, // cacheQueryBTimeSeriesASlidingDotProducts
M, // queryCStd
N, // agg(QB, QC)
O, // mus_T
P, // sigmas_T
Q, // QaSums
R, // QDotsQa
S, // timeSeriesCSlidingMeans
T, // timeSeriesCSlidingStds
U, // query = QC
}
sealed interface SlotManager : Serializable {
operator fun invoke(slot: Slot): Int
}
/**
* Has some slots overlapping to save space.
* Default SlotManager.
*/
object SlotsWithReuse : SlotManager {
override fun invoke(slot: Slot): Int = when (slot) {
A -> 0
B -> 1
B1 -> 17
B2 -> 18
B3 -> 19
B4 -> 20
C -> 2
D -> 3
E -> 4
F -> 5
G -> 6
H -> 7
I -> 8
J -> 9
K -> 10
L -> 11
M -> 0
N -> 12
O -> 0
P -> 1
Q -> 13
R -> 0
S -> 14
T -> 15
U -> 16
}
}
/**
* All slots are unique, better for debugging at cost of space.
*/
object SlotsWithoutReuse : SlotManager {
override fun invoke(slot: Slot): Int = when (slot) {
A -> 0
B -> 1
B1 -> 21
B2 -> 22
B3 -> 23
B4 -> 24
C -> 2
D -> 3
E -> 4
F -> 5
G -> 6
H -> 7
I -> 8
J -> 9
K -> 10
L -> 11
M -> 12
N -> 13
O -> 14
P -> 15
Q -> 16
R -> 17
S -> 18
T -> 19
U -> 20
}
}
/**
* Array cache is not used.
*/
object NoSlots : SlotManager {
override fun invoke(slot: Slot): Int = -1
}
private val arrayCache: MutableMap<Int, F64FlatArray> =
when (slotManager) {
SlotsWithReuse, SlotsWithoutReuse ->
Slot.values()
.map {
object {
val slotKey = slotManager(it)
val isSlidingDots = it in listOf(A, B, B1, B2, B3, B4)
}
}
.associateWith { F64FlatArray(if (it.isSlidingDots) 2 * nextPowerOf2(maxSize) else maxSize) }
.mapKeys { (key, _) -> key.slotKey }
.toMutableMap()
NoSlots -> mutableMapOf()
}
operator fun get(size: Int, slot: Slot): F64FlatArray = when {
slotManager == NoSlots ->
F64FlatArray(size)
slotManager(slot) !in arrayCache ->
F64FlatArray(size)
.also { arrayCache[slotManager(slot)] = it }
arrayCache[slotManager(slot)]!!.length == size ->
arrayCache[slotManager(slot)]!!
arrayCache[slotManager(slot)]!!.length > size ->
arrayCache[slotManager(slot)]!!
.sliceFlat(0, size)
else ->
F64FlatArray(size).also {
arrayCache[slotManager(slot)] = it
println("had to enlarge slot $slot to size $size")
}
}
override fun toString(): String = arrayCache.toString()
}
|
#!/bin/bash
# Temporary:
sysctl -w vm.max_map_count=262144
sysctl -w net.ipv4.ip_local_port_range="15000 61000"
sysctl -w net.ipv4.tcp_fin_timeout=30
sysctl -w net.core.somaxconn=1024
sysctl -w net.core.netdev_max_backlog=2000
sysctl -w net.ipv4.tcp_max_syn_backlog=2048
sysctl -w vm.overcommit_memory=1
# Definitive:
#echo "vm.max_map_count=262144" >> /etc/sysctl.conf
#echo "net.ipv4.ip_local_port_range=\"15000 61000\"" >> /etc/sysctl.conf
#echo "net.ipv4.tcp_fin_timeout=30" >> /etc/sysctl.conf
#echo "net.core.somaxconn=1024" >> /etc/sysctl.conf
#echo "net.core.netdev_max_backlog=2000" >> /etc/sysctl.conf
#echo "net.ipv4.tcp_max_syn_backlog=2048" >> /etc/sysctl.conf
#echo "vm.overcommit_memory=1" >> /etc/sysctl.conf
#
|
package com.yuchen.howyo.profile
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.yuchen.howyo.MainViewModel
import com.yuchen.howyo.NavigationDirections
import com.yuchen.howyo.R
import com.yuchen.howyo.databinding.FragmentProfileBinding
import com.yuchen.howyo.ext.getVmFactory
import com.yuchen.howyo.plan.AccessPlanType
import com.yuchen.howyo.signin.UserManager
class ProfileFragment : Fragment() {
private lateinit var binding: FragmentProfileBinding
val viewModel by viewModels<ProfileViewModel> {
getVmFactory(
ProfileFragmentArgs.fromBundle(requireArguments()).userId
)
}
override fun onCreate(savedInstanceState: Bundle?) {
setHasOptionsMenu(true)
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentProfileBinding.inflate(inflater, container, false)
binding.lifecycleOwner = this
binding.viewModel = viewModel
binding.recyclerProfilePlans.adapter = PlanAdapter(
PlanAdapter.OnClickListener {
viewModel.navigateToPlan(it)
}
)
val mainViewModel = ViewModelProvider(requireActivity()).get(MainViewModel::class.java)
viewModel.currentUser.observe(viewLifecycleOwner) {
it?.let {
mainViewModel.setSharedToolbarTitle(it.name ?: "")
}
}
viewModel.navigateToPlan.observe(viewLifecycleOwner) {
it?.let {
findNavController().navigate(
NavigationDirections.navToPlanFragment(it, AccessPlanType.VIEW)
)
viewModel.onPlanNavigated()
}
}
viewModel.navigateToSetting.observe(viewLifecycleOwner) {
it?.let {
if (it) findNavController().navigate(NavigationDirections.navToSettingFragment())
viewModel.onSettingNavigated()
}
}
viewModel.navigateToFriends.observe(viewLifecycleOwner) {
it?.let {
findNavController().navigate(
NavigationDirections.navToFriendsFragment(it, UserManager.userId ?: "")
)
viewModel.onFriendNavigated()
}
}
return binding.root
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.home_toolbar_nav_view_menu, menu)
menu.findItem(R.id.setting).isVisible = true
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.setting -> viewModel.navigateToSetting()
}
return super.onOptionsItemSelected(item)
}
}
|
package com.snakydesign.livedataextensions
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito
import org.mockito.Mockito.never
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyNoMoreInteractions
import org.mockito.Mockito.verifyZeroInteractions
/**
* Created by Adib Faramarzi
*/
@Suppress("UNCHECKED_CAST")
class CombiningTest {
@Rule
@JvmField
val rule = InstantTaskExecutorRule()
@Before
fun setUp() {
}
@After
fun tearDown() {
}
@Test
fun `test LiveData merge multiple LiveData`() {
val observer = Mockito.mock(Observer::class.java) as Observer<Int>
val sourceLiveData1 = MutableLiveData<Int>()
val sourceLiveData2 = MutableLiveData<Int>()
sourceLiveData1.value = 2
sourceLiveData2.value = 3
val testingLiveData = merge(listOf(sourceLiveData1, sourceLiveData2))
testingLiveData.observeForever(observer)
Assert.assertEquals(3, testingLiveData.value)
verify(observer).onChanged(2)
verify(observer).onChanged(3)
sourceLiveData1.value = 5
Assert.assertEquals(5, testingLiveData.value)
Mockito.verify(observer).onChanged(5)
sourceLiveData2.value = 8
Assert.assertEquals(8, testingLiveData.value)
verify(observer).onChanged(8)
verifyNoMoreInteractions(observer)
}
@Test
fun `test LiveData merge with another LiveData`() {
val observer = Mockito.mock(Observer::class.java) as Observer<Int>
val sourceLiveData1 = MutableLiveData<Int>()
val sourceLiveData2 = MutableLiveData<Int>()
sourceLiveData1.value = 2
sourceLiveData2.value = 3
val testingLiveData = sourceLiveData1.mergeWith(sourceLiveData2)
testingLiveData.observeForever(observer)
Assert.assertEquals(3, testingLiveData.value)
verify(observer).onChanged(2)
verify(observer).onChanged(3)
sourceLiveData1.value = 5
Assert.assertEquals(5, testingLiveData.value)
Mockito.verify(observer).onChanged(5)
sourceLiveData2.value = 8
Assert.assertEquals(8, testingLiveData.value)
verify(observer).onChanged(8)
verifyNoMoreInteractions(observer)
}
@Test
fun `test LiveData startWith`() {
val observer = Mockito.mock(Observer::class.java) as Observer<Int>
val sourceLiveData1 = MutableLiveData<Int>()
val testingLiveData = sourceLiveData1.startWith(2)
testingLiveData.observeForever(observer)
Assert.assertEquals(2, testingLiveData.value)
verify(observer).onChanged(2)
sourceLiveData1.value = 3
verify(observer).onChanged(3)
Assert.assertEquals(3, testingLiveData.value)
verifyNoMoreInteractions(observer)
}
@Test
fun `test LiveData zip with another LiveData`() {
val observer = Mockito.mock(Observer::class.java) as Observer<Pair<Boolean?, Int?>>
val sourceLiveData1 = MutableLiveData<Boolean>()
val sourceLiveData2 = MutableLiveData<Int>()
val expectedResult = Pair(true, 3)
val testingLiveData = zip(sourceLiveData1, sourceLiveData2) { b, i -> Pair(b, i) }
testingLiveData.observeForever(observer)
sourceLiveData1.value = true
Assert.assertEquals(null, testingLiveData.value)
sourceLiveData2.value = 3
Assert.assertEquals(expectedResult, testingLiveData.value)
verify(observer).onChanged(expectedResult)
sourceLiveData2.value = 4 // should not trigger the live data
verifyNoMoreInteractions(observer)
}
@Test
fun `test LiveData zip with another LiveData for second emission`() {
val observer = Mockito.mock(Observer::class.java) as Observer<Pair<Boolean?, Int?>>
val sourceLiveData1 = MutableLiveData<Boolean>()
val sourceLiveData2 = MutableLiveData<Int>()
val expectedResult = Pair(true, 3)
val expectedResult2 = Pair(false, 4)
val testingLiveData = zip(sourceLiveData1, sourceLiveData2) { b, i -> Pair(b, i) }
testingLiveData.observeForever(observer)
sourceLiveData1.value = true
Assert.assertEquals(null, testingLiveData.value)
sourceLiveData2.value = 3
Assert.assertEquals(expectedResult, testingLiveData.value)
verify(observer).onChanged(expectedResult)
sourceLiveData2.value = 4
sourceLiveData1.value = false // should not trigger the live data
verify(observer).onChanged(expectedResult2)
verifyNoMoreInteractions(observer)
}
@Test
fun `test LiveData zip with 2 other LiveData`() {
val observer = Mockito.mock(Observer::class.java) as Observer<Triple<Boolean?, Int?, String?>>
val sourceLiveData1 = MutableLiveData<Boolean>()
val sourceLiveData2 = MutableLiveData<Int>()
val sourceLiveData3 = MutableLiveData<String>()
val expectedResult = Triple(true, 3, "hello")
val testingLiveData = zip(sourceLiveData1, sourceLiveData2, sourceLiveData3) { b, i, s -> Triple(b, i, s) }
testingLiveData.observeForever(observer)
sourceLiveData1.value = true
Assert.assertEquals(null, testingLiveData.value)
sourceLiveData2.value = 3
Assert.assertEquals(null, testingLiveData.value)
sourceLiveData3.value = "hello"
Assert.assertEquals(expectedResult, testingLiveData.value)
verify(observer).onChanged(expectedResult)
verifyNoMoreInteractions(observer)
}
@Test
fun `test LiveData zip with null values`() {
val observer = Mockito.mock(Observer::class.java) as Observer<Triple<Boolean?, Int?, String?>>
val sourceLiveData1 = MutableLiveData<Boolean>()
val sourceLiveData2 = MutableLiveData<Int>()
val sourceLiveData3 = MutableLiveData<String>()
val testingLiveData = zip(sourceLiveData1, sourceLiveData2, sourceLiveData3)
testingLiveData.observeForever(observer)
// Ensure there is no emit until all sources have emitted
sourceLiveData1.value = null
sourceLiveData2.value = null
Assert.assertEquals(null, testingLiveData.value)
verify(observer, never()).onChanged(any())
// After all emitted null, we expect an emit with null values
sourceLiveData3.value = null
val expectedResult = Triple<Boolean?, Int?, String?>(null, null, null)
Assert.assertEquals(expectedResult, testingLiveData.value)
verify(observer).onChanged(expectedResult)
// Ensure there is no emit until all sources have emitted a new value
sourceLiveData2.value = 42
sourceLiveData3.value = "42"
verifyZeroInteractions(observer)
// After all emitted new value, we expect another emit
sourceLiveData1.value = true
val expectedResult2 = Triple<Boolean?, Int?, String?>(true, 42, "42")
Assert.assertEquals(expectedResult2, testingLiveData.value)
verify(observer).onChanged(expectedResult2)
}
@Test
fun `test LiveData sample with another LiveData`() {
val observer = Mockito.mock(Observer::class.java) as Observer<Triple<Boolean?, Int?, String?>>
val sourceLiveData1 = MutableLiveData<Boolean>()
val sourceLiveData2 = MutableLiveData<Int>()
val sourceLiveData3 = MutableLiveData<String>()
val expectedResult = Triple(true, 3, "hello")
val testingLiveData = zip(sourceLiveData1, sourceLiveData2, sourceLiveData3) { b, i, s -> Triple(b, i, s) }
testingLiveData.observeForever(observer)
sourceLiveData1.value = true
Assert.assertEquals(null, testingLiveData.value)
sourceLiveData2.value = 3
Assert.assertEquals(null, testingLiveData.value)
sourceLiveData3.value = "hello"
Assert.assertEquals(expectedResult, testingLiveData.value)
verify(observer).onChanged(expectedResult)
verifyNoMoreInteractions(observer)
}
@Test
fun `test LiveData combineLatest with another LiveData`() {
val observer = Mockito.mock(Observer::class.java) as Observer<Pair<Boolean?, Int?>>
val sourceLiveData1 = MutableLiveData<Boolean>()
val sourceLiveData2 = MutableLiveData<Int>()
val expectedResult = Pair(true, 3)
val expectedResult2 = Pair(true, 4)
val expectedResult3 = Pair(false, 4)
val testingLiveData = combineLatest(sourceLiveData1, sourceLiveData2) { boolean, int -> Pair(boolean, int) }
testingLiveData.observeForever(observer)
sourceLiveData1.value = true
Assert.assertEquals(null, testingLiveData.value)
sourceLiveData2.value = 3
Assert.assertEquals(expectedResult, testingLiveData.value)
verify(observer).onChanged(expectedResult)
sourceLiveData2.value = 4
Assert.assertEquals(expectedResult2, testingLiveData.value)
verify(observer).onChanged(expectedResult2)
sourceLiveData1.value = false
Assert.assertEquals(expectedResult3, testingLiveData.value)
verify(observer).onChanged(expectedResult3)
verifyNoMoreInteractions(observer)
}
@Test
fun `test LiveData combineLatest with null values`() {
val observer = Mockito.mock(Observer::class.java) as Observer<Pair<Boolean?, Int?>>
val sourceLiveData1 = MutableLiveData<Boolean>()
val sourceLiveData2 = MutableLiveData<Int>()
val testingLiveData = combineLatest(sourceLiveData1, sourceLiveData2) { boolean, int -> Pair(boolean, int) }
testingLiveData.observeForever(observer)
// Ensure there is no emit until all sources have emitted
sourceLiveData1.value = null
Assert.assertEquals(null, testingLiveData.value)
verify(observer, never()).onChanged(any())
// After all emitted null, we expect an emit with null values
sourceLiveData2.value = null
val expectedResult = Pair<Boolean?, Int?>(null, null)
Assert.assertEquals(expectedResult, testingLiveData.value)
verify(observer).onChanged(expectedResult)
// One emitted a non-null value
sourceLiveData2.value = 4
val expectedResult2 = Pair<Boolean?, Int?>(null, 4)
Assert.assertEquals(expectedResult2, testingLiveData.value)
verify(observer).onChanged(expectedResult2)
// Both emitted a non-null value
sourceLiveData1.value = false
val expectedResult3 = Pair(false, 4)
Assert.assertEquals(expectedResult3, testingLiveData.value)
verify(observer).onChanged(expectedResult3)
verifyNoMoreInteractions(observer)
}
@Test
fun `test LiveData combineLatest three with null values`() {
val observer = Mockito.mock(Observer::class.java) as Observer<Triple<Boolean?, Int?, Long?>>
val sourceLiveData1 = MutableLiveData<Boolean>()
val sourceLiveData2 = MutableLiveData<Int>()
val sourceLiveData3 = MutableLiveData<Long>()
val testingLiveData = combineLatest(sourceLiveData1, sourceLiveData2, sourceLiveData3) { boolean, int, long ->
Triple(boolean, int, long)
}
testingLiveData.observeForever(observer)
// Ensure there is no emit until all sources have emitted
sourceLiveData1.value = null
sourceLiveData2.value = null
Assert.assertEquals(null, testingLiveData.value)
verify(observer, never()).onChanged(any())
// After all emitted null, we expect an emit with null values
sourceLiveData3.value = null
val expectedResult = Triple<Boolean?, Int?, Long?>(null, null, null)
Assert.assertEquals(expectedResult, testingLiveData.value)
verify(observer).onChanged(expectedResult)
}
@Test
fun `test LiveData sampleWith another live data`() {
val observer = Mockito.mock(Observer::class.java) as Observer<Int>
val sourceLiveData = MutableLiveData<Int>()
val samplerLiveData = MutableLiveData<Boolean>()
val testingLiveData = sourceLiveData.sampleWith(samplerLiveData)
testingLiveData.observeForever(observer)
sourceLiveData.value = 1
Assert.assertNull(testingLiveData.value)
sourceLiveData.value = 2
Assert.assertNull(testingLiveData.value)
samplerLiveData.value = true
Assert.assertEquals(2, testingLiveData.value)
verify(observer).onChanged(2)
sourceLiveData.value = 3
Assert.assertEquals(2, testingLiveData.value)
samplerLiveData.value = true
Assert.assertEquals(3, testingLiveData.value)
verify(observer).onChanged(3)
samplerLiveData.value = true
sourceLiveData.value = 5
verifyNoMoreInteractions(observer)
}
@Test
fun `test LiveData sampleWith another live data to not emit when there are no new values`() {
val observer = Mockito.mock(Observer::class.java) as Observer<Int>
val sourceLiveData = MutableLiveData<Int>()
val samplerLiveData = MutableLiveData<Boolean>()
val testingLiveData = sourceLiveData.sampleWith(samplerLiveData)
testingLiveData.observeForever(observer)
samplerLiveData.value = true
samplerLiveData.value = true
samplerLiveData.value = true
Assert.assertNull(testingLiveData.value)
sourceLiveData.value = 5
samplerLiveData.value = true
Assert.assertEquals(5, testingLiveData.value)
verify(observer).onChanged(5)
verifyNoMoreInteractions(observer)
}
}
|
package homework2
import common.io.promptIntArray
fun <T> List<T>.removeDuplicates(): List<T> {
val lastIndices = this.zip(this.indices).toMap()
return this.filterIndexed { index, value -> index == lastIndices[value] }
}
fun main() {
val result = promptIntArray("Enter some integers, each on new line. Leave a line empty to stop:")
.removeDuplicates()
println("I have left only the last occurrence of each number:")
println(result)
}
|
;;;; duckdb.lisp
(in-package #:duckdb)
(defun get-message (p-string)
(foreign-string-to-lisp (mem-ref p-string '(:pointer :string))))
(define-condition duckdb-error (simple-error)
((database :initarg :database)
(statement :initarg :statement)
(appender :initarg :appender)
(arrow :initarg :arrow)
(error-message :initarg :error-message
:accessor error-message)))
;;; Databases
(defclass database ()
((handle :accessor handle)
(path :accessor path)))
(defmethod initialize-instance :after
((instance database) &key path)
(with-foreign-object (p-database '(:pointer duckdb-api:duckdb-database))
(with-foreign-object (p-error-message '(:pointer :string))
(let* ((path (or path ":memory:"))
;; prefer duckdb-open-ext over duckdb-open for error message
(result (duckdb-api:duckdb-open-ext path
p-database
(null-pointer)
p-error-message)))
(if (eq result :duckdb-success)
(setf (handle instance)
(mem-ref p-database 'duckdb-api:duckdb-database)
(path instance) path)
(error 'duckdb-error
:error-message (get-message p-error-message)))))))
(defun open-database (&optional path)
(make-instance 'database :path path))
(defun close-database (database)
(with-foreign-object (p-database '(:pointer duckdb-api:duckdb-database))
(setf (mem-ref p-database 'duckdb-api:duckdb-database)
(handle database))
(duckdb-api:duckdb-close p-database)))
(defmacro with-open-database ((database-var &optional path) &body body)
`(let ((,database-var (open-database ,path)))
(unwind-protect
,@body
(close-database ,database-var))))
;;; Connections
(defclass connection ()
((database :accessor database)
(handle :accessor handle)))
(defmethod initialize-instance :after
((instance connection) &key database)
(with-foreign-object (p-connection '(:pointer duckdb-api:duckdb-connection))
(let ((result (duckdb-api:duckdb-connect (handle database)
p-connection)))
(if (eq result :duckdb-success)
(setf (database instance) database
(handle instance)
(mem-ref p-connection 'duckdb-api:duckdb-connection))
(error 'duckdb-error :database database)))))
(defun connect (database)
(make-instance 'connection :database database))
(defun disconnect (connection)
(with-foreign-object (p-connection '(:pointer duckdb-api:duckdb-connection))
(setf (mem-ref p-connection 'duckdb-api:duckdb-connection)
(handle connection))
(duckdb-api:duckdb-disconnect p-connection)))
(defmacro with-open-connection ((connection-var database) &body body)
`(let ((,connection-var (connect ,database)))
(unwind-protect
,@body
(disconnect ,connection-var))))
;;; Queries
(defclass result ()
((connection :initarg :connection)
(handle :accessor handle :initarg :handle)
(column-count :accessor column-count :initarg :column-count)
(row-count :accessor row-count :initarg :row-count)
(rows-changed :initarg :rows-changed)
(error-message :initarg :error-message)))
(defun make-result (connection p-result)
(let ((column-count (duckdb-api:duckdb-column-count p-result))
(row-count (duckdb-api:duckdb-row-count p-result))
(rows-changed (duckdb-api:duckdb-rows-changed p-result))
(error-message (duckdb-api:duckdb-result-error p-result)))
(make-instance 'result
:connection connection
:handle p-result
:column-count column-count
:row-count row-count
:rows-changed rows-changed
:error-message error-message)))
(defun query (connection query)
(with-foreign-object (p-result 'duckdb-api:p-duckdb-result)
(with-foreign-string (p-query query)
(if (eq (duckdb-api:duckdb-query (handle connection)
p-query
p-result)
:duckdb-success)
(make-result connection p-result)
(error 'duckdb-error
:database (database connection)
:connection connection
:error-message (duckdb-api:duckdb-result-error p-result))))))
(defun destroy-result (result)
(duckdb-api:duckdb-destroy-result (handle result)))
(defmacro with-query ((result-var connection query) &body body)
`(let ((,result-var (query ,connection ,query)))
(unwind-protect
,@body
(destroy-result ,result-var))))
(defun get-column-values (result column-index)
(let* ((p-result (handle result))
(p-data (duckdb-api:duckdb-column-data p-result
column-index))
(p-nullmask (duckdb-api:duckdb-nullmask-data p-result
column-index))
(column-type (duckdb-api:duckdb-column-type p-result
column-index)))
(loop :for i :below (row-count result)
:collect (unless (mem-aref p-nullmask :bool i)
(mem-aref p-data
(duckdb-api:get-ffi-type column-type)
i)))))
#+nil
(let ((query (concatenate 'string
"SELECT True::boolean AS A"
", -12::tinyint AS B"
", -123::smallint AS C"
", -1234::integer AS D"
", -12345::bigint AS E"
", 12::utinyint AS F"
", 123::usmallint AS G"
", 1234::uinteger AS H"
", 12345::ubigint AS I"
", -18446744073709551629::hugeint AS J"
", 3.14::float AS K"
", 2.71::double AS L"
", 'Pálpusztai' AS cheese"
", '\\xAAAB'::blob AS bleb"
", current_date AS current_date"
", current_time AS current_time"
", now() AS current_typestamp"
", INTERVAL 24 HOURS "
"+ INTERVAL 2 MINUTES "
"+ INTERVAL 55 SECONDS AS i1"
", INTERVAL 6 MONTHS AS i2")))
(with-open-database (db)
(with-open-connection (conn db)
(with-query (result conn query)
(loop :for i :below (column-count result)
:collect (get-column-values result i))))))
|
-- | This module contains tests for "FreeC.Pass.LetSortPass".
module FreeC.Pass.LetSortPassTests ( testLetSortPass ) where
import Test.Hspec
import qualified FreeC.IR.Syntax as IR
import FreeC.Monad.Class.Testable
import FreeC.Monad.Reporter
import FreeC.Pass.LetSortPass
import FreeC.Test.Expectations
import FreeC.Test.Parser
-- | Test group for 'letSortPass' tests.
testLetSortPass :: Spec
testLetSortPass = describe "FreeC.Pass.LetSortPass" $ do
it "sorts `let`-bindings topologically" $ shouldSucceedWith $ do
input <- parseTestExpr "let { x = y; y = 42 } in x"
expectedOutput <- parseTestExpr "let { y = 42; x = y } in x"
output <- sortLetExprs input :: Reporter IR.Expr
return (output `shouldBeSimilarTo` expectedOutput)
it "leaves topologically sorted `let`-bindings unchanged"
$ shouldSucceedWith
$ do
input <- parseTestExpr "let { x = 42; y = x } in y"
output <- sortLetExprs input :: Reporter IR.Expr
return (output `shouldBeSimilarTo` input)
it "rejects recursive `let`-bindings" $ do
input <- expectParseTestExpr "let { x = x } in x"
shouldFailPretty $ do
sortLetExprs input :: Reporter IR.Expr
it "rejects mutually recursive `let`-bindings" $ do
input <- expectParseTestExpr "let { x = y; y = x } in y"
shouldFailPretty $ do
sortLetExprs input :: Reporter IR.Expr
|
/**
* Copyright 2021-2022 Nicola Vitucci
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datagrafting.sql2sparql.calcite.rel;
import java.util.ArrayList;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelOptRule;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.core.TableScan;
public class SparqlPropTableScan extends TableScan implements SparqlPropRel {
private String tableName;
private String prop;
public SparqlPropTableScan(RelOptCluster cluster, RelTraitSet traitSet, RelOptTable relOptTable,
String tableName, String prop) {
super(cluster, traitSet, new ArrayList<>(), relOptTable);
this.tableName = tableName;
this.prop = prop;
assert getConvention() == SparqlPropRel.CONVENTION;
}
@Override
public void register(RelOptPlanner planner) {
// for (RelOptRule rule : planner.getRules()) {
// planner.removeRule(rule);
// }
// E.g. or removing rule:
// planner.removeRule(ReduceExpressionsRule.FilterReduceExpressionsRule.Config.DEFAULT.toRule());
planner.addRule(SparqlPropToEnumerableConverterRule.INSTANCE);
for (RelOptRule rule : SparqlPropRules.RULES) {
planner.addRule(rule);
}
}
@Override
public void implement(Implementor implementor) {
implementor.table = table;
implementor.props.put(this.tableName, this.prop);
}
}
|
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_shop/router/application.dart';
class Recommend extends StatelessWidget {
final List recommend;
const Recommend({Key key, this.recommend}) : super(key: key);
//推荐的标题
Widget _titleWidget() {
return Container(
child: Text(
'商品推荐',
style: TextStyle(fontSize: ScreenUtil().setSp(30), color: Colors.pink),
),
alignment: Alignment.centerLeft,
padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
height: ScreenUtil().setHeight(60),
decoration: BoxDecoration(
color: Colors.white,
border:
Border(bottom: BorderSide(color: Colors.black12, width: 0.5))),
);
}
//推荐的item项
Widget _recommendItem(BuildContext context, int index) {
return InkWell(
onTap: () {
Application.router.navigateTo(
context, "/detail?id=${recommend[index]['goodsId']}",
transition: TransitionType.cupertino);
},
child: Container(
height: ScreenUtil().setHeight(300),
width: ScreenUtil().setWidth(250),
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
color: Colors.white,
border:
Border(left: BorderSide(width: 0.5, color: Colors.black12))),
child: Column(
children: <Widget>[
Container(
height: ScreenUtil().setHeight(160),
child: Image.network(recommend[index]['image']),
),
Text('¥${recommend[index]['mallPrice']}'),
Text(
'¥${recommend[index]['price']}',
style: TextStyle(
decoration: TextDecoration.lineThrough, color: Colors.grey),
)
],
),
),
);
}
//推荐页,横向列表页面
Widget _recommendListView() {
return Container(
height: ScreenUtil().setHeight(280),
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: recommend.length,
itemBuilder: (context, index) {
return _recommendItem(context, index);
},
),
);
}
@override
Widget build(BuildContext context) {
return Container(
height: ScreenUtil().setHeight(360),
margin: EdgeInsets.only(top: 10.0),
child: Column(
children: <Widget>[_titleWidget(), _recommendListView()],
),
);
}
}
|
'use strict';
export default function(sequelize, DataTypes) {
var AuthGithub = sequelize.define(
'AuthGithub',
{
gh_id: { type: DataTypes.STRING, unique: true },
display_name: DataTypes.STRING
},
{ timestamps: true, freezeTableName: true, underscored: true }
);
AuthGithub.associate = function(models) {
models.AuthGithub.belongsTo(models.User, {
foreignKey: 'user_id'
});
};
return AuthGithub;
}
|
using Microsoft.AspNet.Mvc;
namespace Library.WebApi.Controllers
{
[ApiExplorerSettings(IgnoreApi = true)]
public class RootController : Controller
{
public IActionResult Get()
{
//return Redirect( Request.RequestUri.AbsoluteUri + "swagger/ui/index" );
return Redirect(Request.PathBase.ToUriComponent() + "swagger/ui/index");
}
}
}
|
import { Lisan } from 'lisan';
import { Loader } from '../../src';
describe('lisan-plugin-loader > on node', () => {
let lisanInstance;
beforeEach(() => {
lisanInstance = new Lisan();
});
it('should require the js file', () => {
lisanInstance.use(
Loader({
dictionaryUrlFn: dictionaryName =>
`${__dirname}/../data/${dictionaryName}.js`,
}),
);
lisanInstance.load('example.lisan');
expect(lisanInstance.t('anInterpolation', { name: 'John' })).toBe(
'Hello John',
);
});
/**
* @jest-environment jsdom
*/
it('should load the js file', () => {
lisanInstance.use(
Loader({
dictionaryUrlFn: dictionaryName =>
`${__dirname}/../data/${dictionaryName}.js`,
}),
);
lisanInstance.load('example.lisan');
expect(lisanInstance.t('anInterpolation', { name: 'John' })).toBe(
'Hello John',
);
});
});
|
module Eventuria.Libraries.CQRS.Write.Aggregate.Core where
import Eventuria.Libraries.CQRS.Write.Aggregate.Ids.AggregateId
class AggregateJoinable item where {
getAggregateId :: item -> AggregateId
}
|
import {
workspace,
window,
commands,
extensions,
ExtensionContext,
StatusBarAlignment,
TextEditor,
WorkspaceFolder,
QuickPickItem,
WorkspaceConfiguration,
Uri,
languages,
TextDocument,
Range,
TextEdit
} from "vscode";
import * as path from "path";
import * as nls from "vscode-nls";
import execa from "execa";
import { outputChannel } from "./output";
import {
isTypeScriptDocument,
isJavaScriptDocument,
getVersions,
generateDtsForDeno,
downloadDtsForDeno
} from "./utils";
const typeScriptExtensionId = "vscode.typescript-language-features";
const denoExtensionId = "justjavac.vscode-deno";
const pluginId = "typescript-deno-plugin";
const configurationSection = "deno";
const localize = nls.loadMessageBundle();
enum Status {
ok = 1,
warn = 2,
error = 3
}
interface StatusParams {
state: Status;
}
interface WorkspaceFolderItem extends QuickPickItem {
folder: WorkspaceFolder;
}
async function pickFolder(
folders: WorkspaceFolder[],
placeHolder: string
): Promise<WorkspaceFolder> {
if (folders.length === 1) {
return Promise.resolve(folders[0]);
}
const selected = await window.showQuickPick(
folders.map<WorkspaceFolderItem>(folder => {
return {
label: folder.name,
description: folder.uri.fsPath,
folder: folder
};
}),
{ placeHolder: placeHolder }
);
if (!selected) {
return undefined;
}
return selected.folder;
}
function enable() {
let folders = workspace.workspaceFolders;
if (!folders) {
window.showWarningMessage(
"Deno can only be enabled if VS Code is opened on a workspace folder."
);
return;
}
let disabledFolders = folders.filter(
folder =>
!workspace
.getConfiguration(configurationSection, folder.uri)
.get("enable", true)
);
if (disabledFolders.length === 0) {
if (folders.length === 1) {
window.showInformationMessage(
"Deno is already enabled in the workspace."
);
} else {
window.showInformationMessage(
"Deno is already enabled on all workspace folders."
);
}
return;
}
pickFolder(
disabledFolders,
"Select a workspace folder to enable Deno for"
).then(folder => {
if (!folder) {
return;
}
workspace
.getConfiguration(configurationSection, folder.uri)
.update("enable", true);
});
}
function disable() {
let folders = workspace.workspaceFolders;
if (!folders) {
window.showErrorMessage(
"Deno can only be disabled if VS Code is opened on a workspace folder."
);
return;
}
let enabledFolders = folders.filter(folder =>
workspace
.getConfiguration(configurationSection, folder.uri)
.get("enable", true)
);
if (enabledFolders.length === 0) {
if (folders.length === 1) {
window.showInformationMessage(
"Deno is already disabled in the workspace."
);
} else {
window.showInformationMessage(
"Deno is already disabled on all workspace folders."
);
}
return;
}
pickFolder(
enabledFolders,
"Select a workspace folder to disable Deno for"
).then(folder => {
if (!folder) {
return;
}
workspace.getConfiguration("deno", folder.uri).update("enable", false);
});
}
interface SynchronizedConfiguration {
alwaysShowStatus?: boolean;
autoFmtOnSave?: boolean;
enable?: boolean;
dtsPath?: string;
}
export async function activate(context: ExtensionContext) {
const extension = extensions.getExtension(typeScriptExtensionId);
if (!extension) {
return;
}
await extension.activate();
if (!extension.exports || !extension.exports.getAPI) {
return;
}
const api = extension.exports.getAPI(0);
if (!api) {
return;
}
const configurationListener = workspace.onDidChangeConfiguration(
e => {
if (e.affectsConfiguration(configurationSection)) {
synchronizeConfiguration(api);
updateStatusBarVisibility(window.activeTextEditor);
}
},
undefined,
context.subscriptions
);
const formatter = languages.registerDocumentFormattingEditProvider(
["typescript", "javascript", "markdown", "json"],
{
async provideDocumentFormattingEdits(document: TextDocument) {
if (document.isUntitled) {
return;
}
await document.save();
const filename = path.basename(document.uri.fsPath);
const cwd = path.dirname(document.uri.fsPath);
const r = await execa(
"deno",
[
"run",
"--allow-read",
"https://deno.land/std/prettier/main.ts",
filename
],
{ cwd }
);
const fullRange = new Range(
document.positionAt(0),
document.positionAt(document.getText().length - 1)
);
return [new TextEdit(fullRange, r.stdout)];
}
}
);
synchronizeConfiguration(api);
const disposables = [
configurationListener,
formatter,
commands.registerCommand("deno.enable", enable),
commands.registerCommand("deno.disable", disable),
commands.registerCommand("deno.showOutputChannel", async () => {
if (denoStatus === Status.ok) {
outputChannel.show();
return;
}
const show = localize("showOutputChannel", "Show Output");
const help = localize("getHelp", "Get Help");
const choice = await window.showWarningMessage(
localize(
"notfound",
"Deno not found. Install it by using deno_install or click {0} button for more help.",
help
),
show,
help
);
if (choice === show) {
outputChannel.show();
} else if (choice === help) {
commands.executeCommand(
"vscode.open",
Uri.parse("https://github.com/denoland/deno_install")
);
}
})
];
context.subscriptions.push(...disposables, outputChannel);
const statusBarItem = window.createStatusBarItem(StatusBarAlignment.Right, 0);
let denoStatus: Status = Status.ok;
statusBarItem.text = "Deno";
statusBarItem.command = "deno.showOutputChannel";
const versions = await getVersions();
if (versions === undefined) {
denoStatus = Status.warn;
statusBarItem.tooltip = "Deno is not installed";
outputChannel.appendLine("Failed to detect Deno.");
outputChannel.appendLine("You can use one-line commands to install Deno.");
if (process.platform === "win32") {
outputChannel.appendLine(
"> iwr https://deno.land/x/install/install.ps1 | iex"
);
} else {
outputChannel.appendLine(
"> curl -fsSL https://deno.land/x/install/install.sh | sh"
);
}
outputChannel.appendLine(
"See https://github.com/denoland/deno_install for more installation options.\n"
);
downloadDtsForDeno();
} else {
statusBarItem.tooltip = versions.raw;
outputChannel.appendLine("Found deno, version:");
outputChannel.appendLine(versions.raw);
generateDtsForDeno();
}
function showStatusBarItem(show: boolean): void {
if (show) {
statusBarItem.show();
} else {
statusBarItem.hide();
}
}
function updateStatus(status: Status) {
if (denoStatus !== Status.ok && status === Status.ok) {
// an error got addressed fix, write to the output that the status is OK
// client.info("vscode-deno: Status is OK");
}
denoStatus = status;
updateStatusBarVisibility(window.activeTextEditor);
}
function updateStatusBarVisibility(editor: TextEditor | undefined): void {
switch (denoStatus) {
case Status.ok:
statusBarItem.text = `Deno ${versions.deno}`;
break;
case Status.warn:
statusBarItem.text = "$(alert) Deno";
break;
case Status.error:
statusBarItem.text = "$(issue-opened) Deno";
break;
default:
statusBarItem.text = `Deno ${versions.deno}`;
}
let uri = editor ? editor.document.uri : undefined;
let enabled = workspace.getConfiguration("deno", uri)["enable"];
let alwaysShowStatus = workspace.getConfiguration("deno", uri)[
"alwaysShowStatus"
];
if (
!editor ||
!enabled ||
(denoStatus === Status.ok && !alwaysShowStatus)
) {
showStatusBarItem(false);
return;
}
showStatusBarItem(
isTypeScriptDocument(editor.document) ||
isJavaScriptDocument(editor.document)
);
}
window.onDidChangeActiveTextEditor(updateStatusBarVisibility);
updateStatusBarVisibility(window.activeTextEditor);
}
export function deactivate() {}
function synchronizeConfiguration(api: any) {
const config = getConfiguration();
if (!config.dtsPath) {
config.dtsPath = bundledDtsPath();
}
api.configurePlugin(pluginId, config);
}
function getConfiguration(): SynchronizedConfiguration {
const config = workspace.getConfiguration(configurationSection);
const outConfig: SynchronizedConfiguration = {};
withConfigValue(config, outConfig, "enable");
withConfigValue(config, outConfig, "alwaysShowStatus");
withConfigValue(config, outConfig, "autoFmtOnSave");
withConfigValue(config, outConfig, "dtsPath");
return outConfig;
}
function withConfigValue<C, K extends Extract<keyof C, string>>(
config: WorkspaceConfiguration,
outConfig: C,
key: K
): void {
const configSetting = config.inspect<C[K]>(key);
if (!configSetting) {
return;
}
// Make sure the user has actually set the value.
// VS Code will return the default values instead of `undefined`, even if user has not don't set anything.
if (
typeof configSetting.globalValue === "undefined" &&
typeof configSetting.workspaceFolderValue === "undefined" &&
typeof configSetting.workspaceValue === "undefined"
) {
return;
}
const value = config.get<C[K] | undefined>(key, undefined);
if (typeof value !== "undefined") {
outConfig[key] = value;
}
}
function bundledDtsPath(): string {
const { extensionPath } = extensions.getExtension(denoExtensionId);
return path.resolve(
extensionPath,
"node_modules",
"typescript-deno-plugin",
"lib",
"lib.deno_runtime.d.ts"
);
}
|
using Globalmantics.DAL;
using Globalmantics.DAL.Migrations;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Globalmantics.IntegrationTests
{
[SetUpFixture]
public class TestSetup
{
[OneTimeSetUp]
public void SetUpDatabase()
{
DestroyDatabase();
CreateDatabase();
}
[OneTimeTearDown]
public void TearDownDatabase()
{
DestroyDatabase();
}
private static void CreateDatabase()
{
ExecuteSqlCommand(Master, $@"
CREATE DATABASE [Globalmantics]
ON (NAME = 'Globalmantics',
FILENAME = '{Filename}')");
var migration = new MigrateDatabaseToLatestVersion<
GlobalmanticsContext, GlobalmanticsConfiguration>();
migration.InitializeDatabase(new GlobalmanticsContext());
}
private static void DestroyDatabase()
{
var fileNames = ExecuteSqlQuery(Master, @"
SELECT [physical_name] FROM [sys].[master_files]
WHERE [database_id] = DB_ID('Globalmantics')",
row => (string)row["physical_name"]);
if (fileNames.Any())
{
ExecuteSqlCommand(Master, @"
ALTER DATABASE [Globalmantics] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
EXEC sp_detach_db 'Globalmantics'");
fileNames.ForEach(File.Delete);
}
}
private static void ExecuteSqlCommand(
SqlConnectionStringBuilder connectionStringBuilder,
string commandText)
{
using (var connection = new SqlConnection(connectionStringBuilder.ConnectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = commandText;
command.ExecuteNonQuery();
}
}
}
private static List<T> ExecuteSqlQuery<T>(
SqlConnectionStringBuilder connectionStringBuilder,
string queryText,
Func<SqlDataReader, T> read)
{
var result = new List<T>();
using (var connection = new SqlConnection(connectionStringBuilder.ConnectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = queryText;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
result.Add(read(reader));
}
}
}
}
return result;
}
private static SqlConnectionStringBuilder Master =>
new SqlConnectionStringBuilder
{
DataSource = @"(LocalDB)\MSSQLLocalDB",
InitialCatalog = "master",
IntegratedSecurity = true
};
private static string Filename => Path.Combine(
Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location),
"Globalmantics.mdf");
}
}
|
/*
* Copyright 2011-2017 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdlib.h>
#include <string.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include "rand_lcl.h"
#include "internal/thread_once.h"
/*
* Mapping of NIST SP 800-90A DRBG to OpenSSL RAND_METHOD.
*/
/*
* The default global DRBG and its auto-init/auto-cleanup.
*/
static DRBG_CTX ossl_drbg;
static CRYPTO_ONCE ossl_drbg_init = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(do_ossl_drbg_init)
{
int st = 1;
ossl_drbg.lock = CRYPTO_THREAD_lock_new();
st &= ossl_drbg.lock != NULL;
st &= RAND_DRBG_set(&ossl_drbg, NID_aes_128_ctr, 0) == 1;
return st;
}
void rand_drbg_cleanup(void)
{
CRYPTO_THREAD_lock_free(ossl_drbg.lock);
}
static void inc_128(DRBG_CTR_CTX *cctx)
{
int i;
unsigned char c;
unsigned char *p = &cctx->V[15];
for (i = 0; i < 16; i++, p--) {
c = *p;
c++;
*p = c;
if (c != 0) {
/* If we didn't wrap around, we're done. */
break;
}
}
}
static void ctr_XOR(DRBG_CTR_CTX *cctx, const unsigned char *in, size_t inlen)
{
size_t i, n;
if (in == NULL || inlen == 0)
return;
/*
* Any zero padding will have no effect on the result as we
* are XORing. So just process however much input we have.
*/
n = inlen < cctx->keylen ? inlen : cctx->keylen;
for (i = 0; i < n; i++)
cctx->K[i] ^= in[i];
if (inlen <= cctx->keylen)
return;
n = inlen - cctx->keylen;
if (n > 16) {
/* Should never happen */
n = 16;
}
for (i = 0; i < n; i++)
cctx->V[i] ^= in[i + cctx->keylen];
}
/*
* Process a complete block using BCC algorithm of SP 800-90A 10.3.3
*/
static void ctr_BCC_block(DRBG_CTR_CTX *cctx, unsigned char *out,
const unsigned char *in)
{
int i;
for (i = 0; i < 16; i++)
out[i] ^= in[i];
AES_encrypt(out, out, &cctx->df_ks);
}
/*
* Handle several BCC operations for as much data as we need for K and X
*/
static void ctr_BCC_blocks(DRBG_CTR_CTX *cctx, const unsigned char *in)
{
ctr_BCC_block(cctx, cctx->KX, in);
ctr_BCC_block(cctx, cctx->KX + 16, in);
if (cctx->keylen != 16)
ctr_BCC_block(cctx, cctx->KX + 32, in);
}
/*
* Initialise BCC blocks: these have the value 0,1,2 in leftmost positions:
* see 10.3.1 stage 7.
*/
static void ctr_BCC_init(DRBG_CTR_CTX *cctx)
{
memset(cctx->KX, 0, 48);
memset(cctx->bltmp, 0, 16);
ctr_BCC_block(cctx, cctx->KX, cctx->bltmp);
cctx->bltmp[3] = 1;
ctr_BCC_block(cctx, cctx->KX + 16, cctx->bltmp);
if (cctx->keylen != 16) {
cctx->bltmp[3] = 2;
ctr_BCC_block(cctx, cctx->KX + 32, cctx->bltmp);
}
}
/*
* Process several blocks into BCC algorithm, some possibly partial
*/
static void ctr_BCC_update(DRBG_CTR_CTX *cctx,
const unsigned char *in, size_t inlen)
{
if (in == NULL || inlen == 0)
return;
/* If we have partial block handle it first */
if (cctx->bltmp_pos) {
size_t left = 16 - cctx->bltmp_pos;
/* If we now have a complete block process it */
if (inlen >= left) {
memcpy(cctx->bltmp + cctx->bltmp_pos, in, left);
ctr_BCC_blocks(cctx, cctx->bltmp);
cctx->bltmp_pos = 0;
inlen -= left;
in += left;
}
}
/* Process zero or more complete blocks */
for (; inlen >= 16; in += 16, inlen -= 16) {
ctr_BCC_blocks(cctx, in);
}
/* Copy any remaining partial block to the temporary buffer */
if (inlen > 0) {
memcpy(cctx->bltmp + cctx->bltmp_pos, in, inlen);
cctx->bltmp_pos += inlen;
}
}
static void ctr_BCC_final(DRBG_CTR_CTX *cctx)
{
if (cctx->bltmp_pos) {
memset(cctx->bltmp + cctx->bltmp_pos, 0, 16 - cctx->bltmp_pos);
ctr_BCC_blocks(cctx, cctx->bltmp);
}
}
static void ctr_df(DRBG_CTR_CTX *cctx,
const unsigned char *in1, size_t in1len,
const unsigned char *in2, size_t in2len,
const unsigned char *in3, size_t in3len)
{
static unsigned char c80 = 0x80;
size_t inlen;
unsigned char *p = cctx->bltmp;
ctr_BCC_init(cctx);
if (in1 == NULL)
in1len = 0;
if (in2 == NULL)
in2len = 0;
if (in3 == NULL)
in3len = 0;
inlen = in1len + in2len + in3len;
/* Initialise L||N in temporary block */
*p++ = (inlen >> 24) & 0xff;
*p++ = (inlen >> 16) & 0xff;
*p++ = (inlen >> 8) & 0xff;
*p++ = inlen & 0xff;
/* NB keylen is at most 32 bytes */
*p++ = 0;
*p++ = 0;
*p++ = 0;
*p = (unsigned char)((cctx->keylen + 16) & 0xff);
cctx->bltmp_pos = 8;
ctr_BCC_update(cctx, in1, in1len);
ctr_BCC_update(cctx, in2, in2len);
ctr_BCC_update(cctx, in3, in3len);
ctr_BCC_update(cctx, &c80, 1);
ctr_BCC_final(cctx);
/* Set up key K */
AES_set_encrypt_key(cctx->KX, cctx->keylen * 8, &cctx->df_kxks);
/* X follows key K */
AES_encrypt(cctx->KX + cctx->keylen, cctx->KX, &cctx->df_kxks);
AES_encrypt(cctx->KX, cctx->KX + 16, &cctx->df_kxks);
if (cctx->keylen != 16)
AES_encrypt(cctx->KX + 16, cctx->KX + 32, &cctx->df_kxks);
}
/*
* NB the no-df Update in SP800-90A specifies a constant input length
* of seedlen, however other uses of this algorithm pad the input with
* zeroes if necessary and have up to two parameters XORed together,
* handle both cases in this function instead.
*/
static void ctr_update(DRBG_CTX *dctx,
const unsigned char *in1, size_t in1len,
const unsigned char *in2, size_t in2len,
const unsigned char *nonce, size_t noncelen)
{
DRBG_CTR_CTX *cctx = &dctx->ctr;
/* ks is already setup for correct key */
inc_128(cctx);
AES_encrypt(cctx->V, cctx->K, &cctx->ks);
/* If keylen longer than 128 bits need extra encrypt */
if (cctx->keylen != 16) {
inc_128(cctx);
AES_encrypt(cctx->V, cctx->K + 16, &cctx->ks);
}
inc_128(cctx);
AES_encrypt(cctx->V, cctx->V, &cctx->ks);
/* If 192 bit key part of V is on end of K */
if (cctx->keylen == 24) {
memcpy(cctx->V + 8, cctx->V, 8);
memcpy(cctx->V, cctx->K + 24, 8);
}
if (dctx->flags & RAND_DRBG_FLAG_CTR_USE_DF) {
/* If no input reuse existing derived value */
if (in1 != NULL || nonce != NULL || in2 != NULL)
ctr_df(cctx, in1, in1len, nonce, noncelen, in2, in2len);
/* If this a reuse input in1len != 0 */
if (in1len)
ctr_XOR(cctx, cctx->KX, dctx->seedlen);
} else {
ctr_XOR(cctx, in1, in1len);
ctr_XOR(cctx, in2, in2len);
}
AES_set_encrypt_key(cctx->K, dctx->strength, &cctx->ks);
}
int ctr_instantiate(DRBG_CTX *dctx,
const unsigned char *ent, size_t entlen,
const unsigned char *nonce, size_t noncelen,
const unsigned char *pers, size_t perslen)
{
DRBG_CTR_CTX *cctx = &dctx->ctr;
memset(cctx->K, 0, sizeof(cctx->K));
memset(cctx->V, 0, sizeof(cctx->V));
AES_set_encrypt_key(cctx->K, dctx->strength, &cctx->ks);
ctr_update(dctx, ent, entlen, pers, perslen, nonce, noncelen);
return 1;
}
int ctr_reseed(DRBG_CTX *dctx,
const unsigned char *ent, size_t entlen,
const unsigned char *adin, size_t adinlen)
{
ctr_update(dctx, ent, entlen, adin, adinlen, NULL, 0);
return 1;
}
int ctr_generate(DRBG_CTX *dctx,
unsigned char *out, size_t outlen,
const unsigned char *adin, size_t adinlen)
{
DRBG_CTR_CTX *cctx = &dctx->ctr;
if (adin != NULL && adinlen != 0) {
ctr_update(dctx, adin, adinlen, NULL, 0, NULL, 0);
/* This means we reuse derived value */
if (dctx->flags & RAND_DRBG_FLAG_CTR_USE_DF) {
adin = NULL;
adinlen = 1;
}
} else {
adinlen = 0;
}
for ( ; ; ) {
inc_128(cctx);
if (outlen < 16) {
/* Use K as temp space as it will be updated */
AES_encrypt(cctx->V, cctx->K, &cctx->ks);
memcpy(out, cctx->K, outlen);
break;
}
AES_encrypt(cctx->V, out, &cctx->ks);
out += 16;
outlen -= 16;
if (outlen == 0)
break;
}
ctr_update(dctx, adin, adinlen, NULL, 0, NULL, 0);
return 1;
}
int ctr_uninstantiate(DRBG_CTX *dctx)
{
memset(&dctx->ctr, 0, sizeof(dctx->ctr));
return 1;
}
int ctr_init(DRBG_CTX *dctx)
{
DRBG_CTR_CTX *cctx = &dctx->ctr;
size_t keylen;
switch (dctx->nid) {
default:
/* This can't happen, but silence the compiler warning. */
return -1;
case NID_aes_128_ctr:
keylen = 16;
break;
case NID_aes_192_ctr:
keylen = 24;
break;
case NID_aes_256_ctr:
keylen = 32;
break;
}
cctx->keylen = keylen;
dctx->strength = keylen * 8;
dctx->blocklength = 16;
dctx->seedlen = keylen + 16;
if (dctx->flags & RAND_DRBG_FLAG_CTR_USE_DF) {
/* df initialisation */
static unsigned char df_key[32] = {
0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,
0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,
0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,
0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f
};
/* Set key schedule for df_key */
AES_set_encrypt_key(df_key, dctx->strength, &cctx->df_ks);
dctx->min_entropy = cctx->keylen;
dctx->max_entropy = DRBG_MAX_LENGTH;
dctx->min_nonce = dctx->min_entropy / 2;
dctx->max_nonce = DRBG_MAX_LENGTH;
dctx->max_pers = DRBG_MAX_LENGTH;
dctx->max_adin = DRBG_MAX_LENGTH;
} else {
dctx->min_entropy = dctx->seedlen;
dctx->max_entropy = dctx->seedlen;
/* Nonce not used */
dctx->min_nonce = 0;
dctx->max_nonce = 0;
dctx->max_pers = dctx->seedlen;
dctx->max_adin = dctx->seedlen;
}
dctx->max_request = 1 << 16;
dctx->reseed_interval = MAX_RESEED;
return 1;
}
/*
* The following function tie the DRBG code into the RAND_METHOD
*/
DRBG_CTX *RAND_DRBG_get_default(void)
{
if (!RUN_ONCE(&ossl_drbg_init, do_ossl_drbg_init))
return NULL;
return &ossl_drbg;
}
static int drbg_bytes(unsigned char *out, int count)
{
DRBG_CTX *dctx = RAND_DRBG_get_default();
int ret = 0;
CRYPTO_THREAD_write_lock(dctx->lock);
do {
size_t rcnt;
if (count > (int)dctx->max_request)
rcnt = dctx->max_request;
else
rcnt = count;
ret = RAND_DRBG_generate(dctx, out, rcnt, 0, NULL, 0);
if (!ret)
goto err;
out += rcnt;
count -= rcnt;
} while (count);
ret = 1;
err:
CRYPTO_THREAD_unlock(dctx->lock);
return ret;
}
static int drbg_status(void)
{
DRBG_CTX *dctx = RAND_DRBG_get_default();
int ret;
CRYPTO_THREAD_write_lock(dctx->lock);
ret = dctx->status == DRBG_STATUS_READY ? 1 : 0;
CRYPTO_THREAD_unlock(dctx->lock);
return ret;
}
static void drbg_cleanup(void)
{
DRBG_CTX *dctx = RAND_DRBG_get_default();
CRYPTO_THREAD_write_lock(dctx->lock);
RAND_DRBG_uninstantiate(dctx);
CRYPTO_THREAD_unlock(dctx->lock);
}
static const RAND_METHOD rand_drbg_meth =
{
NULL,
drbg_bytes,
drbg_cleanup,
NULL,
drbg_bytes,
drbg_status
};
const RAND_METHOD *RAND_drbg(void)
{
return &rand_drbg_meth;
}
|
/*
* MIT License
*
* Copyright (c) 2021 akanchi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "mp4_demuxer.hpp"
#include <iostream>
#include <stack>
#include <tuple>
#include "file_stream/file_stream.hpp"
#include "boxs/box.hpp"
#include "common/common.hpp"
namespace akanchi
{
Mp4Demuxer::Mp4Demuxer(/* args */)
: root(new Box())
{
}
Mp4Demuxer::~Mp4Demuxer()
{
}
int Mp4Demuxer::decode(FileStreamBuffer *inSb)
{
root->start = 0;
root->size = inSb->size();
Box *tmpRoot = root.get();
std::stack<Box*> parentStack;
parentStack.push(tmpRoot);
Box *mdhd = nullptr;
while (!inSb->empty())
{
Box *box = Box::create_box(inSb);
if (!box) {
std::cout << "can't create box!" << std::endl;
return -1;
}
if (ascii_from(box->type) == "stsd") {
BoxStsd *stsdBox = dynamic_cast<BoxStsd*>(box);
uint32_t codec_id = stsdBox->get_codec_id();
TrackContext *track = TrackContext::create_track_context(codec_id);
if (track) {
contexts[codec_id] = std::shared_ptr<TrackContext>(track);
contexts[codec_id]->stbl = tmpRoot;
contexts[codec_id]->sb = inSb;
if (BoxMdhd *tmp = dynamic_cast<BoxMdhd*>(mdhd)) {
contexts[codec_id]->mdhd = tmp;
}
} else {
std::cout << "Unknown codec!" << std::endl;
}
} else if (ascii_from(box->type) == "mdhd") {
mdhd = box;
}
tmpRoot->append(box);
if (is_container_box(box->type)) {
tmpRoot = box;
parentStack.push(tmpRoot);
continue;
} else {
int end_pos = box->start + box->size;
inSb->skip(end_pos - inSb->pos());
while (!parentStack.empty()) {
if (box->start + box->size >= tmpRoot->start + tmpRoot->size) {
parentStack.pop();
if (parentStack.empty()) {
break;
}
tmpRoot = parentStack.top();
} else {
break;
}
}
}
}
return 0;
}
bool Mp4Demuxer::is_container_box(uint32_t type)
{
std::string type_string = ascii_from(type);
return type_string == "moov" ||
type_string == "trak" ||
type_string == "edts" ||
type_string == "mdia" ||
type_string == "meta" ||
type_string == "minf" ||
type_string == "stbl" ||
type_string == "dinf" ||
type_string == "udta";
}
int Mp4Demuxer::extract()
{
for (auto it = contexts.begin(); it != contexts.end(); it++) {
it->second->extract();
}
return 0;
}
int Mp4Demuxer::print()
{
return print_recursive(root.get(), "");
}
int Mp4Demuxer::print_recursive(Box *box, std::string prefix)
{
if (!box) {
return -1;
}
std::cout << box->description(prefix) << std::endl;
for (auto it = box->childs.begin(); it != box->childs.end(); it++) {
print_recursive(it->get(), prefix + " ");
}
return 0;
}
}
|
<?php
require_once('db_config.php');
require_once('function.php');
$fname = $_POST['fname'];
$lname=$_POST['lname'];
$email =$_POST['email'];
$birthday =$_POST['birthday'];
$gender =$_POST['gender'];
$userid=$_POST['userid'];
$usertype=$_POST['usertype'];
foreach($fname as $key=>$firstname ){
$sqlupdate="UPDATE `user` SET `FirstName` ='".$fname[$key]."', `LastName`='".$lname[$key]."'
, `email` ='".$email[$key]."', `Birthday` ='".$birthday[$key]."',
`Gender` ='".$gender[$key]."',`UserType` ='".$usertype[$key]."' WHERE `UserID` = ".$userid[$key];
$result=mysqli_query($db_conn,$sqlupdate);
}
// exit;
$to="manage_user.php";
if ($result>0){
//delete Success
$msg="Update was Success";
}else{
//delete failure
$msg="Update is not successful";
}
goto2($to,$msg);
?>
|
#!/bin/sh
cat <<__EOF__ > PWD
UID=${TDSPWDUID}
PWD=${TDSPWDPWD}
SRV=${TDSPWDSRV}
DB=${TDSPWDDB}
__EOF__
|
<?php
return [
'required_choices' => 5,
'gdpr_anonymise_after' => 365,
'gdpr_contact' => env('GDPR_CONTACT'),
'wlm_api_url' => env('OLD_API_URL'),
];
|
export const getQuicksortAnimations = (array) => {
let animations = [];
let auxArray = array.slice();
quicksort(auxArray, 0, auxArray.length - 1, animations);
return animations;
};
function quicksort(array, start, end, animations) {
if (start < end) {
let pIndex = partition(array, start, end, animations);
quicksort(array, start, pIndex - 1, animations);
quicksort(array, pIndex + 1, end, animations);
}
}
function swap(array, index1, index2) {
let tmp = array[index2];
array[index2] = array[index1];
array[index1] = tmp;
}
function partition(array, start, end, animations) {
let pivot = array[end];
let pIndex = start;
for (let i = start; i < end; i++) {
animations.push(["comparing", pIndex, i, end]);
if (array[i] <= pivot) {
animations.push(["swapping", pIndex, i, end]);
swap(array, i, pIndex);
pIndex++;
}
}
swap(array, pIndex, end);
animations.push(["swapping", pIndex, end, end]);
return pIndex;
}
|
/*
* bakufu
*
* Copyright (c) 2016 STNMRSHX
* Licensed under the WTFPL license.
*/
package ssl
import (
"crypto/tls"
"crypto/x509"
"errors"
"io/ioutil"
nethttp "net/http"
"strings"
"github.com/go-martini/martini"
"github.com/stnmrshx/golib/log"
"github.com/stnmrshx/bakufu/go/config"
)
var cipherSuites = []uint16{
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
}
func HasString(elem string, arr []string) bool {
for _, s := range arr {
if s == elem {
return true
}
}
return false
}
func NewTLSConfig(caFile string, mutualTLS bool) (*tls.Config, error) {
var c tls.Config
c.MinVersion = tls.VersionTLS12
c.CipherSuites = cipherSuites
c.PreferServerCipherSuites = true
if mutualTLS {
log.Info("MutualTLS requested, client certificates will be verified")
c.ClientAuth = tls.VerifyClientCertIfGiven
}
if caFile != "" {
data, err := ioutil.ReadFile(caFile)
if err != nil {
return &c, err
}
c.ClientCAs = x509.NewCertPool()
if !c.ClientCAs.AppendCertsFromPEM(data) {
return &c, errors.New("No certificates parsed")
}
log.Info("Read in CA file:", caFile)
}
c.BuildNameToCertificate()
return &c, nil
}
func Verify(r *nethttp.Request, validOUs []string) error {
if strings.Contains(r.URL.String(), config.Config.StatusEndpoint) && !config.Config.StatusOUVerify {
return nil
}
if r.TLS == nil {
return errors.New("No TLS")
}
for _, chain := range r.TLS.VerifiedChains {
s := chain[0].Subject.OrganizationalUnit
log.Debug("All OUs:", strings.Join(s, " "))
for _, ou := range s {
log.Debug("Client presented OU:", ou)
if HasString(ou, validOUs) {
log.Debug("Found valid OU:", ou)
return nil
}
}
}
log.Error("No valid OUs found")
return errors.New("Invalid OU")
}
func VerifyOUs(validOUs []string) martini.Handler {
return func(res nethttp.ResponseWriter, req *nethttp.Request, c martini.Context) {
log.Debug("Verifying client OU")
if err := Verify(req, validOUs); err != nil {
nethttp.Error(res, err.Error(), nethttp.StatusUnauthorized)
}
}
}
func AppendKeyPair(tlsConfig *tls.Config, certFile string, keyFile string) error {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
return nil
}
func ListenAndServeTLS(addr string, handler nethttp.Handler, tlsConfig *tls.Config) error {
if addr == "" {
addr = ":https"
}
l, err := tls.Listen("tcp", addr, tlsConfig)
if err != nil {
return err
}
return nethttp.Serve(l, handler)
}
|
package com.github.quillraven.commons.ashley.component
import com.badlogic.ashley.core.Component
import com.badlogic.ashley.core.Engine
import com.badlogic.ashley.core.Entity
import com.badlogic.gdx.utils.GdxRuntimeException
import com.badlogic.gdx.utils.Pool
import com.github.quillraven.commons.ashley.system.RemoveSystem
import ktx.ashley.get
import ktx.ashley.mapperFor
/**
* Component to mark an [Entity] for removal. It is used by the [RemoveSystem] to
* remove entities from the [Engine] at the beginning/end of a frame.
*
* Use [delay] to remove an entity after a specific amount of seconds.
*/
class RemoveComponent : Component, Pool.Poolable {
var delay = 0f
override fun reset() {
delay = 0f
}
companion object {
val MAPPER = mapperFor<RemoveComponent>()
}
}
/**
* Returns a [FadeComponent] or throws a [GdxRuntimeException] if it doesn't exist.
*/
val Entity.removeCmp: RemoveComponent
get() = this[RemoveComponent.MAPPER]
?: throw GdxRuntimeException("RemoveComponent for entity '$this' is null")
/**
* Adds a [RemoveComponent] to the [Entity] by using the [engine's][Engine]
* [createComponent][Engine.createComponent] method.
* The entity then gets removed by the [RemoveSystem].
*
* Use [delay] to remove the entity after a specific amount of seconds.
*/
fun Entity.removeFromEngine(engine: Engine, delay: Float = 0f) {
this.add(engine.createComponent(RemoveComponent::class.java).apply { this.delay = delay })
}
/**
* Checks if an [Entity] gets removed by the engine or has a [RemoveComponent].
* Use this instead of [Entity.isRemoving] to check if an entity really gets removed.
*/
val Entity.isRemoved: Boolean
get() {
return this.isRemoving || this[RemoveComponent.MAPPER] != null
}
|
Future<dynamic> delayed ({int milliseconds = 666}) async {
/// 适当延时,让操作节奏慢下来
return await Future<dynamic>.delayed(Duration(milliseconds: milliseconds));
}
const Duration scrollDuration = Duration(milliseconds: 300);
|
import 'package:cvideo_employer_mobile/src/models/models.dart';
import 'package:equatable/equatable.dart';
abstract class LoadListCVApplyState extends Equatable {
@override
List<Object> get props => [];
}
class LoadListCVApplyInitial extends LoadListCVApplyState {}
class LoadListCVApplyLoading extends LoadListCVApplyState {}
class LoadListCVApplySuccess extends LoadListCVApplyState {
final RecruitmentApplyCV recruitment;
final List<Application> listApplied;
LoadListCVApplySuccess({this.recruitment, this.listApplied});
LoadListCVApplySuccess copyWith(
{RecruitmentApplyCV recruitment, Application listApplied}) {
return LoadListCVApplySuccess(
recruitment: recruitment ?? this.recruitment,
listApplied: listApplied ?? this.listApplied);
}
}
class LoadListCVApplyFailed extends LoadListCVApplyState {}
|
/*
* Copyright 2020 Databricks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.databricks.spark.xml.util
import java.nio.file.Paths
import org.apache.spark.sql.types.{ArrayType, DecimalType, FloatType, LongType, StringType}
import org.scalatest.funsuite.AnyFunSuite
import com.databricks.spark.xml.TestUtils._
class XSDToSchemaSuite extends AnyFunSuite {
private val resDir = "src/test/resources"
test("Basic parsing") {
val parsedSchema = XSDToSchema.read(Paths.get(s"$resDir/basket.xsd"))
val expectedSchema = buildSchema(
field("basket",
struct(
structArray("entry",
field("key"),
field("value"))), nullable = false))
assert(expectedSchema === parsedSchema)
}
test("Relative path parsing") {
val parsedSchema = XSDToSchema.read(Paths.get(s"$resDir/include-example/first.xsd"))
val expectedSchema = buildSchema(
field("basket",
struct(
structArray("entry",
field("key"),
field("value"))), nullable = false))
assert(expectedSchema === parsedSchema)
}
test("Test schema types and attributes") {
val parsedSchema = XSDToSchema.read(Paths.get(s"$resDir/catalog.xsd"))
val expectedSchema = buildSchema(
field("catalog",
struct(
field("product",
struct(
structArray("catalog_item",
field("item_number", nullable = false),
field("price", FloatType, nullable = false),
structArray("size",
structArray("color_swatch",
field("_VALUE"),
field("_image")),
field("_description")),
field("_gender")),
field("_description"),
field("_product_image")),
nullable = false)),
nullable = false))
assert(expectedSchema === parsedSchema)
}
test("Test xs:choice nullability") {
val parsedSchema = XSDToSchema.read(Paths.get(s"$resDir/choice.xsd"))
val expectedSchema = buildSchema(
field("el", struct(field("foo"), field("bar"), field("baz")), nullable = false))
assert(expectedSchema === parsedSchema)
}
test("Two root elements") {
val parsedSchema = XSDToSchema.read(Paths.get(s"$resDir/twoelements.xsd"))
val expectedSchema = buildSchema(field("bar", nullable = false), field("foo", nullable = false))
assert(expectedSchema === parsedSchema)
}
test("xs:any schema") {
val parsedSchema = XSDToSchema.read(Paths.get(s"$resDir/xsany.xsd"))
val expectedSchema = buildSchema(
field("root",
struct(
field("foo",
struct(
field("xs_any")),
nullable = false),
field("bar",
struct(
field("xs_any", nullable = false)),
nullable = false),
field("baz",
struct(
field("xs_any", ArrayType(StringType), nullable = false)),
nullable = false),
field("bing",
struct(
field("xs_any")),
nullable = false)),
nullable = false))
assert(expectedSchema === parsedSchema)
}
test("Tests xs:long type / Issue 520") {
val parsedSchema = XSDToSchema.read(Paths.get(s"$resDir/long.xsd"))
val expectedSchema = buildSchema(
field("test",
struct(field("userId", LongType, nullable = false)), nullable = false))
assert(expectedSchema === parsedSchema)
}
test("Test xs:decimal type with restriction[fractionalDigits]") {
val parsedSchema = XSDToSchema.read(Paths.get(s"$resDir/decimal-with-restriction.xsd"))
val expectedSchema = buildSchema(field("decimal_type_1", DecimalType(38, 18), nullable = false),
field("decimal_type_2", DecimalType(38, 2), nullable = false))
assert(parsedSchema === expectedSchema)
}
}
|
# <auto-generated>
# This code was generated by the UnitCodeGenerator tool
#
# Changes to this file will be lost if the code is regenerated
# </auto-generated>
def to_seconds(value):
return value * 86400.0
def to_minutes(value):
return value * 1440.0
def to_hours(value):
return value * 24.0
def to_weeks(value):
return value / 7.0
def to_months(value):
return value / 30.4167
def to_years(value):
return value / 365.0
def to_decades(value):
return value / 3650.0
def to_centuries(value):
return value / 36500.0
|
(load "fl-interpreter.lisp")
; Basic Tests
(assert (equal nil (fl-interp nil nil)))
(assert (equal '(RANDOM-UNIMPLEMENTED-COMMAND) (fl-interp '(RANDOM-UNIMPLEMENTED-COMMAND) nil)))
; Primitive Addition Tests
(assert (equal 3 (fl-interp '(+ 1 2) nil)))
(assert (equal 6 (fl-interp '(+ 1 (+ 2 3)) nil)))
(assert (equal 10 (fl-interp '(+ (+ 1 2) (+ 3 4)) nil)))
(assert (equal 28 (fl-interp '(+ (+ 1 (+ 2 3)) (+ 4 (+ 5 (+ 6 7)))) nil)))
; Primitive Subtraction Tests
(assert (equal -1 (fl-interp '(- 1 2) nil)))
(assert (equal 2 (fl-interp '(- 1 (- 2 3)) nil)))
(assert (equal 0 (fl-interp '(- (- 1 2) (- 3 4)) nil)))
(assert (equal 4 (fl-interp '(- (- 1 (- 2 3)) (- 4 (- 5 (- 6 7)))) nil)))
; Primitive Multiplication Tests
(assert (equal 2 (fl-interp '(* 1 2) nil)))
(assert (equal 6 (fl-interp '(* 1 (* 2 3)) nil)))
(assert (equal 24 (fl-interp '(* (* 1 2) (* 3 4)) nil)))
(assert (equal 5040 (fl-interp '(* (* 1 (* 2 3)) (* 4 (* 5 (* 6 7)))) nil)))
; Composite Primitive Arithmetic Tests
(assert (equal -5 (fl-interp '(- 1 (* 2 3)) nil)))
(assert (equal -9 (fl-interp '(- (+ 1 2) (* 3 4)) nil)))
(assert (equal -37 (fl-interp '(+ (- 1 (* 2 3)) (* 4 (- 5 (+ 6 7)))) nil)))
; Primitive Greater-Than Tests
(assert (equal nil (fl-interp '(> 1 2) nil)))
(assert (equal T (fl-interp '(> 2 1) nil)))
; Primitive Less-Than Tests
(assert (equal T (fl-interp '(< 1 2) nil)))
(assert (equal nil (fl-interp '(< 2 1) nil)))
; Primitive Equals Tests
(assert (equal T (fl-interp '(= 1 1) nil)))
(assert (equal nil (fl-interp '(= 1 2) nil)))
; Primitive And Tests
(assert (equal nil (fl-interp '(and nil nil) nil)))
(assert (equal nil (fl-interp '(and nil T) nil)))
(assert (equal nil (fl-interp '(and T nil) nil)))
(assert (equal T (fl-interp '(and T T) nil)))
; Primitive Or Tests
(assert (equal nil (fl-interp '(or nil nil) nil)))
(assert (equal T (fl-interp '(or nil T) nil)))
(assert (equal T (fl-interp '(or T nil) nil)))
(assert (equal T (fl-interp '(or T T) nil)))
; Primitive Not Tests
(assert (equal T (fl-interp '(not nil) nil)))
(assert (equal nil (fl-interp '(not T) nil)))
; Primitive If Tests
(assert (equal 1 (fl-interp '(if (= 1 1) 1 2) nil)))
(assert (equal 2 (fl-interp '(if (= 1 2) 1 2) nil)))
; Primitive Null Tests
(assert (equal T (fl-interp '(null nil) nil)))
(assert (equal nil (fl-interp '(null T) nil)))
(assert (equal nil (fl-interp '(null 1) nil)))
(assert (equal nil (fl-interp '(null (1)) nil)))
(assert (equal T (fl-interp '(null (and nil nil)) nil)))
; Primitive Atom Tests
(assert (equal T (fl-interp '(atom nil) nil)))
(assert (equal T (fl-interp '(atom T) nil)))
(assert (equal T (fl-interp '(atom 1) nil)))
(assert (equal nil (fl-interp '(atom (1)) nil)))
; Primitive Eq Tests
(assert (equal T (fl-interp '(eq 1 1) nil)))
(assert (equal nil (fl-interp '(eq 1 2) nil)))
(assert (equal nil (fl-interp '(eq (1) (1)) nil)))
(assert (equal nil (fl-interp '(eq (1) (2)) nil)))
(assert (equal nil (fl-interp '(eq (1 2) (1 2)) nil)))
(assert (equal nil (fl-interp '(eq (1 2) (3 4)) nil)))
; Primitive First Tests
(assert (equal nil (fl-interp '(first nil) nil)))
(assert (equal 1 (fl-interp '(first (1)) nil)))
(assert (equal 1 (fl-interp '(first (1 2 3)) nil)))
; Primitive Rest Tests
(assert (equal nil (fl-interp '(rest nil) nil)))
(assert (equal nil (fl-interp '(rest (1)) nil)))
(assert (equal '(2 3) (fl-interp '(rest (1 2 3)) nil)))
; Primitive Cons Tests
(assert (equal '(nil) (fl-interp '(cons nil nil) nil)))
(assert (equal '(1) (fl-interp '(cons 1 nil) nil)))
(assert (equal '(1 2 3) (fl-interp '(cons 1 (2 3)) nil)))
; Primitive Equal Tests
(assert (equal T (fl-interp '(equal 1 1) nil)))
(assert (equal nil (fl-interp '(equal 1 2) nil)))
(assert (equal nil (fl-interp '(equal (1) 1) nil)))
(assert (equal T (fl-interp '(equal (1) (1)) nil)))
(assert (equal nil (fl-interp '(equal (1 2) (1)) nil)))
(assert (equal T (fl-interp '(equal (1 2) (1 2)) nil)))
; Primitive Number Tests
(assert (equal nil (fl-interp '(number nil) nil)))
(assert (equal nil (fl-interp '(number T) nil)))
(assert (equal T (fl-interp '(number 1) nil)))
(assert (equal nil (fl-interp '(number (1)) nil)))
(assert (equal T (fl-interp '(number (+ 1 2)) nil)))
; Miscellaneous Composite Tests
(assert (equal 12 (fl-interp '(if (and (or (- 1 0) (number nil)) (null (atom (1 2)))) (* 3 4) (> 9 0)) nil)))
(assert (equal T (fl-interp '(if (and nil (null (atom (1 2)))) (* 3 4) (> 9 0)) nil)))
; User-Defined Function Header Requisition Tests
(assert (equal '(test-fn X Y) (fl-get-function-header '(test-fn X Y = (+ X Y)))))
; User-Defined Function Body Requisition Tests
(assert (equal '(+ X Y) (fl-get-function-body '(test-fn X Y = (+ X Y)))))
; User-Defined Function Argument Acquisition Tests
(assert (equal 1 (fl-get-arg-value 'X '(X Y Z) '(1 2 3))))
(assert (equal 2 (fl-get-arg-value 'Y '(X Y Z) '(1 2 3))))
(assert (equal 3 (fl-get-arg-value 'Z '(X Y Z) '(1 2 3))))
; User-Defined Function Expansion Requisition Tests
(assert (equal nil (fl-get-function-application nil nil nil)))
(assert
(equal
'(if (null (1 2 3)) 0 (+ 1 (count (rest (1 2 3)))))
(fl-get-function-application
'(X)
'((1 2 3))
'(if (null X) 0 (+ 1 (count (rest X))))
)
)
)
; User-Defined Function Parse Tests
(assert
(equal
3
(fl-parse-user-defined-function
'(test-fn 1 2)
'(
(test-fn X Y = (+ X Y))
)
)
)
)
; User-Defined Function Evaluation Tests
(assert
(equal
3
(fl-interp
'(test-fn 1 2)
'(
(test-fn X Y = (+ X Y))
)
)
)
)
(assert
(equal
7
(fl-interp
'(test-fn 1 2 3)
'(
(test-fn X Y Z = (+ X (+ Y (+ 1 Z))))
)
)
)
)
(assert
(equal
6
(fl-interp
'(test-fn 1 2 3)
'(
(test-fn X Y = (+ X Y))
(test-fn X Y Z = (+ X (+ Y Z)))
)
)
)
)
(assert
(equal
1
(fl-interp
'(count (1))
'((count X = (if (null X) 0 (+ 1 (count (rest X))))))
)
)
)
(assert
(equal
2
(fl-interp
'(count (1 2))
'((count X = (if (null X) 0 (+ 1 (count (rest X))))))
)
)
)
(assert
(equal
3
(fl-interp
'(count (1 2 3))
'((count X = (if (null X) 0 (+ 1 (count (rest X))))))
)
)
)
(assert
(equal
10
(fl-interp
'(count (1 2 3 4 5 6 7 8 9 10))
'((count X = (if (null X) 0 (+ 1 (count (rest X))))))
)
)
)
(assert
(equal
'(1 2)
(fl-interp
'(append (1) (2))
'(
(append X Y = (if (null X)
Y
(cons (first X) (append (rest X) Y)))
)
)
)
)
)
(assert
(equal
'(1)
(fl-interp
'(reverse (1))
'(
(reverse X = (if (null X)
nil
(append (reverse (rest X)) (cons (first X) nil))))
(append X Y = (if (null X)
Y
(cons (first X) (append (rest X) Y)))
)
)
)
)
)
(assert
(equal
'(2 1)
(fl-interp
'(reverse (1 2))
'(
(reverse X = (if (null X)
nil
(append (reverse (rest X)) (cons (first X) nil))))
(append X Y = (if (null X)
Y
(cons (first X) (append (rest X) Y)))
)
)
)
)
)
(assert
(equal
'(10 9 8 7 6 5 4 3 2 1)
(fl-interp
'(reverse (1 2 3 4 5 6 7 8 9 10))
'(
(reverse X = (if (null X)
nil
(append
(reverse (rest X))
(cons (first X) nil)
)
)
)
(append X Y = (if (null X)
Y
(cons
(first X)
(append (rest X) Y)
)
)
)
)
)
)
)
|
@JS('navigator.contacts')
library picker;
import 'dart:html';
import 'package:contact_picker_web/src/js/promise.js.dart';
import 'package:js/js.dart';
external List<String> getProperties();
@JS('select')
external Promise<List<JSContact>> openPicker(
List<String> props, Options options);
@JS()
@anonymous
class Options {
external bool get multiple;
external factory Options({required bool multiple});
}
@JS('ContactAddress')
abstract class JSContact {
external List<String> get name;
external List<String> get email;
external List<String> get tel;
external List<Blob> get icon;
external List<JSAddress> get address;
}
@JS('ContactAddress')
abstract class JSAddress {
external String get city;
external String get country;
external String get dependentLocality;
external String get organization;
external String get phone;
external String get postalCode;
external String get recipient;
external String get region;
external String get sortingCode;
external List<String> get addressLine;
}
class PickerProperties {
static const String NAME_PROP = 'name';
static const String TEL_PROP = 'tel';
static const String EMAIL_PROP = 'email';
/// [ICON_PROP] only available on Chrome 84 and later
static const String ICON_PROP = 'icon';
/// [ADDR_PROP] only available on Chrome 84 and later
static const String ADDR_PROP = 'address';
}
|
<?php
namespace Cerad\Bundle\PersonBundle\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
class StripTagsTransformer implements DataTransformerInterface
{
public function transform($value)
{
//echo get_class($value); die(' WTF Strip Transform');
return $value;
}
public function reverseTransform($value)
{
//echo get_class($value); die(' WTF Strip Reverse');
return strip_tags($value);
}
}
?>
|
# User Resources
GET users
## Description
Returns the profile information for the current user.
***
## Requires authentication
**[OAuth][]**
***
## Parameters
None
***
## Return format
Current user's profile information in **[full format][]**.
Additional data:
- **upload_limit** — the number of photos the user may upload at this moment, integer.
- **upload_limit_expiry** — date and time of the beginning of the new upload limit cycle, datetime.
***
## Errors
None.
***
## Example
**Request (Using [OAuth][])**
https://api.500px.com/v1/users
**Return**
``` json
{
"user": {
"id": 173,
"username": "vovko",
"firstname": "Voldemar",
"lastname": "Petruskauskus",
"birthday": null,
"sex": 0,
"city": "",
"state": "",
"country": "",
"registration_date": "2009-11-08T12:41:14-05:00",
"about": "lbalblabla",
"domain": "vovko.500px.com",
"upgrade_status": 2,
"fotomoto_on": false,
"locale": "en",
"show_nude": true,
"store_on": false,
"contacts": {
"website": "www.drizhepolov.com",
"twitter": "vovko",
"livejournal": "vovko",
"flickr": "Vladimir Drizhepolov",
"gtalk": "vladimir@drizhepolov.com",
"skype": "trulllllll",
"facebook": "562874260",
"facebookpage": "www.facebook.com/vovko"
},
"equipment": {
"camera": [
"Kiev 88",
"Lomo Rocket",
"Lomo Action sampler"
],
"lens": [
"Volna 80mm"
]
},
"fullname": "Voldemar Petruskauskus",
"userpic_url": "http://acdn.500px.net/173.jpg",
"email": "vladimir@drizhepolov.com",
"photos_count": 5,
"affection": 7,
"in_favorites_count": 0,
"friends_count": 37,
"followers_count": 7,
"upload_limit": null,
"upload_limit_expiry": "2012-06-08T14:30:28-04:00",
"upgrade_status_expiry": "2012-12-12",
"auth": {
"facebook": 0,
"twitter": 0
}
}
}
```
[OAuth]: https://github.com/500px/api-documentation/tree/master/authentication
[full format]: https://github.com/500px/api-documentation/blob/master/basics/formats_and_terms.md#profile-format
|
#include <iostream>
#include "JsonDB.hpp"
#include "SQLiteDB.hpp"
int main(int, char **)
{
// Open local jsonDB (auto parses)
hsc::JsonDB old_db("../../old-system/db.json");
// Open local SQLite database
hsc::SQLiteDB new_db("../../new-system/db.db");
new_db.open();
// Insert each record from old database into new database
for (auto &record : old_db.records) {
new_db.insertRecord(record);
}
// Finished
new_db.close();
}
|
/*
* Copyright (C) 2019. Zac Sweers
*
* 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 io.sweers.catchup.service.hackernews
import androidx.fragment.app.Fragment
import androidx.lifecycle.AbstractSavedStateViewModelFactory
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.squareup.inject.assisted.dagger2.AssistedModule
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.Reusable
import dagger.multibindings.IntoMap
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.SingleEmitter
import io.sweers.catchup.service.api.CatchUpItem
import io.sweers.catchup.service.api.DataRequest
import io.sweers.catchup.service.api.DataResult
import io.sweers.catchup.service.api.FragmentKey
import io.sweers.catchup.service.api.Mark.Companion.createCommentMark
import io.sweers.catchup.service.api.Service
import io.sweers.catchup.service.api.ServiceException
import io.sweers.catchup.service.api.ServiceKey
import io.sweers.catchup.service.api.ServiceMeta
import io.sweers.catchup.service.api.ServiceMetaKey
import io.sweers.catchup.service.api.SummarizationInfo
import io.sweers.catchup.service.api.TextService
import io.sweers.catchup.service.hackernews.model.HackerNewsStory
import io.sweers.catchup.service.hackernews.viewmodelbits.ViewModelAssistedFactory
import io.sweers.catchup.service.hackernews.viewmodelbits.ViewModelKey
import io.sweers.catchup.serviceregistry.annotations.Meta
import io.sweers.catchup.serviceregistry.annotations.ServiceModule
import io.sweers.catchup.util.d
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import javax.inject.Inject
import javax.inject.Qualifier
typealias AssistedFactory = ViewModelAssistedFactory<out ViewModel>
@Qualifier
private annotation class InternalApi
private const val SERVICE_KEY = "hn"
internal class HackerNewsService @Inject constructor(
@InternalApi private val serviceMeta: ServiceMeta,
private val database: dagger.Lazy<FirebaseDatabase>
) :
TextService {
override fun meta() = serviceMeta
override fun fetchPage(request: DataRequest): Single<DataResult> {
val page = request.pageId.toInt()
val itemsPerPage = 25 // TODO Pref this
return Single
.create { emitter: SingleEmitter<DataSnapshot> ->
val listener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
emitter.onSuccess(dataSnapshot)
}
override fun onCancelled(firebaseError: DatabaseError) {
d { "${firebaseError.code}" }
emitter.onError(firebaseError.toException())
}
}
val ref = database.get().getReference("v0/topstories").apply {
keepSynced(true)
}
emitter.setCancellable { ref.removeEventListener(listener) }
ref.addValueEventListener(listener)
}
.flattenAsObservable { it.children }
.skip(((page + 1) * itemsPerPage - itemsPerPage).toLong())
.take(itemsPerPage.toLong())
.map { d -> d.value as Long }
.concatMapEager { id ->
Observable.create<DataSnapshot> { emitter ->
val ref = database.get().getReference("v0/item/$id")
val listener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
emitter.onNext(dataSnapshot)
emitter.onComplete()
}
override fun onCancelled(firebaseError: DatabaseError) {
d { "${firebaseError.code}" }
emitter.onError(firebaseError.toException())
}
}
emitter.setCancellable { ref.removeEventListener(listener) }
ref.addValueEventListener(listener)
}
}
.filter { it.hasChild("title") } // Some HN items are just empty junk
.map { HackerNewsStory.create(it) }
.map {
val url = it.url
with(it) {
CatchUpItem(
id = id,
title = title,
score = "+" to score,
timestamp = realTime(),
author = by,
source = url?.let { it.toHttpUrlOrNull()!!.host },
tag = realType()?.tag(nullIfStory = true),
itemClickUrl = url,
summarizationInfo = SummarizationInfo.from(url),
mark = kids?.size?.let {
createCommentMark(
count = it,
clickUrl = "https://news.ycombinator.com/item?id=$id"
)
},
detailKey = id.toString()
)
}
}
.toList()
.map { DataResult(it, if (it.isEmpty()) null else (page + 1).toString()) }
.onErrorResumeNext { t: Throwable ->
if (t is IllegalArgumentException) {
// Firebase didn't init
Single.error(ServiceException(
"Firebase wasn't able to initialize, likely due to missing credentials."))
} else {
Single.error(t)
}
}
}
}
@Meta
@ServiceModule
@Module
abstract class HackerNewsMetaModule {
@IntoMap
@ServiceMetaKey(SERVICE_KEY)
@Binds
internal abstract fun hackerNewsServiceMeta(@InternalApi meta: ServiceMeta): ServiceMeta
@Module
companion object {
@InternalApi
@Provides
@Reusable
@JvmStatic
internal fun provideHackerNewsServiceMeta() = ServiceMeta(
SERVICE_KEY,
R.string.hn,
R.color.hnAccent,
R.drawable.logo_hn,
pagesAreNumeric = true,
firstPageKey = "0",
deeplinkFragment = HackerNewsCommentsFragment::class.java
)
}
}
@ServiceModule
@Module(
includes = [
HackerNewsMetaModule::class,
FragmentViewModelFactoryModule::class,
ViewModelModule::class
]
)
abstract class HackerNewsModule {
@IntoMap
@ServiceKey(SERVICE_KEY)
@Binds
internal abstract fun hackerNewsService(hackerNewsService: HackerNewsService): Service
@Binds
@IntoMap
@FragmentKey(HackerNewsCommentsFragment::class)
internal abstract fun bindHnFragment(mainFragment: HackerNewsCommentsFragment): Fragment
@Module
companion object {
@Provides
@JvmStatic
internal fun provideDataBase(): FirebaseDatabase =
FirebaseDatabase.getInstance("https://hacker-news.firebaseio.com/")
}
}
@AssistedModule
@Module(includes = [AssistedInject_ViewModelModule::class])
internal abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(HackerNewsCommentsViewModel::class)
abstract fun mainViewModel(viewModel: HackerNewsCommentsViewModel.Factory): AssistedFactory
}
// TODO generify this somewhere once something other than HN does it
@Module
internal object FragmentViewModelFactoryModule {
@Provides
@JvmStatic
fun viewModelFactory(
viewModels: @JvmSuppressWildcards Map<Class<out ViewModel>, AssistedFactory>
): ViewModelProviderFactoryInstantiator {
return object : ViewModelProviderFactoryInstantiator {
override fun create(fragment: Fragment): ViewModelProvider.Factory {
return object : AbstractSavedStateViewModelFactory(fragment, null) {
override fun <T : ViewModel> create(
key: String,
modelClass: Class<T>,
handle: SavedStateHandle
): T {
// TODO this is ugly extract these constants
handle.set("detailKey", fragment.arguments!!.getString("detailKey")!!)
handle.set("detailTitle", fragment.arguments!!.getString("detailTitle"))
@Suppress("UNCHECKED_CAST")
return viewModels.getValue(modelClass).create(handle) as T
}
}
}
}
}
// This exists to avoid the static fragment dependency for dagger. We don't place fragments
// directly on the DI graph, but rather route them all through a fragment factory that only
// produces new instances. Instead we defer initialization to the fragment consuming the
// ViewModelProvider.Factory to pass itself in a deferred fashion.
//
// I initially named this ViewModelProviderFactoryFactory, and repent for my sins.
interface ViewModelProviderFactoryInstantiator {
fun create(fragment: Fragment): ViewModelProvider.Factory
}
}
|
/// <vs SolutionOpened='default' />
// http://andy-carter.com/blog/a-beginners-guide-to-the-task-runner-gulp
// http://www.smashingmagazine.com/2014/06/11/building-with-gulp/
var gulp = require('gulp'),
plumber = require('gulp-plumber'),
watch = require('gulp-watch');
gulp.task('copy_csComp', function () {
gulp.src('../csComp/dist/*.*')
.pipe(plumber())
.pipe(gulp.dest('csComp'));
});
gulp.task('watch', function () {
gulp.watch('../csComp/dist/*.*', ['copy_csComp']);
});
gulp.task('default', ['copy_csComp', 'watch']);
|
use crate::geometry::direction::Direction;
use crate::geometry::vector::Vector4;
#[derive(Copy, Clone, Debug)]
pub struct Ray {
pub start: Vector4,
pub direction: Direction,
}
impl Ray {
pub fn march(&self, t: f64) -> Vector4 {
return self.start + (Vector4::from(self.direction) * t);
}
}
|
#include "./dist_async_sum-inl.h"
int CreateServerNode(int argc, char *argv[]) {
mshadow::ps::MShadowServerNode<float> server(argc, argv);
return 0;
}
int WorkerNodeMain(int argc, char *argv[]) {
return Run<mshadow::cpu>(argc, argv);
}
|
#[cfg(feature = "physics")]
mod physics_bundle;
#[cfg(feature = "physics")]
pub use physics_bundle::PhysicsBundle;
#[cfg(feature = "animation")]
mod animation_bundle;
#[cfg(feature = "animation")]
pub use animation_bundle::AnimationBundle;
#[cfg(feature = "audio")]
mod audio_bundle;
#[cfg(feature = "audio")]
pub use audio_bundle::AudioBundle;
|
package com.shopping
import math._
import Shop._
object Offer {
type Discount = BigDecimal
val buyOneGetOneFreeOnApple : ShoppingCart => Discount = shoppingCart => {
val appleList = shoppingCart.items collect { case item @ Apple => item }
floor(appleList.size/2) * 0.60
}
val threeForThePriceOfTwoOnOrange : ShoppingCart => Discount = shoppingCart => {
val orangeList = shoppingCart.items collect { case item @ Orange => item }
floor(orangeList.size/3) * 0.25
}
}
|
module RootHitFiles
import Base, Tables
using Mmap: mmap
using Parsers
export RootHitFile
"""
RootHitFile(file::Union{IOStream, AbstractString})
represents a `.root.hits` file, which can be iterated or read to yield events, which are
tables of hits.
"""
struct RootHitFile
stream::IOBuffer
end
RootHitFile(stream::IOStream) = RootHitFile(IOBuffer(mmap(stream)))
RootHitFile(path::AbstractString) = occursin(r".root.hits$", path) ? RootHitFile((open(path))) :
throw(ArgumentError("$path is not a .root.hits file"))
EventTuple = NamedTuple{
(:eventnum, :primcount, :pos, :E, :time, :particleID, :trkID, :trkparentID, :volumeID),
Tuple{
Int32, Int32, Vector{NTuple{3, Float32}}, Vector{Float32}, Vector{Float32},
Vector{Int32}, Vector{Int32}, Vector{Int32}, Vector{String}
}
}
function Base.read(f::RootHitFile)
eventnum = Parsers.parse(Int32, f.stream)
hitcount = Parsers.parse(Int32, f.stream)
primcount = Parsers.parse(Int32, f.stream)
# skip newline
skip(f.stream, 1)
pos = Vector{NTuple{3, Float32}}(undef, hitcount)
E = Vector{ Float32}(undef, hitcount)
time = Vector{ Float32}(undef, hitcount)
particleID = Vector{ Int32}(undef, hitcount)
trkID = Vector{ Int32}(undef, hitcount)
trkparentID = Vector{ Int32}(undef, hitcount)
volumeID = Vector{ String}(undef, hitcount)
@inbounds for i in 1:hitcount
pos[i] = (
Parsers.parse(Float32, f.stream),
Parsers.parse(Float32, f.stream),
Parsers.parse(Float32, f.stream)
)
E[i] = Parsers.parse(Float32, f.stream)
time[i] = Parsers.parse(Float32, f.stream)
particleID[i] = Parsers.parse(Int32, f.stream)
trkID[i] = Parsers.parse(Int32, f.stream)
trkparentID[i] = Parsers.parse(Int32, f.stream)
volumeID[i] = String(readuntil(f.stream, UInt8('\n')))
end
return EventTuple((
eventnum, primcount, pos, E, time,
particleID, trkID, trkparentID, volumeID
))
end
Base.eof(f::RootHitFile) = eof(f.stream)
function Base.iterate(f::RootHitFile, state = nothing)
eof(f) && return nothing
return read(f), nothing
end
Base.IteratorSize(::Type{RootHitFile}) = Base.SizeUnknown()
Base.IteratorEltype(::Type{RootHitFile}) = Base.HasEltype()
Base.eltype(::RootHitFile) = EventTuple
Tables.isrowtable(::Type{RootHitFile}) = true
Tables.schema(f::RootHitFile) = Tables.Schema(eltype(f))
end # RootHitFiles
|
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import { Grid } from '@material-ui/core';
import cardImage from '../../../assets/imgs/card.jpg'
import { Link, useHistory } from 'react-router-dom';
const useStyles = makeStyles({
root: {
maxWidth: 345,
'&:hover': {
cursor: 'pointer',
borderColor: '#d45858',
border: '2px solid'
},
transition: 'all 0.5s 0s ease'
},
media: {
height: 140,
},
link: {
textDecoration: 'none',
color: '#fff'
}
});
interface PokemonProps {
name?: string
url?: string
}
const PokemonCard: React.FC<PokemonProps> = ({ name, url }) => {
const classes = useStyles();
const history = useHistory()
const urlcutted = url?.split('/')
const id = urlcutted && urlcutted[urlcutted?.length - 2]
const handleClick = () => {
history.push(`/detail/${id}`)
}
return (
<Grid item xs={6} md={3}>
<Card className={classes.root} onClick={handleClick}>
<CardActionArea>
<CardMedia
className={classes.media}
image={cardImage}
title="Contemplative Reptile"
/>
<CardContent>
<Typography gutterBottom variant="h5" component="h2">
{name?.toLocaleUpperCase()}
</Typography>
</CardContent>
</CardActionArea>
<CardActions>
<Button fullWidth color="primary" variant="contained">
<Link to={`/detail/${id}`} className={classes.link} >
Detalhes
</Link>
</Button>
</CardActions>
</Card>
</Grid>
);
}
export default PokemonCard
|
require 'player'
describe Player do
let(:name){ double :name }
subject { described_class.new(name) }
it 'should return the player name' do
expect(subject.get_name).to eq name
end
end
|
// Copyright 2019 Yunion
//
// 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 sqlchemy
// Filter method filters a SQL query with given ICondition
// equivalent to add a clause in where conditions
func (tq *SQuery) Filter(cond ICondition) *SQuery {
if tq.groupBy != nil && len(tq.groupBy) > 0 {
if tq.having == nil {
tq.having = cond
} else {
tq.having = AND(tq.having, cond)
}
} else {
if tq.where == nil {
tq.where = cond
} else {
tq.where = AND(tq.where, cond)
}
}
return tq
}
// FilterByTrue filters query with a true condition
func (tq *SQuery) FilterByTrue() *SQuery {
return tq.Filter(&STrueCondition{})
}
// FilterByFalse filters query with a false condition
func (tq *SQuery) FilterByFalse() *SQuery {
return tq.Filter(&SFalseCondition{})
}
// Like filters query with a like condition
func (tq *SQuery) Like(f string, v string) *SQuery {
cond := Like(tq.Field(f), v)
return tq.Filter(cond)
}
// Contains filters query with a contains condition
func (tq *SQuery) Contains(f string, v string) *SQuery {
cond := Contains(tq.Field(f), v)
return tq.Filter(cond)
}
// Startswith filters query with a startswith condition
func (tq *SQuery) Startswith(f string, v string) *SQuery {
cond := Startswith(tq.Field(f), v)
return tq.Filter(cond)
}
// Endswith filters query with a endswith condition
func (tq *SQuery) Endswith(f string, v string) *SQuery {
cond := Endswith(tq.Field(f), v)
return tq.Filter(cond)
}
// NotLike filters query with a not like condition
func (tq *SQuery) NotLike(f string, v string) *SQuery {
cond := Like(tq.Field(f), v)
return tq.Filter(NOT(cond))
}
// In filters query with a in condition
func (tq *SQuery) In(f string, v interface{}) *SQuery {
cond := In(tq.Field(f), v)
return tq.Filter(cond)
}
// NotIn filters query with a not in condition
func (tq *SQuery) NotIn(f string, v interface{}) *SQuery {
cond := In(tq.Field(f), v)
return tq.Filter(NOT(cond))
}
// Between filters query with a between condition
func (tq *SQuery) Between(f string, v1, v2 interface{}) *SQuery {
cond := Between(tq.Field(f), v1, v2)
return tq.Filter(cond)
}
// NotBetween filters query with a not between condition
func (tq *SQuery) NotBetween(f string, v1, v2 interface{}) *SQuery {
cond := Between(tq.Field(f), v1, v2)
return tq.Filter(NOT(cond))
}
// Equals filters query with a equals condition
func (tq *SQuery) Equals(f string, v interface{}) *SQuery {
cond := Equals(tq.Field(f), v)
return tq.Filter(cond)
}
// NotEquals filters the query with a not equals condition
func (tq *SQuery) NotEquals(f string, v interface{}) *SQuery {
cond := NotEquals(tq.Field(f), v)
return tq.Filter(cond)
}
// GE filters the query with a >= condition
func (tq *SQuery) GE(f string, v interface{}) *SQuery {
cond := GE(tq.Field(f), v)
return tq.Filter(cond)
}
// LE filters the query with a <= condition
func (tq *SQuery) LE(f string, v interface{}) *SQuery {
cond := LE(tq.Field(f), v)
return tq.Filter(cond)
}
// GT filters the query with a > condition
func (tq *SQuery) GT(f string, v interface{}) *SQuery {
cond := GT(tq.Field(f), v)
return tq.Filter(cond)
}
// LT filters the query with a < condition
func (tq *SQuery) LT(f string, v interface{}) *SQuery {
cond := LT(tq.Field(f), v)
return tq.Filter(cond)
}
// IsNull filters the query with a is null condition
func (tq *SQuery) IsNull(f string) *SQuery {
cond := IsNull(tq.Field(f))
return tq.Filter(cond)
}
// IsNotNull filters the query with a is not null condition
func (tq *SQuery) IsNotNull(f string) *SQuery {
cond := IsNotNull(tq.Field(f))
return tq.Filter(cond)
}
// IsEmpty filters the query with a is_empty condition
func (tq *SQuery) IsEmpty(f string) *SQuery {
cond := IsEmpty(tq.Field(f))
return tq.Filter(cond)
}
// IsNullOrEmpty filters the query with a is null or empty condition
func (tq *SQuery) IsNullOrEmpty(f string) *SQuery {
cond := IsNullOrEmpty(tq.Field(f))
return tq.Filter(cond)
}
// IsNotEmpty filters the query with a is not empty condition
func (tq *SQuery) IsNotEmpty(f string) *SQuery {
cond := IsNotEmpty(tq.Field(f))
return tq.Filter(cond)
}
// IsTrue filters the query with a is true condition
func (tq *SQuery) IsTrue(f string) *SQuery {
cond := IsTrue(tq.Field(f))
return tq.Filter(cond)
}
// IsFalse filters the query with a is false condition
func (tq *SQuery) IsFalse(f string) *SQuery {
cond := IsFalse(tq.Field(f))
return tq.Filter(cond)
}
|
package studio.forface.covid.data
import studio.forface.covid.data.local.localDataModule
import studio.forface.covid.data.remote.remoteDataModule
val dataModule = remoteDataModule + localDataModule
|
import { expect } from "chai";
import { Project } from "../../Project";
describe("tests for issue #1164", () => {
it("should not forget the source file when using `getSymbol()` after it creates a source file", () => {
const project = new Project({ useInMemoryFileSystem: true });
const sourceFile = project.createSourceFile("index.ts", "");
const i = sourceFile.addInterface({ name: "Foo" }).getType();
expect(project.getSourceFiles().length).to.equal(1);
sourceFile.addInterface({ name: "FooBar" });
i.getSymbol();
expect(project.getSourceFiles().length).to.equal(1); // was 0 before this was fixed
});
});
|
Bolt Language Experiments
=========================
Bolt is an experimental programming language that I'm creating. The
design is currently documented in [a gist][bolt-design].
[bolt-design]: https://gist.github.com/NelsonCrosby/bd6906833a567ab006c970d4d8c7da05
By *experimental*, I don't necessarily mean *way out there*, just that
I'm currently playing around without a huge amount of direction at the
moment.
|
import 'package:flutter/material.dart';
import 'package:possystem/components/style/hint_text.dart';
class MetaBlock extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.symmetric(horizontal: 4),
child: const Text('•'),
);
}
static TextSpan span() {
return const TextSpan(text: string);
}
static const string = ' • ';
static Widget? withString(
BuildContext context,
Iterable<String> data, {
TextStyle? textStyle,
String? emptyText,
TextOverflow textOverflow = TextOverflow.ellipsis,
}) {
if (data.isNotEmpty) {
final children = data
.expand((value) => [
TextSpan(text: value),
MetaBlock.span(),
])
.toList();
// remove last block
children.removeLast();
return RichText(
overflow: textOverflow,
text: TextSpan(
children: children,
// disable parent text style
style: textStyle ?? Theme.of(context).textTheme.bodyText1,
),
);
} else if (emptyText != null) {
return RichText(text: HintText.inSpan(context, emptyText));
} else {
return null;
}
}
}
|
import APIJSON from '../../../../config/api.json'
export default function getAPIBaseURL () {
return APIJSON.api.path
}
|
/* ----------------------------- Segments -------------------------------- */
/*
Each malloc space may include non-contiguous segments, held in a
list headed by an embedded malloc_segment record representing the
top-most space. Segments also include flags holding properties of
the space. Large chunks that are directly allocated by mmap are not
included in this list. They are instead independently created and
destroyed without otherwise keeping track of them.
Segment management mainly comes into play for spaces allocated by
MMAP. Any call to MMAP might or might not return memory that is
adjacent to an existing segment. MORECORE normally contiguously
extends the current space, so this space is almost always adjacent,
which is simpler and faster to deal with. (This is why MORECORE is
used preferentially to MMAP when both are available -- see
sys_alloc.) When allocating using MMAP, we don't use any of the
hinting mechanisms (inconsistently) supported in various
implementations of unix mmap, or distinguish reserving from
committing memory. Instead, we just ask for space, and exploit
contiguity when we get it. It is probably possible to do
better than this on some systems, but no general scheme seems
to be significantly better.
Management entails a simpler variant of the consolidation scheme
used for chunks to reduce fragmentation -- new adjacent memory is
normally prepended or appended to an existing segment. However,
there are limitations compared to chunk consolidation that mostly
reflect the fact that segment processing is relatively infrequent
(occurring only when getting memory from system) and that we
don't expect to have huge numbers of segments:
* Segments are not indexed, so traversal requires linear scans. (It
would be possible to index these, but is not worth the extra
overhead and complexity for most programs on most platforms.)
* New segments are only appended to old ones when holding top-most
memory; if they cannot be prepended to others, they are held in
different segments.
Except for the top-most segment of an mstate, each segment record
is kept at the tail of its segment. Segments are added by pushing
segment records onto the list headed by &mstate.seg for the
containing mstate.
Segment flags control allocation/merge/deallocation policies:
* If EXTERN_BIT set, then we did not allocate this segment,
and so should not try to deallocate or merge with others.
(This currently holds only for the initial segment passed
into create_mspace_with_base.)
* If USE_MMAP_BIT set, the segment may be merged with
other surrounding mmapped segments and trimmed/de-allocated
using munmap.
* If neither bit is set, then the segment was obtained using
MORECORE so can be merged with surrounding MORECORE'd segments
and deallocated/trimmed using MORECORE with negative arguments.
*/
|
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Post;
use Livewire\WithPagination;
use Illuminate\Support\Facades\DB;
class SearchPosts extends Component
{
use WithPagination;
public $searchTerm;
public $lang;
protected $posts;
protected $pagination = '9';
// If the language is not sq or al, we set it to null so that we can display posts from both languages
public function switchLanguage($val = NULL){
$this->lang = $val;
}
/*
* Showing all posts and provides searching with the term entered by user
* If language is not available, all posts are displayed. Or we display the required language only
*/
public function render()
{
$this->posts = Post::query()
->where('lang', 'LIKE', "%". ($this->lang) ? $this->lang : '' . "%")
->where(function($query) {
$query->where('title', 'LIKE', "%{$this->searchTerm}%")
->orWhere('body', 'LIKE', "%{$this->searchTerm}%");
})
->with('user')
->withCount('children')
->orderBy('created_at', 'desc')
->paginate($this->pagination);
return view('livewire.search-posts', [
'posts' => $this->posts,
]);
}
}
|
package com.cattong.sns.impl.facebook;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.cattong.commons.LibException;
import com.cattong.commons.LibResultCode;
import com.cattong.commons.util.ParseUtil;
import com.cattong.commons.util.StringUtil;
import com.cattong.sns.entity.Status;
public class FacebookStatusAdapter {
public static Status createStatus(String jsonString) throws LibException {
try {
JSONObject json = new JSONObject(jsonString);
return createStatus(json);
} catch (JSONException e) {
throw new LibException(LibResultCode.JSON_PARSE_ERROR, e);
}
}
public static List<Status> createStatusList(String jsonString)
throws LibException {
try {
if (StringUtil.isEquals("{}", jsonString)
|| StringUtil.isEquals("[]", jsonString)) {
return new ArrayList<Status>(0);
}
JSONArray jsonArray = new JSONArray(jsonString);
int length = jsonArray.length();
List<Status> statuses = new ArrayList<Status>(length);
for (int i = 0; i < length; i++) {
statuses.add(createStatus(jsonArray.getJSONObject(i)));
}
return statuses;
} catch (JSONException e) {
throw new LibException(LibResultCode.JSON_PARSE_ERROR, e);
}
}
public static Status createStatus(JSONObject json) throws LibException {
if (json == null) {
return null;
}
try {
Status status = new Status();
status.setId(ParseUtil.getRawString("id", json));
status.setText(ParseUtil.getRawString("message", json));
status.setUpdatedTime(ParseUtil.getDate("update_time", json, Facebook.DATE_FORMAT));
if (json.has("comments")) {
status.setCommentsCount(json.getJSONObject("comments").getJSONArray("data").length());
}
return status;
} catch (ParseException e) {
throw new LibException(LibResultCode.DATE_PARSE_ERROR, e);
} catch (JSONException e) {
throw new LibException(LibResultCode.JSON_PARSE_ERROR, e);
}
}
}
|
SOS.events.onBattle = function(){
}
SOS.events.offBattle = function(){
}
|
#!/bin/bash
export GOROOT=/Users/devdatta/Downloads/go1.13.9/go
export PATH=$GOROOT/bin:$PATH
|
import 'package:flutter/material.dart';
class BaseModel extends ChangeNotifier {
bool _busy = false;
bool get busy => _busy;
void setBusy(bool value) {
_busy = value;
notifyListeners();
}
@override
void dispose() {
print('I have been disposed: ' + this.runtimeType.toString());
super.dispose();
}
}
|
-module(wnkd_web_item).
-export([init/2]).
init(Req, []) ->
{ok, Body, Req2} = cowboy_req:body(Req, [{length, 100000000}]),
Request = jsx:decode(Body, [return_maps]),
ok = wnkd_item:create(Request),
Req3 = cowboy_req:reply(200, [
{<<"content-type">>, <<"text/json">>}
], jsx:encode(#{ status => ok }), Req2),
{ok, Req3, []}.
|
<?php
namespace Drupal\entity_reference_display\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\TypedData\OptionsProviderInterface;
/**
* Plugin implementation of the 'entity_reference_display' field type.
*
* @FieldType(
* id = "entity_reference_display",
* label = @Translation("Display mode"),
* description = @Translation("This field allows you to specify a display mode for entity reference field."),
* category = @Translation("Reference"),
* default_widget = "options_select",
* default_formatter = "list_default"
* )
*/
class EntityReferenceDisplayItem extends FieldItemBase implements OptionsProviderInterface {
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
return [
'value' => DataDefinition::create('string')
->setLabel(new TranslatableMarkup('Display mode'))
->setRequired(TRUE),
];
}
/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
'columns' => [
'value' => [
'type' => 'varchar',
'length' => 255,
],
],
];
}
/**
* {@inheritdoc}
*/
public static function defaultFieldSettings() {
return [
'exclude' => [],
'negate' => FALSE,
] + parent::defaultFieldSettings();
}
/**
* {@inheritdoc}
*/
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$element = [];
// Prepare select element with all options.
$element['exclude'] = [
'#type' => 'select',
'#title' => $this->t('Excluded display modes'),
'#description' => $this->t('Select all display modes which will not be offered.'),
'#options' => $this->getAllDisplayModes(),
'#default_value' => $this->getSetting('exclude'),
'#multiple' => TRUE,
];
$element['negate'] = [
'#type' => 'checkbox',
'#title' => $this->t('Include selected display modes instead of excluding'),
'#description' => $this->t('If checked, only display modes selected above will be offered.'),
'#default_value' => $this->getSetting('negate'),
];
return $element;
}
/**
* {@inheritdoc}
*/
public function isEmpty() {
$value = $this->get('value')->getValue();
return $value === NULL || $value === '';
}
/**
* {@inheritdoc}
*/
public function getPossibleValues(AccountInterface $account = NULL) {
// Get values from possible options.
return array_keys($this->getPossibleOptions($account));
}
/**
* {@inheritdoc}
*/
public function getPossibleOptions(AccountInterface $account = NULL) {
// Get all display modes in alphabetical order.
$display_modes = $this->getAllDisplayModes();
// Get displays to exclude from options.
$exclude = $this->getSetting('exclude');
// Check if display modes should be negated.
$negate = !empty($this->getSetting('negate'));
// Get options array.
$options = [];
foreach ($display_modes as $key => $display_mode) {
// Only if display is not excluded or it's negated and included.
if ((!$negate && !isset($exclude[$key])) || ($negate && isset($exclude[$key]))) {
// Add display between options.
$options[$key] = $display_mode;
}
}
return $options;
}
/**
* {@inheritdoc}
*/
public function getSettableValues(AccountInterface $account = NULL) {
// Get values from settable options.
return array_keys($this->getSettableOptions($account));
}
/**
* {@inheritdoc}
*/
public function getSettableOptions(AccountInterface $account = NULL) {
// Get the same as from possible options.
return $this->getPossibleOptions($account);
}
/**
* Get all display modes in alphabetical order with Default as first.
*/
private function getAllDisplayModes() {
// Get all display modes grouped by entity types.
$display_modes = \Drupal::service('entity_display.repository')
->getAllViewModes();
// Get basic information about display modes.
$result = [];
foreach ($display_modes as $modes) {
foreach ($modes as $mode => $info) {
// If display mode is not already in result set.
if (!isset($result[$mode])) {
$result[$mode] = $info['label'];
}
}
}
// Sort display modes in alphabetical order.
asort($result);
// Return array of all display modes prepended by Default.
return ['default' => 'Default'] + $result;
}
}
|
// Copyright (c) 2009 STFC
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef SAGA_PACKAGES_ISN_NAVIGATOR_HPP
#define SAGA_PACKAGES_ISN_NAVIGATOR_HPP
// include dependent spec sections
#include <saga/saga/util.hpp>
#include <saga/saga/base.hpp>
#include <saga/saga/types.hpp>
#include <saga/saga/session.hpp>
#include <saga/saga/call.hpp>
#include <saga/saga/exception.hpp>
#include <saga/saga/url.hpp>
#include <saga/saga/packages/isn/config.hpp>
#include "entity_types.hpp"
namespace saga { namespace impl { class navigator; class entity_data_set;} }
///@cond
namespace saga
{
namespace isn {
class SAGA_ISN_PACKAGE_EXPORT navigator
: public saga::object
{
public:
private:
// factory
SAGA_CALL_CREATE_PRIV_3(std::string const& model,
session const&,
saga::url)
SAGA_CALL_PRIV_1 (list_related_entity_names, std::string)
SAGA_CALL_PRIV_4 (get_related_entities,
std::string,
std::string,
std::string,
std::vector<saga::isn::entity_data>)
SAGA_CALL_PRIV_2 (get_entities,
std::string,
std::string)
protected:
TR1::shared_ptr <saga::impl::navigator> get_impl_sp (void) const;
saga::impl::navigator* get_impl (void) const;
friend class saga::impl::navigator;
explicit navigator(saga::impl::navigator* impl)
SAGA_THROW_SPEC(throw(saga::not_implemented,
saga::incorrect_url,
saga::does_not_exist,
saga::authorization_failed,
saga::authentication_failed,
saga::timeout,
saga::no_success));
public:
explicit navigator(std::string const& model = std::string(),
saga::url loc = saga::url())
SAGA_THROW_SPEC(throw(saga::not_implemented,
saga::incorrect_url,
saga::does_not_exist,
saga::authorization_failed,
saga::authentication_failed,
saga::timeout,
saga::no_success));
explicit navigator(std::string const& model,
session const& s,
saga::url loc = saga::url())
SAGA_THROW_SPEC(throw(saga::not_implemented,
saga::incorrect_url,
saga::does_not_exist,
saga::authorization_failed,
saga::authentication_failed,
saga::timeout,
saga::no_success));
~navigator (void) SAGA_THROW_SPEC(throw());
static navigator create(std::string const& model,
session const& s,
saga::url loc = saga::url())
SAGA_THROW_SPEC(throw(saga::not_implemented,
saga::incorrect_url,
saga::does_not_exist,
saga::authorization_failed,
saga::authentication_failed,
saga::timeout,
saga::no_success))
{
return navigator(model, s, loc);
}
SAGA_CALL_CREATE_3_DEF_1(std::string const&,
session const&,
saga::url,
saga::url())
static navigator create(std::string const& model = std::string(),
saga::url loc = saga::url())
SAGA_THROW_SPEC(throw(saga::not_implemented,
saga::incorrect_url,
saga::not_implemented,
saga::authorization_failed,
saga::authentication_failed,
saga::timeout,
saga::no_success))
{
return navigator(model, loc);
}
template <typename Tag>
static saga::task create(std::string const& model = std::string(),
saga::url loc = saga::url())
{
return create<Tag>(model, saga::detail::get_the_session(), loc);
}
// default operator=() and copy ctor
navigator& operator= (saga::object const& o)
SAGA_THROW_SPEC(throw());
std::vector<std::string>
list_related_entity_names(std::string entityName)
SAGA_THROW_SPEC(throw(saga::bad_parameter,
saga::authorization_failed,
saga::authentication_failed,
saga::timeout,
saga::no_success))
{
saga::task t = list_related_entity_namespriv(entityName,
saga::task_base::Sync());
return t.get_result<std::vector<std::string> >();
}
SAGA_CALL_PUB_1_DEF_0 (list_related_entity_names, std::string)
std::vector<saga::isn::entity_data>
get_related_entities(std::string entityName,
std::string related_entity_name,
std::string filter,
std::vector<saga::isn::entity_data> entities)
{
saga::task t = get_related_entitiespriv(entityName,
related_entity_name,
filter,
entities,
saga::task_base::Sync());
return t.get_result<std::vector<saga::isn::entity_data> >();
}
SAGA_CALL_PUB_4_DEF_0 (get_related_entities,
std::string,
std::string,
std::string,
std::vector<saga::isn::entity_data>)
std::vector<saga::isn::entity_data>
get_entities(std::string entityName,
std::string filter)
{
saga::task t = get_entitiespriv(entityName,
filter,
saga::task_base::Sync());
return t.get_result<std::vector<saga::isn::entity_data> >();
}
SAGA_CALL_PUB_2_DEF_0 (get_entities,
std::string,
std::string)
}; // discoverer
} // namespace isn
} // namespace saga
///@endcond
#endif
|
import { QueryOptions } from 'apollo-client';
export interface DaffCategoryQueryManagerInterface {
getACategoryQuery(identifier: string | number): QueryOptions;
}
|
class AddEscrowAmountToPuzzles < ActiveRecord::Migration
def change
add_column :puzzles, :escrow_amount, :integer
end
end
|
real = float(input('quanto de dinheiro na sua carteira você tem?'))
a = real / 5.3
print('com',real,'você pode comprar',a,'dolarés')
|
Contribution: 2019-12-01 20:00
Contribution: 2019-12-01 20:01
Contribution: 2019-12-01 20:02
Contribution: 2019-12-01 20:03
Contribution: 2019-12-02 20:00
Contribution: 2019-12-02 20:01
Contribution: 2019-12-03 20:00
Contribution: 2019-12-04 20:00
Contribution: 2019-12-05 20:00
Contribution: 2019-12-08 20:00
Contribution: 2019-12-08 20:01
Contribution: 2019-12-09 20:00
Contribution: 2019-12-09 20:01
Contribution: 2019-12-09 20:02
Contribution: 2019-12-09 20:03
Contribution: 2019-12-09 20:04
Contribution: 2019-12-11 20:00
Contribution: 2019-12-11 20:01
Contribution: 2019-12-11 20:02
Contribution: 2019-12-11 20:03
Contribution: 2019-12-12 20:00
Contribution: 2019-12-13 20:00
Contribution: 2019-12-13 20:01
Contribution: 2019-12-13 20:02
Contribution: 2019-12-13 20:03
Contribution: 2019-12-14 20:00
Contribution: 2019-12-14 20:01
Contribution: 2019-12-15 20:00
Contribution: 2019-12-15 20:01
Contribution: 2019-12-15 20:02
Contribution: 2019-12-15 20:03
Contribution: 2019-12-15 20:04
Contribution: 2019-12-16 20:00
Contribution: 2019-12-16 20:01
Contribution: 2019-12-17 20:00
Contribution: 2019-12-17 20:01
Contribution: 2019-12-17 20:02
Contribution: 2019-12-18 20:00
Contribution: 2019-12-20 20:00
Contribution: 2019-12-20 20:01
Contribution: 2019-12-21 20:00
Contribution: 2019-12-21 20:01
Contribution: 2019-12-23 20:00
Contribution: 2019-12-23 20:01
Contribution: 2019-12-23 20:02
Contribution: 2019-12-24 20:00
Contribution: 2019-12-24 20:01
Contribution: 2019-12-24 20:02
Contribution: 2019-12-24 20:03
Contribution: 2019-12-25 20:00
Contribution: 2019-12-25 20:01
Contribution: 2019-12-25 20:02
Contribution: 2019-12-27 20:00
Contribution: 2019-12-27 20:01
Contribution: 2019-12-27 20:02
Contribution: 2019-12-27 20:03
Contribution: 2019-12-27 20:04
Contribution: 2019-12-28 20:00
Contribution: 2019-12-28 20:01
Contribution: 2019-12-28 20:02
Contribution: 2019-12-28 20:03
Contribution: 2019-12-28 20:04
Contribution: 2019-12-30 20:00
Contribution: 2019-12-30 20:01
Contribution: 2019-12-30 20:02
Contribution: 2019-12-30 20:03
Contribution: 2019-12-30 20:04
Contribution: 2019-12-31 20:00
Contribution: 2020-01-04 20:00
Contribution: 2020-01-04 20:01
Contribution: 2020-01-04 20:02
Contribution: 2020-01-04 20:03
Contribution: 2020-01-05 20:00
Contribution: 2020-01-05 20:01
Contribution: 2020-01-05 20:02
Contribution: 2020-01-05 20:03
Contribution: 2020-01-06 20:00
Contribution: 2020-01-08 20:00
Contribution: 2020-01-08 20:01
Contribution: 2020-01-08 20:02
Contribution: 2020-01-08 20:03
Contribution: 2020-01-08 20:04
Contribution: 2020-01-09 20:00
Contribution: 2020-01-09 20:01
Contribution: 2020-01-09 20:02
Contribution: 2020-01-09 20:03
Contribution: 2020-01-09 20:04
Contribution: 2020-01-10 20:00
Contribution: 2020-01-10 20:01
Contribution: 2020-01-10 20:02
Contribution: 2020-01-10 20:03
Contribution: 2020-01-11 20:00
Contribution: 2020-01-14 20:00
Contribution: 2020-01-14 20:01
Contribution: 2020-01-14 20:02
Contribution: 2020-01-15 20:00
Contribution: 2020-01-15 20:01
Contribution: 2020-01-16 20:00
Contribution: 2020-01-16 20:01
Contribution: 2020-01-16 20:02
Contribution: 2020-01-17 20:00
Contribution: 2020-01-17 20:01
Contribution: 2020-01-18 20:00
Contribution: 2020-01-18 20:01
Contribution: 2020-01-18 20:02
Contribution: 2020-01-18 20:03
Contribution: 2020-01-20 20:00
Contribution: 2020-01-20 20:01
Contribution: 2020-01-20 20:02
Contribution: 2020-01-21 20:00
Contribution: 2020-01-21 20:01
Contribution: 2020-01-21 20:02
Contribution: 2020-01-21 20:03
Contribution: 2020-01-23 20:00
Contribution: 2020-01-23 20:01
Contribution: 2020-01-27 20:00
Contribution: 2020-01-27 20:01
Contribution: 2020-01-27 20:02
Contribution: 2020-01-27 20:03
Contribution: 2020-01-27 20:04
Contribution: 2020-01-28 20:00
Contribution: 2020-01-29 20:00
Contribution: 2020-01-30 20:00
Contribution: 2020-01-30 20:01
Contribution: 2020-01-30 20:02
Contribution: 2020-01-31 20:00
Contribution: 2020-01-31 20:01
Contribution: 2020-01-31 20:02
Contribution: 2020-01-31 20:03
Contribution: 2020-02-02 20:00
Contribution: 2020-02-04 20:00
Contribution: 2020-02-04 20:01
|
package Test::Some;
our $AUTHORITY = 'cpan:YANICK';
# ABSTRACT: test a subset of tests
$Test::Some::VERSION = '0.2.1';
use 5.10.0;
use strict;
use warnings;
use Test::More;
use List::MoreUtils qw/ none any /;
use Package::Stash;
our %filters;
our $BYPASS = 0;
my @init_namespaces;
sub INIT {
# delaying stuff to INIT
# because Test::Some can be loaded before Test::More if used on the
# prompt
for my $caller ( keys %filters ) {
my $original_subtest = $caller->can('subtest')
or die "no function 'subtest' found in package $caller. Forgot to import Test::More?";
Package::Stash->new($caller)->add_symbol( '&subtest' =>
_subtest_maker( $original_subtest, $caller )
);
}
}
sub import {
my $caller = caller;
my(undef,@filters) = @_;
no warnings 'uninitialized';
@filters = split ',', $ENV{TEST_SOME} unless @filters;
_groom_filter($caller,$_) for @filters;
}
sub _groom_filter {
my( $caller, $filter, $is_tag, $is_negated ) = @_;
return $BYPASS = 1 if $filter eq '~';
return _groom_filter( $caller, $filter, 1, $is_negated )
if $filter =~ s/^://;
return _groom_filter( $caller, $filter, $is_tag, 1 )
if $filter =~ s/^!//;
return _groom_filter( $caller, qr/$filter/, $is_tag, $is_negated )
if $filter =~ s#^/##;
my $sub = ref $filter eq 'CODE' ? $filter
: $is_tag ? sub {
return ref $filter ? any { /$filter/ } keys %_
: $_{$filter};
}
: sub { ref $filter ? /$filter/ : $_ eq $filter };
if( $is_negated ) {
my $prev_sub = $sub;
$sub = sub { not $prev_sub->() };
}
push @{ $filters{$caller} }, $sub;
}
sub _should_be_skipped {
my( $caller, $name, @tags ) = @_;
return none {
my $filter = $_;
{
local( $_, %_ ) = ( $name, map { $_ => 1 } @tags );
$filter->();
}
} eval { @{ $filters{$caller} } };
}
sub _subtest_maker {
my( $orig, $caller ) = @_;
return sub {
my ( $name, $code, @tags ) = @_;
if( _should_be_skipped($caller,$name,@tags) ) {
return if $BYPASS;
$code = sub {
Test::More::plan( skip_all => 'Test::Some skipping' );
$orig->($name, sub { } )
}
}
$orig->( $name, $code );
}
}
1;
__END__
=pod
=encoding UTF-8
=head1 NAME
Test::Some - test a subset of tests
=head1 VERSION
version 0.2.1
=head1 SYNOPSIS
use Test::More;
use Test::Some 'foo';
plant tests => 3;
subtest foo => sub { pass };
# will be skipped
subtest bar => sub { fail };
=head1 DESCRIPTION
This module allows to run a subset of the 'subtest' tests given in a test file.
The module declaration takes a whitelist of the subtests we want to run.
Any subtest that doesn't match any of the whitelist
items will be skipped (or potentially bypassed).
The test files don't even need to be modified, as
the module can also be invoked from the command-line. E.g.,
$ perl -MTest::Some=foo t/tests.t
If no argument is given to the module declaration, the environment
variable C<TEST_SOME> will be used as the defaults. For example, this
is equivalent to the example above:
$ export TEST_SOME=foo
$ perl -MTest::Some t/tests.t
=head2 Whitelist items
=head3 '~'
Tells Test::Some to bypass the non-whitelisted tests instead of skipping them. That makes for a smaller output, but
the test file would now fail if it has a C<plan tests => $n> line (as we'll only report on C<$n - bypassed> tests).
=head3 Subtest name
At its most simple, the names of the subtests we want to run can be passed.
# run subtests 'foo' and 'bar'
use Test::Some 'foo', 'bar';
=head3 Negation
An item prefixed with a bang (!) is negated.
use Test::Some '!foo'; # run all tests but 'foo'
Note that a subtest is run if it matches any item in the whitelist, so
use Test::Some '!foo', '!bar';
will run all tests as `foo` is not `bar` and vice versa.
=head3 Regular expression
A string beginning with a slash (/), or a regular expression object
will be considered to be a regular expression to be compared against the
subtest name
use Test::Some '/foo'; # only tests with 'foo' in their name
# equivalent to
use Test::Some qr/foo/;
=head3 Tags
Strings prefixed with a colon (:) are considered to be tags.
# run all tests with the 'basic' tag
use Test::Some ':basic';
Tags can be assigned to a subtest by putting them
after the coderef. E.g.,
subtest foo, sub {
...
}, 'tag1', 'tag2';
Test::More's subtest ignore those trailing arguments, so they be put there without
breaking backward compatibility. If you want to give more visibility to those
tags, you can also do
subtest foo => $_, 'tag1', 'tag2', for sub {
...;
};
(that neat trick, incidentally, was pointed out by aristotle)
=head3 Code
A coderef can be passed. It'll have the subtest name and its tags passed in as
C<$_> and C<%_>, respectively.
# run tests with tags 'important' *and* 'auth'
use Test::Some sub {
$_{important} and $_{auth}
};
=head1 SEE ALSO
* L<http://techblog.babyl.ca/entry/test-some> - introduction blog entry
=head1 AUTHOR
Yanick Champoux <yanick@cpan.org>
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2015 by Yanick Champoux.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
|
/*
* Copyright 2018 phData Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.phdata.retirementage.filters
import io.phdata.retirementage.domain._
import io.phdata.retirementage.storage.HdfsStorage
import io.phdata.retirementage.{SparkTestBase, TestObjects}
import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.types._
import org.scalatest.FunSuite
class TableFilterTest extends FunSuite with SparkTestBase {
val table = DatedTable("table1", "parquet", "date", 1, None, None, None)
val database = Database("default", Seq(table))
test("Filter out a date when column is unix time seconds") {
val table = DatedTable("table1", "parquet", "date", 1, None, None, None)
val database = Database("default", Seq(table))
val schema = StructType(StructField("date", LongType, false) :: Nil)
val data = TestObjects.smallDatasetSeconds
val df = createDataFrame(TestObjects.smallDatasetSeconds, schema)
val filter = getDatedFrameFilter(database, table, df)
assertResult(2)(filter.expiredRecordsCount())
assertResult(1)(filter.newDatasetCount())
}
test("show expired records") {
val table = DatedTable("table1", "parquet", "date", 1, None, None, None)
val database = Database("default", Seq(table))
val schema = StructType(StructField("date", LongType, nullable = false) :: Nil)
val data = TestObjects.smallDatasetSeconds
val df = createDataFrame(data, schema)
val filter = getDatedFrameFilter(database, table, df)
assertResult(true)(filter.hasExpiredRecords())
}
test("get expired records count") {
val table = DatedTable("table1", "parquet", "date", 1, None, None, None)
val database = Database("default", Seq(table))
val schema = StructType(StructField("date", LongType, false) :: Nil)
val data = TestObjects.smallDatasetSeconds
val df = createDataFrame(data, schema)
val filter = getDatedFrameFilter(database, table, df)
assertResult(2)(filter.expiredRecordsCount())
}
test("dry run on children doesn't change datasets") {}
test("show no expired records") {
val table = DatedTable("table1", "parquet", "date", 1000000000, None, None, None)
val database = Database("default", Seq(table))
val schema = StructType(StructField("date", LongType, nullable = false) :: Nil)
val data = TestObjects.smallDatasetSeconds
val df = createDataFrame(data, schema)
val filter = getDatedFrameFilter(database, table, df)
assertResult(false)(filter.hasExpiredRecords())
}
test("Filter out a date when column is unix time millis") {
val table = DatedTable("table1", "parquet", "date", 1, None, None, None)
val database = Database("default", Seq(table))
val data = TestObjects.smallDatasetSeconds
val schema = StructType(StructField("date", LongType, false) :: Nil)
val df = createDataFrame(data, schema)
val filter = getDatedFrameFilter(database, table, df)
assertResult(2)(filter.expiredRecordsCount())
}
test("Filter out child dataset") {
val parentSchema = StructType(
StructField("parentKey", LongType, false) :: StructField("date", LongType, false) :: Nil)
val childSchema = StructType(
StructField("childKey", LongType, false) :: StructField("col1", StringType, false) :: Nil)
val parentTableName = writeTestTable(TestObjects.parentDataset, parentSchema)
val childTableName = writeTestTable(TestObjects.childDataset, childSchema)
val child =
ChildTable(childTableName, "parquet", List(JoinOn("parentKey", "childKey")), None, None)
val parent =
DatedTable(parentTableName, "parquet", "date", 1, None, None, Some(List(child)))
val database = Database("default", Seq(parent))
val parentFilter = new DatedTableFilter(database, parent) with HdfsStorage
val reports = parentFilter.doFilter(true)
val parentReport = reports.filter(_.qualifiedTableName == s"default.$parentTableName").head
assertResult(true)(reports.forall(_.recordsRemoved))
assertResult(Some(1))(parentReport.newDataset.get.count)
}
test("Don't filter out child dataset with a hold") {
val parentSchema = StructType(
StructField("parentKey", LongType, false) :: StructField("date", LongType, false) :: Nil)
val childSchema = StructType(
StructField("childKey", LongType, false) :: StructField("col1", StringType, false) :: Nil)
val parentTableName = writeTestTable(TestObjects.parentDataset, parentSchema)
val childTableName = writeTestTable(TestObjects.childDataset, childSchema)
val child = ChildTable(childTableName,
"parquet",
List(JoinOn("parentKey", "childKey")),
Some(Hold(true, "legal", "legal@client.biz")),
None)
val parent =
DatedTable(parentTableName, "parquet", "date", 1, None, None, Some(List(child)))
val database = Database("default", Seq(parent))
val parentFilter = new DatedTableFilter(database, parent) with HdfsStorage
val reports = parentFilter.doFilter(true)
assertResult(false)(reports.forall(_.recordsRemoved))
val childReport = reports.filter(_.qualifiedTableName == s"default.$childTableName").head
assertResult(None)(childReport.newDataset)
}
test("Undo deletions") {
val parentSchema = StructType(
StructField("parentKey", LongType, false) :: StructField("date", LongType, false) :: Nil)
val childSchema = StructType(
StructField("childKey", LongType, false) :: StructField("col1", StringType, false) :: Nil)
val parentTableName = writeTestTable(TestObjects.parentDataset, parentSchema)
val childTableName = writeTestTable(TestObjects.childDataset, childSchema)
val child =
ChildTable(childTableName, "parquet", List(JoinOn("parentKey", "childKey")), None, None)
val table =
DatedTable(parentTableName, "parquet", "date", 1, None, None, Some(List(child)))
val database = Database("default", Seq(table))
val parentFilter = new DatedTableFilter(database, table) with HdfsStorage
parentFilter.doFilter(false, false)
val reports = parentFilter.undoDeletions()
reports.foreach(println)
assertResult(true)(reports.forall(_.recordsRemoved))
val childReport = reports.filter(_.qualifiedTableName == s"default.$childTableName").head
assertResult(s"file:/tmp/$childTableName")(childReport.newDataset.get.location)
val parentReport = reports.filter(_.qualifiedTableName == s"default.$parentTableName").head
assertResult(s"file:/tmp/$parentTableName")(parentReport.newDataset.get.location)
}
def getDatedFrameFilter(database: Database, table: DatedTable, frame: DataFrame) = {
class TestTableFilter(database: Database, table: DatedTable)
extends DatedTableFilter(database, table)
with HdfsStorage {
override lazy val currentFrame: DataFrame = frame
override def removeRecords(computeCountsFlag: Boolean,
dryRun: Boolean,
qualifiedTableName: String,
storageType: String,
currentFrame: DataFrame,
filteredFrame: DataFrame): RetirementReport = {
RetirementReport(
qualifiedTableName,
true,
DatasetReport("", Some(currentDatasetCount)),
Some(
DatasetReport(getCurrentDatasetLocation(s"${database.name}.${table.name}"),
Some(filteredFrame.count()))),
None
)
}
}
new TestTableFilter(database, table)
}
test("filter out nested related datasets") {}
def getRelatedFrameFilter(database: Database,
table: ChildTable,
frame: DataFrame,
parent: TableFilter) = {
class TestTableFilter(database: Database, table: ChildTable)
extends ChildTableFilter(database, table, parent)
with HdfsStorage {
override lazy val currentFrame: DataFrame = frame
override def removeRecords(computeCountsFlag: Boolean,
dryRun: Boolean,
qualifiedTableName: String,
storageType: String,
currentFrame: DataFrame,
filteredFrame: DataFrame): RetirementReport = {
RetirementReport(
qualifiedTableName,
true,
DatasetReport("", Some(currentDatasetCount)),
Some(
DatasetReport(getCurrentDatasetLocation(s"${database.name}.${table.name}"),
Some(filteredFrame.count()))),
None
)
}
}
new TestTableFilter(database, table)
}
}
|
# MinimalUI
MinimalUI 是一个基于 Vue 的简约UI库,提供了常见的,如:`Button` , `Grid` 等组件。

|
package com.oliveroneill.wilt.data
import androidx.lifecycle.MutableLiveData
import androidx.paging.PagedList
import com.google.firebase.functions.FirebaseFunctionsException
import com.oliveroneill.wilt.Data
import com.oliveroneill.wilt.Event
import com.oliveroneill.wilt.Message
import com.oliveroneill.wilt.data.dao.ArtistRank
import com.oliveroneill.wilt.data.dao.PlayHistoryDao
import com.oliveroneill.wilt.viewmodel.PlayHistoryNetworkState
import com.oliveroneill.wilt.viewmodel.PlayHistoryState
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.ZoneId
import java.util.concurrent.Executor
import java.util.concurrent.Executors
class ArtistRankBoundaryCallback(
private val dao: PlayHistoryDao,
private val firebase: FirebaseAPI,
private val loadingState: MutableLiveData<Message<PlayHistoryState>>,
private val pageSize: Long,
private val executor: Executor = Executors.newSingleThreadExecutor()
): PagedList.BoundaryCallback<ArtistRank>() {
/**
* All dates in the BigQuery database are in GMT timezone
*/
private val gmtZone = ZoneId.of("GMT")
/**
* Keep track of whether the current week has been refreshed, so that we can update it once.
* We can't always update it because we get stuck in a loop calling [onItemAtFrontLoaded].
* This flag should be good enough to just update the current week once every time the app is started
*/
private var refreshedCurrentWeek = false
/**
* We need to keep track of whether we're just refreshing the current week, so that we don't unnecessarily
* try and load the next page
*/
private var refreshingCurrentWeek = false
/**
* Database returned 0 items. We should query the backend for more items.
*/
override fun onZeroItemsLoaded() {
val endDate = LocalDate.now()
// Ensure requests are always run from the start of the week to avoid missing
// earlier plays
.with(DayOfWeek.MONDAY)
// The last date we'll request from is one week ahead of now. We add one week since otherwise the
// query might not include the current week
.plusWeeks(1)
val end = endDate.atStartOfDay(gmtZone).toEpochSecond()
// Each page is a week, so we subtract weeks to decide what to request
// Increasing the page size seems to fix scrolling issues
val weeksToRequest = pageSize * 2
val startDate = endDate.minusWeeks(weeksToRequest)
val start = startDate.atStartOfDay(gmtZone).toEpochSecond()
topArtists(start, end, firstLoad = true)
}
/**
* Load items that are more recent than [itemAtFront]
*/
override fun onItemAtFrontLoaded(itemAtFront: ArtistRank) {
// If we've just refreshed the current week then don't try and load another page
if (refreshingCurrentWeek) {
// Next load we can try again
refreshingCurrentWeek = false
return
}
// Ensure requests are always run from the start of the week to avoid missing
// earlier plays
val date = itemAtFront.date.with(DayOfWeek.MONDAY)
// In most cases date will be the current week and we should refresh this since it will change before
// the week ends. We'll only refresh this once to avoid constantly refreshing and after that
// we'll skip this week
val startDate = if (refreshedCurrentWeek) date.plusWeeks(1) else date
// Indicate that we're refreshing the current week
if (!refreshedCurrentWeek) refreshingCurrentWeek = true
refreshedCurrentWeek = true
val start = startDate.atStartOfDay(gmtZone).toEpochSecond()
// Each page is a week, so we subtract weeks to decide what to request
val endDate = startDate.plusWeeks(pageSize)
val end = endDate.atStartOfDay(gmtZone).toEpochSecond()
topArtists(start, end)
}
/**
* Load items that are older than [itemAtEnd]
*/
override fun onItemAtEndLoaded(itemAtEnd: ArtistRank) {
// Ensure requests are always run from the start of
// the week to avoid missing
// earlier plays
val date = itemAtEnd.date.with(DayOfWeek.MONDAY)
// Subtract 1 week so that we don't include the week we've already got
val endDate = date.minusWeeks(1)
val end = endDate.atStartOfDay(gmtZone).toEpochSecond()
// Each page is a week, so we subtract weeks to decide what to request
val startDate = endDate.minusWeeks(pageSize)
val start = startDate.atStartOfDay(gmtZone).toEpochSecond()
topArtists(start, end, loadingFromTop = false)
}
private fun topArtists(start: Long, end: Long, firstLoad: Boolean = false, loadingFromTop: Boolean = true) {
// Update state
val state = if (loadingFromTop) {
PlayHistoryNetworkState.LoadingFromTop
} else {
PlayHistoryNetworkState.LoadingFromBottom
}
loadingState.postValue(Data(PlayHistoryState.LoggedIn(state)))
firebase.topArtistsPerWeek(start.toInt(), end.toInt()) { result ->
result.onSuccess {
// If this is the initial load and there's no data available then
// we should update the UI
if (firstLoad && it.isEmpty()) {
loadingState.postValue(
Data(
PlayHistoryState.LoggedIn(PlayHistoryNetworkState.NoRows)
)
)
return@onSuccess
}
// If the page size is greater than 1 then we've retrieved more than just the
// current week, so there could be more data in the next page. Therefore
// this isn't just a refresh of the current week
if (it.size > 1) refreshingCurrentWeek = false
executor.execute {
// We update the loading state before inserting to avoid jank from
// the inserted elements appearing above the loading spinner
loadingState.postValue(
Data(
PlayHistoryState.LoggedIn(PlayHistoryNetworkState.NotLoading)
)
)
dao.insert(it)
}
}.onFailure {
// Check whether we've logged out
if (it is FirebaseFunctionsException &&
it.code == FirebaseFunctionsException.Code.UNAUTHENTICATED) {
// Send back a logged out error
loadingState.postValue(Event(PlayHistoryState.LoggedOut))
// Short circuit
return@onFailure
}
val failure = if (loadingFromTop) {
PlayHistoryNetworkState.FailureAtTop(
it.localizedMessage ?: it.message ?: "Unknown error"
// Retry
) { topArtists(start, end, firstLoad, loadingFromTop) }
} else {
PlayHistoryNetworkState.FailureAtBottom(
it.localizedMessage ?: it.message ?: "Unknown error"
// Retry
) { topArtists(start, end, firstLoad, loadingFromTop) }
}
loadingState.postValue(Data(PlayHistoryState.LoggedIn(failure)))
}
}
}
}
|
// style dependencies
import '../../../style/core/default'
import '../../../icon/style/themes/default'
import './default.less'
|
```bash
$ cd $HADOOP_HOME
$ ./bin/stop-all.sh
$ ./bin/start-all.sh
```
|
<?php
echo '<div class="user-activity">';
$params['post']->full_view = true;
$user = ossn_user_by_guid($params['post']->poster_guid);
if ($params['post']->type == 'user') {
$vars = ossn_wallpost_to_item($params['post']);
echo ossn_wall_view_template($vars);
}
if ($params['post']->type == 'group') {
$vars = ossn_wallpost_to_item($params['post']);
$vars['show_group'] = true;
echo ossn_wall_view_template($vars);
}
echo '</div>';
|
package com.wire.backups.exports.ios.database
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import java.util.UUID
import kotlin.test.assertEquals
import kotlin.test.assertTrue
@Disabled
class ConversationsConverterKtTest {
@Test
fun `test get conversations`() {
val data = withDatabase(
"ignored-assets/store.wiredatabase"
) {
getConversations(UUID.randomUUID())
}
assertTrue { data.isNotEmpty() }
println(data)
println(data.size)
assertEquals(140, data.size)
}
}
|
#!/usr/bin/env perl
# {no strict; *{p} = sub { print YAML::Dump(@_) }}
use Markapl;
package MyView;
use Markapl;
sub simple1 {
p {
outs "Let's visit my ";
a(href => "http://example.com") { "Homepage" };
};
}
sub simple2 {
p {
a(href => "http://example.com") { "Homepage" };
outs " is here.";
};
}
sub simple3 {
p {
outs "My ";
a(href => "http://example.com") { "Homepage" };
outs " is here.";
};
}
package main;
use Test::More;
use Test::HTML::Lint;
plan tests => 12;
{
my $html = MyView->render("simple1");
diag $html;
like($html, qr/<p>.+<\/p>/s);
like($html, qr/<a.+>.+<\/a>/s);
html_ok($html);
is($html, qq{<p>Let's visit my <a href="http://example.com">Homepage</a></p>});
}
{
my $html = MyView->render("simple2");
diag $html;
like($html, qr/<p>.+<\/p>/s);
like($html, qr/<a.+>.+<\/a>/s);
html_ok($html);
is($html, qq{<p><a href="http://example.com">Homepage</a> is here.</p>});
}
{
my $html = MyView->render("simple3");
diag $html;
like($html, qr/<p>.+<\/p>/s);
like($html, qr/<a.+>.+<\/a>/s);
html_ok($html);
is($html, qq{<p>My <a href="http://example.com">Homepage</a> is here.</p>});
}
|
package com.example.koakptutorial.data
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
interface OpenWeatherMapApi {
@GET("weather")
fun geoCoordinate
(@Query("lat") latitude : String,
@Query("lon") longitude : String
) : Call<OpenWeatherMapResponse>
@GET("weather")
fun getByCityName
(@Query("q") cityName : String
) : Call<OpenWeatherMapResponse>
}
|
using System.Data.Entity;
using Parser.Common.Constants.Configuration;
using Parser.Common.Logging.Models;
namespace Parser.Common.Logging
{
public class LoggingServiceDbContext : DbContext, ILoggingServiceDbContext
{
public LoggingServiceDbContext()
: base($"name={ConnectionStrings.ParserDbConnectionString}")
{
}
public virtual IDbSet<LogEntry> LogEntries { get; set; }
}
}
|
cookbook_file "/usr/share/elasticsearch/config/logging.yml" do
source "logging.yml"
owner "elasticsearch"
group "elasticsearch"
mode "0755"
end
|
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.websocket.javax.tests.coders;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;
/**
* Decode Date
*/
public class DateDecoder implements Decoder.Text<Date>
{
private static final TimeZone GMT = TimeZone.getTimeZone("GMT");
@Override
public Date decode(String s) throws DecodeException
{
try
{
SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
format.setTimeZone(GMT);
return format.parse(s);
}
catch (ParseException e)
{
throw new DecodeException(s, e.getMessage(), e);
}
}
@Override
public void destroy()
{
CoderEventTracking.getInstance().addEvent(this, "destroy()");
}
@Override
public void init(EndpointConfig config)
{
CoderEventTracking.getInstance().addEvent(this, "init(EndpointConfig)");
}
@Override
public boolean willDecode(String s)
{
CoderEventTracking.getInstance().addEvent(this, "willDecode(String)");
return true;
}
}
|
# Welcome to Scoutify!
Scoutify is a simple Python library for [Spotify Web API](https://developer.spotify.com/documentation/web-api/).
Please make an app from Spotify developer's page first before using this library
and keep in mind that Spotify requires authentication before using their API.
## Installation
Install or upgrade scoutify with:
```bash
pip install scoutify --upgrade
```
## Getting Started
Usage example
```python
from scoutify import Scoutify
sp = Scoutify(
client_id='YOUR_CLIENT_ID',
client_secret='YOUR_CLIENT_SECRET',
redirect_url='your_callback_url'
)
sp.set_access_token('OBTAINED ACCESS TOKEN')
result = sp.search(search_type="artist", q="blackpink")
print(result)
```
|
package logging
import (
"fmt"
"github.com/go-errors/errors"
"io"
"io/ioutil"
"log"
"strings"
)
const (
Fatal = iota
Error
Warn
Info
Debug
)
type loggerSimple struct {
logger *log.Logger
level int
out io.Writer
}
func NewSimpleLogger(out io.Writer, level int) Logger {
return &loggerSimple{
logger: log.New(out, "", log.LstdFlags),
level: level,
out: out,
}
}
func NewSimpleLoggerNull() Logger {
return NewSimpleLogger(ioutil.Discard, Fatal)
}
func (l *loggerSimple) ErrorErr(err error) {
if l.level >= Error {
richErr := errors.Wrap(err, 1)
l.logger.Print(richErr.ErrorStack())
}
}
func (l *loggerSimple) Errorf(format string, args ...interface{}) {
if l.level >= Error {
l.logger.Printf(format, args...)
}
}
func (l *loggerSimple) Error(args ...interface{}) {
if l.level >= Error {
l.logger.Print(args...)
}
}
func (l *loggerSimple) Warnf(format string, args ...interface{}) {
if l.level >= Warn {
l.logger.Printf(format, args...)
}
}
func (l *loggerSimple) Warn(args ...interface{}) {
if l.level >= Warn {
l.logger.Print(args...)
}
}
func (l *loggerSimple) Infof(format string, args ...interface{}) {
if l.level >= Info {
l.logger.Printf(format, args...)
}
}
func (l *loggerSimple) Info(args ...interface{}) {
if l.level >= Info {
l.logger.Print(args...)
}
}
func (l *loggerSimple) Debugf(format string, args ...interface{}) {
if l.level >= Debug {
l.logger.Printf(format, args...)
}
}
func (l *loggerSimple) Debug(args ...interface{}) {
if l.level >= Debug {
l.logger.Print(args...)
}
}
func (l *loggerSimple) WithContext(fields map[string]interface{}) Logger {
elements := make([]string, 0)
elements = append(elements, l.logger.Prefix())
for k, v := range fields {
elements = append(elements, fmt.Sprintf("%s=%v", k, v))
}
prefix := strings.Join(elements, " ")
return &loggerSimple{
logger: log.New(l.out, prefix, log.LstdFlags),
level: l.level,
out: l.out,
}
}
|
package io.apptik.roxy;
import org.reactivestreams.Processor;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static io.apptik.roxy.Roxy.TePolicy.PASS;
import static io.apptik.roxy.Roxy.TePolicy.WRAP;
/**
* Roxy implementation using Reactive Streams
*/
public abstract class RSProcProxy<P extends Publisher> implements Roxy<P> {
private final Processor proc;
private final TePolicy tePolicy;
private final Map<Publisher, Subscription> subscriptions = new ConcurrentHashMap<>();
public RSProcProxy(Processor proc, TePolicy tePolicy) {
this.proc = proc;
this.tePolicy = tePolicy;
}
/**
* Subscribes RSProcProxy to {@link Publisher}.
* If there is no RSProcProxy with the specific tag a new one will be created
*
* @param publisher the Publisher to subscribe to
*/
@Override
public Removable addUpstream(final Publisher publisher) {
publisher.subscribe(new Subscriber() {
@Override
public void onSubscribe(final Subscription s) {
subscriptions.put(publisher, s);
s.request(Long.MAX_VALUE);
}
@Override
public void onNext(Object o) {
proc.onNext(o);
}
@Override
public void onError(Throwable t) {
if (tePolicy.equals(WRAP)) {
proc.onNext(new Event.ErrorEvent(t));
} else if (tePolicy.equals(PASS)) {
proc.onError(t);
}
}
@Override
public void onComplete() {
if (tePolicy.equals(WRAP)) {
proc.onNext(Event.COMPLETE);
} else if (tePolicy.equals(PASS)) {
proc.onComplete();
}
}
});
return new Removable() {
@Override
public void remove() {
removeUpstream(publisher);
}
};
}
/**
* Unsubscribe {@link Publisher} from a RSProcProxy
*
* @param publisher the Publisher to unsubscribe from
*/
@Override
public void removeUpstream(Publisher publisher) {
synchronized (subscriptions) {
Subscription s = subscriptions.get(publisher);
if (s != null) {
s.cancel();
subscriptions.remove(publisher);
}
}
}
@Override
public P pub() {
//make sure we expose it as Publisher hide proxy's identity
return hide(proc);
}
@Override
public <T> P pub(Class<T> filterClass) {
return filter(proc, filterClass);
}
@Override
public void emit(Object event) {
proc.onNext(event);
}
@Override
public void complete() {
proc.onComplete();
}
@Override
public TePolicy tePolicy() {
return tePolicy;
}
@Override
public void clear() {
synchronized (subscriptions) {
for (Subscription s : subscriptions.values()) {
s.cancel();
}
subscriptions.clear();
}
}
/**
* Hides processor identity
*
* @param processor
* @return
*/
protected abstract P hide(Processor processor);
protected abstract <T> P filter(Processor processor, Class<T> filterClass);
}
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Guzzle\Http\Exception\ClientErrorResponseException;
class ApiServiceController extends Controller
{
public static function postApi($table, $api_url, $method, $params = null, $token = null){
$client = new Client();
$url = api_domain(). '/' . $table.'/'.$api_url;
if($params == null) $params = [];
try{
$response = $client->request($method, $url, [
'headers' => [
'Content-Type' => 'application/json',
'auth-token' => $token,
],
'json' => $params,
]);
}catch(\Exception $e){
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
return ['error' => $responseBodyAsString];
}
$res = json_decode($response->getBody()->getContents());
return $res;
}
}
|
import 'dart:async' show Future;
import 'dart:io' show File;
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tailor_made/constants/mk_colors.dart';
import 'package:tailor_made/utils/mk_image_choice_dialog.dart';
import 'package:tailor_made/utils/mk_image_utils.dart';
import 'package:tailor_made/utils/mk_theme.dart';
import 'package:tailor_made/widgets/_partials/mk_loading_spinner.dart';
import 'package:tailor_made/widgets/_partials/mk_touchable_opacity.dart';
class MkProfileAvatar extends StatefulWidget {
const MkProfileAvatar({
Key key,
this.radius = 32.0,
this.imageUrl,
this.simple = false,
this.onPickImage,
}) : super(key: key);
final double radius;
final String imageUrl;
final bool simple;
final ValueSetter<File> onPickImage;
@override
MkProfileAvatarState createState() => MkProfileAvatarState(imageUrl);
}
class MkProfileAvatarState extends State<MkProfileAvatar> {
MkProfileAvatarState(this.imageUrl);
String imageUrl;
Image image;
bool isUploading = false;
@override
void didUpdateWidget(MkProfileAvatar oldWidget) {
super.didUpdateWidget(oldWidget);
if (imageUrl != widget.imageUrl) {
setState(() => imageUrl = widget.imageUrl);
}
}
@override
Widget build(BuildContext context) {
final _borderRadius = BorderRadius.circular(45.0);
return SizedBox.fromSize(
size: Size.square(widget.radius * 2),
child: Stack(
children: <Widget>[
Positioned.fill(
child: Material(
color: MkColors.light_grey.withOpacity(.2),
clipBehavior: Clip.hardEdge,
borderRadius: _borderRadius,
child: _buildImage(),
),
),
Align(
alignment: const Alignment(1.15, 1.05),
child: SizedBox.fromSize(
size: const Size.square(35.0),
child: DecoratedBox(
decoration: BoxDecoration(
color: MkColors.primary,
shape: BoxShape.circle,
border: Border.all(
color: Colors.white,
width: 2.0,
),
),
child: MkTouchableOpacity(
child: const Icon(
Icons.add,
color: Colors.white,
),
onPressed: () => _handlePhotoButtonPressed(context),
),
),
),
),
],
),
);
}
Future<void> _handlePhotoButtonPressed(BuildContext context) async {
final source = await mkImageChoiceDialog(context: context);
if (source == null) {
return;
}
File file;
try {
file = await ImagePicker.pickImage(source: source);
print("File path: " + file.path);
} on PlatformException catch (e) {
print("Error while picking the file: " + e.toString());
}
if (file == null) {
return;
}
if (widget.onPickImage != null) {
final _file = await MkImageUtils(context: context, file: file).resize();
widget.onPickImage(_file);
}
setState(() {
image = Image.file(
file,
fit: BoxFit.cover,
alignment: Alignment.topCenter,
);
isUploading = true;
});
}
Widget _buildImage() {
print([imageUrl]);
final _color = MkColors.dark.shade400;
return imageUrl != null || image != null
? isUploading == false
? CachedNetworkImage(
placeholder: MkLoadingSpinner(
size: widget.radius / 2,
),
imageUrl: imageUrl,
fit: BoxFit.cover,
)
: image
: widget.simple
? const SizedBox()
: SizedBox(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Icon(
Icons.photo_camera,
color: _color,
size: 32.0,
),
Text(
"Upload\nPhoto",
style: MkTheme.of(context).button.copyWith(color: _color),
textAlign: TextAlign.center,
),
],
),
);
}
}
|
import 'package:meta/meta.dart';
/// Утилиты работы с датами.
///
/// См. также [Utils].
class DateUtils {
/// Check if [a] and [b] are on the same day.
static bool isSameDay(DateTime a, DateTime b) {
return a.year == b.year && a.month == b.month && a.day == b.day;
}
/// Returns [DateTime] for the beginning of the day (00:00:00).
///
/// (2020, 4, 9, 16, 50) -> (2020, 4, 9, 0, 0)
static DateTime startOfDay(DateTime dateTime) =>
_date(dateTime.isUtc, dateTime.year, dateTime.month, dateTime.day);
/// Returns [DateTime] for the beginning of the next day (00:00:00).
///
/// (2020, 4, 9, 16, 50) -> (2020, 4, 10, 0, 0)
static DateTime startOfNextDay(DateTime dateTime) =>
_date(dateTime.isUtc, dateTime.year, dateTime.month, dateTime.day + 1);
/// Returns [DateTime] for the beginning of today (00:00:00).
static DateTime startOfToday() => startOfDay(DateTime.now());
/// Creates a copy of [date] but with time replaced with the new values.
static DateTime setTime(DateTime date, int hours, int minutes,
[int seconds = 0, int milliseconds = 0, int microseconds = 0]) =>
_date(date.isUtc, date.year, date.month, date.day, hours, minutes,
seconds, milliseconds, microseconds);
/// Creates a copy of [date] but with the given fields
/// replaced with the new values.
static DateTime copyWith(DateTime date,
{int? year,
int? month,
int? day,
int? hour,
int? minute,
int? second,
int? millisecond,
int? microsecond}) =>
_date(
date.isUtc,
year ?? date.year,
month ?? date.month,
day ?? date.day,
hour ?? date.hour,
minute ?? date.minute,
second ?? date.second,
millisecond ?? date.millisecond,
microsecond ?? date.microsecond);
/// Returns a number of the next month.
static int nextMonth(DateTime date) {
final month = date.month;
return month == DateTime.monthsPerYear ? 1 : month + 1;
}
/// Returns the [DateTime] resulting from adding the given number
/// of months to this [DateTime].
///
/// The result is computed by incrementing the month parts of this
/// [DateTime] by months months, and, if required, adjusting the day part
/// of the resulting date downwards to the last day of the resulting month.
///
/// For example:
/// (2020, 12, 31) -> add 2 months -> (2021, 2, 28).
/// (2020, 12, 31) -> add 1 month -> (2021, 1, 31).
static DateTime addMonths(DateTime date, int months) {
var res = DateUtils.copyWith(date, month: date.month + months);
if (date.day != res.day) res = DateUtils.copyWith(res, day: 0);
return res;
}
/// Returns week number in year.
///
/// The first week of the year is the week that contains
/// 4 or more days of that year (='First 4-day week').
///
/// So if week contains less than 4 days - it's in another year.
///
/// The highest week number in a year is either 52 or 53.
///
/// You can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
///
/// By default it's [DateTime.monday].
static int getWeekNumber(DateTime date, {int? firstWeekday}) {
assert(firstWeekday == null || firstWeekday > 0 && firstWeekday < 8);
if (isWeekInYear(date, date.year, firstWeekday)) {
final startOfTheFirstWeek =
firstDayOfFirstWeek(date.year, firstWeekday: firstWeekday);
final diffInDays = getDaysDifference(date, startOfTheFirstWeek);
return (diffInDays / DateTime.daysPerWeek).floor() + 1;
} else if (date.month == DateTime.december) {
// first of the next year
return 1;
} else {
// last of the previous year
return getWeekNumber(DateTime(date.year - 1, DateTime.december, 31),
firstWeekday: firstWeekday);
}
}
/// Returns number of the last week in [year].
///
/// You can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
///
/// By default it's [DateTime.monday].
///
/// See [getWeekNumber].
static int getLastWeekNumber(int year, {int? firstWeekday}) {
assert(firstWeekday == null || firstWeekday > 0 && firstWeekday < 8);
final start = firstDayOfFirstWeek(year, firstWeekday: firstWeekday);
final end = firstDayOfWeek(DateTime(year, DateTime.december, 31),
firstWeekday: firstWeekday);
final diffInDays = getDaysDifference(end, start);
var res = diffInDays ~/ DateTime.daysPerWeek;
if (isWeekInYear(end, year, firstWeekday)) res++;
return res;
}
/// Returns number of the day in week (starting with 1).
///
/// Difference from [DateTime.weekday] is that
/// you can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
///
/// By default it's [DateTime.monday].
///
static int getDayNumberInWeek(DateTime date, {int? firstWeekday}) {
var res = date.weekday - (firstWeekday ?? DateTime.monday) + 1;
if (res <= 0) res += DateTime.daysPerWeek;
return res;
}
/// Returns number of the day in year.
///
/// Starting with 1.
static int getDayNumberInYear(DateTime date) {
final firstDayOfYear = DateTime(date.year, DateTime.january, 1);
return getDaysDifference(date, firstDayOfYear) + 1;
}
/// Returns the number of days in a given year.
static int getDaysInYear(int year) {
final lastDayOfYear = DateTime(year, DateTime.december, 31);
return getDayNumberInYear(lastDayOfYear);
}
/// Returns count of days between two dates.
///
/// Time will be ignored, so for the dates
/// (2020, 11, 18, 16, 50) and (2020, 11, 19, 10, 00)
/// result will be 1.
///
/// Use this method for count days instead of
/// `a.difference(b).inDays`, since it can return
/// some unexpected result, because of daylight saving hour.
static int getDaysDifference(DateTime a, DateTime b) {
final straight = a.isBefore(b);
final start = startOfDay(straight ? a : b);
final end = startOfDay(straight ? b : a).add(const Duration(hours: 12));
final diff = end.difference(start);
return diff.inHours ~/ 24;
}
/// Checks if [day] is in the first day of a week.
///
/// You can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
///
/// By default it's [DateTime.monday].
static bool isFirstDayOfWeek(DateTime day, {int? firstWeekday}) {
assert(firstWeekday == null || firstWeekday > 0 && firstWeekday < 8);
return isSameDay(firstDayOfWeek(day, firstWeekday: firstWeekday), day);
}
/// Checks if [day] is in the last day of a week.
///
/// You can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
///
/// By default it's [DateTime.monday],
/// so the last day will be [DateTime.sunday].
static bool isLastDayOfWeek(DateTime day, {int? firstWeekday}) {
assert(firstWeekday == null || firstWeekday > 0 && firstWeekday < 8);
return isSameDay(lastDayOfWeek(day, firstWeekday: firstWeekday), day);
}
/// Checks if [day] is in the first day of a month.
static bool isFirstDayOfMonth(DateTime day) {
return day.day == 1;
}
/// Checks if [day] is in the last day of a month.
static bool isLastDayOfMonth(DateTime day) {
return nextDay(day).month != day.month;
}
/// Returns start of the first day of the week for specified [dateTime].
///
/// For example: (2020, 4, 9, 15, 16) -> (2020, 4, 6, 0, 0, 0, 0).
///
/// You can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
///
/// By default it's [DateTime.monday].
static DateTime firstDayOfWeek(DateTime dateTime, {int? firstWeekday}) {
assert(firstWeekday == null || firstWeekday > 0 && firstWeekday < 8);
var days = dateTime.weekday - (firstWeekday ?? DateTime.monday);
if (days < 0) days += DateTime.daysPerWeek;
return _date(
dateTime.isUtc, dateTime.year, dateTime.month, dateTime.day - days);
}
/// Returns start of the first day of the first week in [year].
///
/// For example: (2020, 4, 9, 15, 16) -> (2019, 12, 30, 0, 0, 0, 0).
///
/// You can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
///
/// By default it's [DateTime.monday].
///
/// See [getWeekNumber].
static DateTime firstDayOfFirstWeek(int year, {int? firstWeekday}) {
assert(firstWeekday == null || firstWeekday > 0 && firstWeekday < 8);
final startOfYear = DateTime(year);
return isWeekInYear(startOfYear, year, firstWeekday)
? firstDayOfWeek(startOfYear, firstWeekday: firstWeekday)
: firstDayOfNextWeek(startOfYear, firstWeekday: firstWeekday);
}
/// Returns start of the first day of the next week for specified [dateTime].
///
/// For example: (2020, 4, 9, 15, 16) -> (2020, 4, 13, 0, 0, 0, 0).
///
/// You can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
/// By default it's [DateTime.monday].
static DateTime firstDayOfNextWeek(DateTime dateTime, {int? firstWeekday}) {
assert(firstWeekday == null || firstWeekday > 0 && firstWeekday < 8);
var days = dateTime.weekday - (firstWeekday ?? DateTime.monday);
if (days >= 0) days -= DateTime.daysPerWeek;
return _date(
dateTime.isUtc, dateTime.year, dateTime.month, dateTime.day - days);
}
/// Returns start of the last day of the week for specified [dateTime].
///
/// For example: (2020, 4, 9, 15, 16) -> (2020, 4, 12, 0, 0, 0, 0).
///
/// You can define first weekday (Monday, Sunday or Saturday) with
/// parameter [firstWeekday]. It should be one of the constant values
/// [DateTime.monday], ..., [DateTime.sunday].
///
/// By default it's [DateTime.monday],
/// so the last day will be [DateTime.sunday].
static DateTime lastDayOfWeek(DateTime dateTime, {int? firstWeekday}) {
assert(firstWeekday == null || firstWeekday > 0 && firstWeekday < 8);
var days = (firstWeekday ?? DateTime.monday) - 1 - dateTime.weekday;
if (days < 0) days += DateTime.daysPerWeek;
return _date(
dateTime.isUtc, dateTime.year, dateTime.month, dateTime.day + days);
}
/// Returns [DateTime] that represents a beginning
/// of the first day of the month containing [date].
///
/// Example: (2020, 4, 9, 15, 16) -> (2020, 4, 1, 0, 0, 0, 0).
static DateTime firstDayOfMonth(DateTime date) {
return _date(date.isUtc, date.year, date.month);
}
/// Returns [DateTime] that represents a beginning
/// of the first day of the next month.
///
/// Example: (2020, 4, 9, 15, 16) -> (2020, 5, 1, 0, 0, 0, 0).
static DateTime firstDayOfNextMonth(DateTime dateTime) {
final month = dateTime.month;
final year = dateTime.year;
final nextMonthStart = (month < DateTime.monthsPerYear)
? _date(dateTime.isUtc, year, month + 1, 1)
: _date(dateTime.isUtc, year + 1, 1, 1);
return nextMonthStart;
}
/// Returns [DateTime] that represents a beginning
/// of the last day of the month containing [date].
///
/// Example: (2020, 4, 9, 15, 16) -> (2020, 4, 30, 0, 0, 0, 0).
static DateTime lastDayOfMonth(DateTime dateTime) {
return previousDay(firstDayOfNextMonth(dateTime));
}
/// Returns [DateTime] that represents a beginning
/// of the first day of the year containing [date].
///
/// Example: (2020, 3, 9, 15, 16) -> (2020, 1, 1, 0, 0, 0, 0).
static DateTime firstDayOfYear(DateTime dateTime) {
return _date(dateTime.isUtc, dateTime.year, 1, 1);
}
/// Returns [DateTime] that represents a beginning
/// of the first day of the next year.
///
/// Example: (2020, 3, 9, 15, 16) -> (2021, 1, 1, 0, 0, 0, 0).
static DateTime firstDayOfNextYear(DateTime dateTime) {
return _date(dateTime.isUtc, dateTime.year + 1, 1, 1);
}
/// Returns [DateTime] that represents a beginning
/// of the last day of the year containing [date].
///
/// Example: (2020, 4, 9, 15, 16) -> (2020, 12, 31, 0, 0, 0, 0).
static DateTime lastDayOfYear(DateTime dateTime) {
return _date(dateTime.isUtc, dateTime.year, DateTime.december, 31);
}
/// Проверяет является ли заданная дата текущей.
static bool isCurrentDate(DateTime date) {
final now = DateTime.now();
return isSameDay(date, now);
}
/// Returns number of days in the [month] of the [year].
static int getDaysInMonth(int year, int monthNum) {
assert(monthNum > 0);
assert(monthNum <= 12);
return DateTime(year, monthNum + 1, 0).day;
}
/// Returns same time in the next day.
static DateTime nextDay(DateTime d) {
return copyWith(d, day: d.day + 1);
}
/// Returns same time in the previous day.
static DateTime previousDay(DateTime d) {
return copyWith(d, day: d.day - 1);
}
/// Returns same date in the next year.
static DateTime nextYear(DateTime d) {
return _date(d.isUtc, d.year + 1, d.month, d.day);
}
/// Returns same date in the previous year.
static DateTime previousYear(DateTime d) {
return _date(d.isUtc, d.year - 1, d.month, d.day);
}
/// Returns an iterable of [DateTime] with 1 day step in given range.
///
/// [start] is the start of the rande, inclusive.
/// [end] is the end of the range, exclusive.
///
/// If [start] equals [end], than [start] still will be included in interbale.
/// If [start] less than [end], than empty interable will be returned.
///
/// [DateTime] in result uses [start] timezone.
static Iterable<DateTime> generateWithDayStep(
DateTime start, DateTime end) sync* {
if (end.isBefore(start)) return;
var date = start;
do {
yield date;
date = nextDay(date);
} while (date.isBefore(end));
}
/// Checks if week, that contains [date] is in [year].
@visibleForTesting
static bool isWeekInYear(DateTime date, int year, int? firstWeekday) {
const requiredDaysInYear = 4;
final startWeekDate = firstDayOfWeek(date, firstWeekday: firstWeekday);
final endWeekDate = lastDayOfWeek(date, firstWeekday: firstWeekday);
if (startWeekDate.year == year && endWeekDate.year == year) {
return true;
} else if (endWeekDate.year == year) {
final startYearDate = DateTime(year, DateTime.january, 1);
final daysInPrevYear = getDaysDifference(startYearDate, startWeekDate);
return daysInPrevYear < requiredDaysInYear;
} else if (startWeekDate.year == year) {
final startNextYearDate = DateTime(year + 1, DateTime.january, 1);
final daysInNextYear =
getDaysDifference(endWeekDate, startNextYearDate) + 1;
return daysInNextYear < requiredDaysInYear;
} else {
return false;
}
}
static DateTime _date(bool utc, int year,
[int month = 1,
int day = 1,
int hour = 0,
int minute = 0,
int second = 0,
int millisecond = 0,
int microsecond = 0]) =>
utc
? DateTime.utc(
year, month, day, hour, minute, second, millisecond, microsecond)
: DateTime(
year, month, day, hour, minute, second, millisecond, microsecond);
DateUtils._();
}
|
import requests
import argparse
import sys
aparse = argparse.ArgumentParser(add_help=False)
aparse.add_argument('-u', '--uri', help='the fbopen elasticsearch index uri')
args = vars(aparse.parse_args())
resp = requests.get("{0}{1}".format(args.get('uri'), '/_cluster/health'))
data = resp.json()
#disabling warning for yellow because we're in staging
#if data['status'] == 'yellow':
# print("WARNING: CLUSTER HEALTH IS YELLOW")
# sys.exit(1)
if data['status'] == 'red':
print("ERROR: CLUSTER IS DOWN") #email!
sys.exit(1)
elif data['status'] == 'green': print("All is well. Cluster is green")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.