text
stringlengths 1
22.8M
|
|---|
Circus Girl may refer to:
Circus Girl (film), a 1937 American film
Circus Girl (album) or the title song, by Sherrié Austin, 2011
The Circus Girl, an 1896 stage musical
Circus Girl, a 1957 children's book by Jack Sendak
|
```hcl
output "str" {
value = "str"
}
output "list" {
value = ["a", "b", "c"]
}
output "map" {
value = { foo = "bar" }
}
```
|
```php
<?php
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
*/
namespace Google\Service\Forms;
class FormsEmpty extends \Google\Model
{
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(FormsEmpty::class, 'Google_Service_Forms_FormsEmpty');
```
|
Amphiboloidea is a taxonomic superfamily of air-breathing land snails.
Distribution
Amphibolids are found in Indo-Pacific intertidal mangrove, saltmarsh and estuarine mudflat habitats.
Taxonomy
2005 taxonomy
According to the taxonomy of the Gastropoda (Bouchet & Rocroi, 2005), it is a superfamily in the informal group Basommatophora, within the Pulmonata.
This superfamily has contained only one family, the Amphibolidae.
2007 taxonomy
Golding et al. (2007) have established new families:
Maningrididae Golding, Ponder & Byrne, 2007 - with the only species Maningrida arnhemensis
Phallomedusidae Golding, Ponder & Byrne, 2007
2010 taxonomy
Basommatophora (Siphonarioidea and Amphiboloidea and Hygrophila) have been found polyphyletic and so Jörger et al. (2010) have moved Amphiboloidea to Panpulmonata.
References
Further reading
Golding R. E., Byrne M., Ponder W. F. (2008) "Novel copulatory structures and reproductive functions in Amphiboloidea (Gastropoda, Heterobranchia, Pulmonata)". Invertebrate Biology 127(2): 168–180
Panpulmonata
Taxa named by John Edward Gray
|
The 2007–08 United Counties League season was the 101st in the history of the United Counties League, a football competition in England.
Premier Division
The Premier Division featured 19 clubs which competed in the division last season, along with two new clubs, promoted from Division One:
Kempston Rovers
Sleaford Town
League table
Division One
Division One featured 14 clubs which competed in the division last season, along with two new clubs, relegated from the Premier Division:
Buckingham Town
Ford Sports Daventry, who changed name to Daventry United
Also, Higham Town merged with Rushden Rangers to form new club Rushden & Higham United.
League table
References
External links
United Counties League
9
United Counties League seasons
|
Josia gigantea is a moth of the family Notodontidae first described by Herbert Druce in 1885. It is found from southern Mexico to Colombia.
Larvae have been recorded on Passiflora sexflora and Passiflora apatela in Costa Rica.
External links
"Josia gigantea (Druce 1885)". Tree of Life Web Project. Retrieved December 29, 2019.
Notodontidae of South America
Moths described in 1885
|
```c
/* p12_decr.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 1999.
*/
/* ====================================================================
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (path_to_url"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (path_to_url"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/pkcs12.h>
/* Define this to dump decrypted output to files called DERnnn */
/*
* #define DEBUG_DECRYPT
*/
/*
* Encrypt/Decrypt a buffer based on password and algor, result in a
* OPENSSL_malloc'ed buffer
*/
unsigned char *PKCS12_pbe_crypt(X509_ALGOR *algor, const char *pass,
int passlen, unsigned char *in, int inlen,
unsigned char **data, int *datalen, int en_de)
{
unsigned char *out;
int outlen, i;
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
/* Decrypt data */
if (!EVP_PBE_CipherInit(algor->algorithm, pass, passlen,
algor->parameter, &ctx, en_de)) {
PKCS12err(PKCS12_F_PKCS12_PBE_CRYPT,
PKCS12_R_PKCS12_ALGOR_CIPHERINIT_ERROR);
return NULL;
}
if (!(out = OPENSSL_malloc(inlen + EVP_CIPHER_CTX_block_size(&ctx)))) {
PKCS12err(PKCS12_F_PKCS12_PBE_CRYPT, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!EVP_CipherUpdate(&ctx, out, &i, in, inlen)) {
OPENSSL_free(out);
out = NULL;
PKCS12err(PKCS12_F_PKCS12_PBE_CRYPT, ERR_R_EVP_LIB);
goto err;
}
outlen = i;
if (!EVP_CipherFinal_ex(&ctx, out + i, &i)) {
OPENSSL_free(out);
out = NULL;
PKCS12err(PKCS12_F_PKCS12_PBE_CRYPT,
PKCS12_R_PKCS12_CIPHERFINAL_ERROR);
goto err;
}
outlen += i;
if (datalen)
*datalen = outlen;
if (data)
*data = out;
err:
EVP_CIPHER_CTX_cleanup(&ctx);
return out;
}
/*
* Decrypt an OCTET STRING and decode ASN1 structure if zbuf set zero buffer
* after use.
*/
void *PKCS12_item_decrypt_d2i(X509_ALGOR *algor, const ASN1_ITEM *it,
const char *pass, int passlen,
ASN1_OCTET_STRING *oct, int zbuf)
{
unsigned char *out;
const unsigned char *p;
void *ret;
int outlen;
if (!PKCS12_pbe_crypt(algor, pass, passlen, oct->data, oct->length,
&out, &outlen, 0)) {
PKCS12err(PKCS12_F_PKCS12_ITEM_DECRYPT_D2I,
PKCS12_R_PKCS12_PBE_CRYPT_ERROR);
return NULL;
}
p = out;
#ifdef DEBUG_DECRYPT
{
FILE *op;
char fname[30];
static int fnm = 1;
sprintf(fname, "DER%d", fnm++);
op = fopen(fname, "wb");
fwrite(p, 1, outlen, op);
fclose(op);
}
#endif
ret = ASN1_item_d2i(NULL, &p, outlen, it);
if (zbuf)
OPENSSL_cleanse(out, outlen);
if (!ret)
PKCS12err(PKCS12_F_PKCS12_ITEM_DECRYPT_D2I, PKCS12_R_DECODE_ERROR);
OPENSSL_free(out);
return ret;
}
/*
* Encode ASN1 structure and encrypt, return OCTET STRING if zbuf set zero
* encoding.
*/
ASN1_OCTET_STRING *PKCS12_item_i2d_encrypt(X509_ALGOR *algor,
const ASN1_ITEM *it,
const char *pass, int passlen,
void *obj, int zbuf)
{
ASN1_OCTET_STRING *oct;
unsigned char *in = NULL;
int inlen;
if (!(oct = M_ASN1_OCTET_STRING_new())) {
PKCS12err(PKCS12_F_PKCS12_ITEM_I2D_ENCRYPT, ERR_R_MALLOC_FAILURE);
return NULL;
}
inlen = ASN1_item_i2d(obj, &in, it);
if (!in) {
PKCS12err(PKCS12_F_PKCS12_ITEM_I2D_ENCRYPT, PKCS12_R_ENCODE_ERROR);
return NULL;
}
if (!PKCS12_pbe_crypt(algor, pass, passlen, in, inlen, &oct->data,
&oct->length, 1)) {
PKCS12err(PKCS12_F_PKCS12_ITEM_I2D_ENCRYPT, PKCS12_R_ENCRYPT_ERROR);
OPENSSL_free(in);
return NULL;
}
if (zbuf)
OPENSSL_cleanse(in, inlen);
OPENSSL_free(in);
return oct;
}
IMPLEMENT_PKCS12_STACK_OF(PKCS7)
```
|
```java
Updating interfaces by using `default` methods
Use `DecimalFormat` class to format numbers
Metadata: creating a user-defined file attribute
Increase `PermGen` space as to avoid `OutOfMemory` errors
Supply `toString()` in all classes
```
|
```c++
//
// Aspia Project
//
// This program is free software: you can redistribute it and/or modify
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//
// along with this program. If not, see <path_to_url
//
#include "client/ui/sys_info/sys_info_widget_open_files.h"
#include "common/system_info_constants.h"
#include <QMenu>
namespace client {
//your_sha256_hash----------------------------------
SysInfoWidgetOpenFiles::SysInfoWidgetOpenFiles(QWidget* parent)
: SysInfoWidget(parent)
{
ui.setupUi(this);
ui.tree->setMouseTracking(true);
connect(ui.action_copy_row, &QAction::triggered, this, [this]()
{
copyRow(ui.tree->currentItem());
});
connect(ui.action_copy_value, &QAction::triggered, this, [this]()
{
copyColumn(ui.tree->currentItem(), current_column_);
});
connect(ui.tree, &QTreeWidget::customContextMenuRequested,
this, &SysInfoWidgetOpenFiles::onContextMenu);
connect(ui.tree, &QTreeWidget::itemDoubleClicked,
this, [this](QTreeWidgetItem* item, int /* column */)
{
copyRow(item);
});
connect(ui.tree, &QTreeWidget::itemEntered,
this, [this](QTreeWidgetItem* /* item */, int column)
{
current_column_ = column;
});
}
//your_sha256_hash----------------------------------
SysInfoWidgetOpenFiles::~SysInfoWidgetOpenFiles() = default;
//your_sha256_hash----------------------------------
std::string SysInfoWidgetOpenFiles::category() const
{
return common::kSystemInfo_OpenFiles;
}
//your_sha256_hash----------------------------------
void SysInfoWidgetOpenFiles::setSystemInfo(const proto::system_info::SystemInfo& system_info)
{
ui.tree->clear();
if (!system_info.has_open_files())
{
ui.tree->setEnabled(false);
return;
}
const proto::system_info::OpenFiles& open_files = system_info.open_files();
QIcon item_icon(":/img/folder-share.png");
for (int i = 0; i < open_files.open_file_size(); ++i)
{
const proto::system_info::OpenFiles::OpenFile& open_file =
open_files.open_file(i);
QTreeWidgetItem* item = new QTreeWidgetItem();
item->setIcon(0, item_icon);
item->setText(0, QString::fromStdString(open_file.file_path()));
item->setText(1, QString::fromStdString(open_file.user_name()));
item->setText(2, QString::number(open_file.lock_count()));
ui.tree->addTopLevelItem(item);
}
ui.tree->setColumnWidth(0, 250);
ui.tree->setColumnWidth(1, 120);
ui.tree->setColumnWidth(2, 100);
}
//your_sha256_hash----------------------------------
QTreeWidget* SysInfoWidgetOpenFiles::treeWidget()
{
return ui.tree;
}
//your_sha256_hash----------------------------------
void SysInfoWidgetOpenFiles::onContextMenu(const QPoint& point)
{
QTreeWidgetItem* current_item = ui.tree->itemAt(point);
if (!current_item)
return;
ui.tree->setCurrentItem(current_item);
QMenu menu;
menu.addAction(ui.action_copy_row);
menu.addAction(ui.action_copy_value);
menu.exec(ui.tree->viewport()->mapToGlobal(point));
}
} // namespace client
```
|
```objective-c
//
//
// path_to_url
//
// Unless required by applicable law or agreed to in writing, software
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#pragma once
#if defined(_MSC_VER)
#include <BaseTsd.h>
typedef SSIZE_T ssize_t;
#endif
#include <pybind11/pybind11.h>
namespace paddle {
namespace pybind {
void BindFleetExecutor(pybind11::module* m);
} // namespace pybind
} // namespace paddle
```
|
Veljko Stojnić (born 4 February 1999) is a Serbian professional road cyclist, who currently rides for UCI Continental team .
Major results
2016
Junior National Road Championships
1st Time trial
2nd Road race
2017
Junior National Road Championships
1st Road race
1st Time trial
2nd Overall Belgrade Trophy Milan Panić
8th Time trial, UEC European Junior Road Championships
9th Overall Course de la Paix Juniors
2018
1st Time trial, National Road Championships
6th Time trial, Mediterranean Games
2019
National Road Championships
2nd Road race
2nd Time trial
2020
1st Time trial, National Road Championships
1st Sprints classification, UAE Tour
2nd Overall In the footsteps of the Romans
2021
1st Mountains classification, Czech Cycling Tour
2022
1st Stage 4 Tour de la Guadeloupe
1st Stage 6 Vuelta a Venezuela
National Road Championships
3rd Time trial
4th Road race
2023
Combativity award Stage 3 Giro d'Italia
6th GP Vorarlberg
Grand Tour general classification results timeline
References
External links
1999 births
Living people
Serbian male cyclists
Competitors at the 2018 Mediterranean Games
Mediterranean Games competitors for Serbia
Sportspeople from Sombor
21st-century Serbian people
Competitors at the 2022 Mediterranean Games
|
Abraham II (died 1787) was Greek Orthodox Patriarch of Jerusalem (June/July 1775 – November 13, 1787).
1787 deaths
18th-century Greek Orthodox Patriarchs of Jerusalem
Year of birth unknown
|
```python
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# project = path_to_url
# author Double8
"""
MongodDB
Usage:
python POC-T.py -s mongodb-unauth -aZ "port:27017 country:us"
"""
import pymongo
from plugin.util import host2IP
from plugin.util import checkPortTcp
def poc(url):
ip = host2IP(url).split(':')[0]
port = 27017
try:
if not checkPortTcp(ip, port):
return False
conn = pymongo.MongoClient(ip, port, socketTimeoutMS=3000)
dbs = conn.database_names()
return ip + ' -> ' + '|'.join(dbs) if dbs else False
except Exception:
return False
```
|
The African goshawk (Accipiter tachiro) is an African species of bird of prey in the genus Accipiter which is the type genus of the family Accipitridae.
Description
The African goshawk is a medium to large-sized Accipiter which is mainly grey and rufous with the typical broad-winged and long-tailed shape of its genus. The adult has grey upperparts which tend to be darker in males than in females, the underparts are whitish marked with rufous barring which is more pronounced in males. The underwing is pale rufous, fading to white on some birds and the flight feathers and tail vary from sooty brown to grey with faint grey bars above, white with grey bars below. The bill is black, the cere is greenish-grey, the eyes are yellow, and the legs and feet are yellow. Juveniles are brown above with whitish unterparts and flanks which are boldly blotched with brown. Females weigh , while the smaller males weigh . The wingspan is 1.7 times the bird's total length and in males and in females.
Voice
It is noisy when displaying. Its characteristic clicking call is omitted every 2–3 seconds and sounds to the human ear like two stones being knocked together.
Distribution
From the Western Cape of South Africa north to the southern Democratic Republic of Congo and through east Africa, Somalia to southern Ethiopia, including the islands of Mafia, Unguja (Zanzibar) and Pemba.
Habitat
The African goshawk generally occurs in forest and diverse dense woodland in both lowland and montane areas, but it can also be found in riverine and gallery forest, plantations of exotic trees, parks and large gardens. It can occur in both moist and dry forest, even in isolated patches.
Habits
The African goshawk typically soars above the canopy in the morning in a display flight involving slow wing beats interspersed with gliding, sometimes so high up that the only sign of the birds is its regular clicking call. Its main prey are birds up to the size of hornbills or francolins, but it also feeds on mammals, lizards and sometimes invertebrates. It is an ambush hunter, waiting on a perch until the prey is observed then swooping down to catch it. Pairs occasionally hunt co-operatively at large congregations of prey, such as bat roosts or weaver colonies.
The African goshawk is territorial and the typical courtship display is performed by both sexes when they fly together in an undulated flight while calling loudly, sometimes finishing with a steep dive. The female builds the nest making a platform of sticks lined with fresh foliage, as well as pine needles, lichen and mistletoe. It is normally built on a branch away from the main trunk of a tree, as the species prefers to nest within dense foliage but the nest may also be constructed on top of an old Hadeda ibis nest. African Goshawks have also been recorded taking over the nest of a little sparrowhawk (Accipiter minullus) instead of building their own. One to three eggs are laid in July–December, with a peak in September–November and are incubated mainly or solely by the female for about 35–37 days, while the male regularly brings food to her. The chicks are fed by both parents, fledging at about 30–35 days old but staying within the vicinity of the nest tree for another six weeks or so before becoming fully independent roughly 1–3 months after leaving the nest.
The species has been recorded as being preyed on by the black sparrowhawk (Accipiter melanoleuca), the tawny eagle (Aquila rapax), the Cape eagle-owl (Bubo capensis), the lanner falcon (Falco biarmicus) and the peregrine falcon (Falco peregrinus).
Taxonomy
There are three currently recognised subspecies:
Accipiter tachiro tachiro: Southern Angola to Mozambique and South Africa
Accipiter tachiro sparsimfasciatus: Somalia to northern Democratic Republic of the Congo, Angola, Zambia and Mozambique
Accipiter tachiro pembaensis: Pemba
The African Goshawk is sometimes considered conspecific with the Central African subspecies of the Red-chested goshawk (Accipiter toussenelii).
References
External links
African Goshawk - Species text in The Atlas of Southern African Birds
African goshawk
African goshawk
Birds of prey of Sub-Saharan Africa
African goshawk
Taxonomy articles created by Polbot
|
```python
#!/usr/bin/env python3
# Test remapping of topic name for incoming message
from mosq_test_helper import *
def write_config(filename, port1, port2, port3, protocol_version):
with open(filename, 'w') as f:
f.write("per_listener_settings true\n")
f.write("port %d\n" % (port2))
f.write("listener %d 127.0.0.1\n" % (port3))
f.write("\n")
f.write("connection bridge_sample\n")
f.write("address 127.0.0.1:%d\n" % (port1))
f.write("bridge_attempt_unsubscribe false\n")
f.write("topic # in 0 local/topic/ remote/topic/\n")
f.write("topic prefix/# in 0 local2/topic/ remote2/topic/\n")
f.write("topic +/value in 0 local3/topic/ remote3/topic/\n")
f.write("topic ic/+ in 0 local4/top remote4/tip\n")
f.write("topic clients/total in 0 test/mosquitto/org $SYS/broker/\n")
f.write("notifications false\n")
f.write("restart_timeout 5\n")
f.write("bridge_protocol_version %s\n" % (protocol_version))
def inner_test(bridge, sock, proto_ver):
global connect_packet, connack_packet
if not mosq_test.expect_packet(bridge, "connect", connect_packet):
return 1
bridge.send(connack_packet)
if proto_ver == 5:
opts = mqtt5_opts.MQTT_SUB_OPT_NO_LOCAL | mqtt5_opts.MQTT_SUB_OPT_RETAIN_AS_PUBLISHED
else:
opts = 0
mid = 0
patterns = [
"remote/topic/#",
"remote2/topic/prefix/#",
"remote3/topic/+/value",
"remote4/tipic/+",
"$SYS/broker/clients/total",
]
for pattern in ("remote/topic/#", "remote2/topic/prefix/#", "remote3/topic/+/value"):
mid += 1
subscribe_packet = mosq_test.gen_subscribe(mid, pattern, 0 | opts, proto_ver=proto_ver)
suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver)
if not mosq_test.expect_packet(bridge, "subscribe", subscribe_packet):
return 1
bridge.send(suback_packet)
mid += 1
subscribe_packet = mosq_test.gen_subscribe(mid, "#", 0 | opts, proto_ver=proto_ver)
suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver)
sock.send(subscribe_packet)
if not mosq_test.expect_packet(sock, "suback", suback_packet):
return 1
cases = [
('local/topic/something', 'remote/topic/something'),
('local/topic/some/t/h/i/n/g', 'remote/topic/some/t/h/i/n/g'),
('local/topic/value', 'remote/topic/value'),
# Don't work, #40 must be fixed before
# ('local/topic', 'remote/topic'),
('local2/topic/prefix/something', 'remote2/topic/prefix/something'),
('local3/topic/something/value', 'remote3/topic/something/value'),
('local4/topic/something', 'remote4/tipic/something'),
('test/mosquitto/orgclients/total', '$SYS/broker/clients/total'),
]
for (local_topic, remote_topic) in cases:
mid += 1
remote_publish_packet = mosq_test.gen_publish(
remote_topic, qos=0, mid=mid, payload='', proto_ver=proto_ver)
local_publish_packet = mosq_test.gen_publish(
local_topic, qos=0, mid=mid, payload='', proto_ver=proto_ver)
bridge.send(remote_publish_packet)
match = mosq_test.expect_packet(sock, "publish", local_publish_packet)
if not match:
print("Fail on cases local_topic=%r, remote_topic=%r" % (
local_topic, remote_topic,
))
return 1
return 0
def do_test(proto_ver):
global connect_packet, connack_packet
if proto_ver == 4:
bridge_protocol = "mqttv311"
proto_ver_connect = 128+4
else:
bridge_protocol = "mqttv50"
proto_ver_connect = 5
(port1, port2, port3) = mosq_test.get_port(3)
conf_file = os.path.basename(__file__).replace('.py', '.conf')
write_config(conf_file, port1, port2, port3, bridge_protocol)
rc = 1
keepalive = 60
client_id = socket.gethostname()+".bridge_sample"
connect_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, clean_session=False, proto_ver=proto_ver_connect)
connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver)
client_connect_packet = mosq_test.gen_connect("pub-test", keepalive=keepalive, proto_ver=proto_ver)
client_connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver)
ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ssock.settimeout(4)
ssock.bind(('', port1))
ssock.listen(5)
broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True)
try:
(bridge, address) = ssock.accept()
bridge.settimeout(2)
sock = mosq_test.do_client_connect(
client_connect_packet, client_connack_packet,
port=port2,
)
rc = inner_test(bridge, sock, proto_ver)
sock.close()
bridge.close()
except mosq_test.TestError:
pass
finally:
os.remove(conf_file)
try:
bridge.close()
except NameError:
pass
broker.terminate()
broker.wait()
(stdo, stde) = broker.communicate()
ssock.close()
if rc:
print(stde.decode('utf-8'))
exit(rc)
do_test(proto_ver=4)
do_test(proto_ver=5)
exit(0)
```
|
Bubnov () or Bubnow () is a Russian masculine surname that originates either from a verb bubnit' (to mumble) or from a verb bubenit' (to beat, to ring a bell). its feminine counterpart is Bubnova. The surname may refer to the following notable people:
Aleksandr Bubnov (born 1955), Soviet and Russian football player, coach, analyst, commentator and businessman
Andrei Bubnov (1884–1938), Russian Bolshevik revolutionary
Anton Bubnow (born 1988), Belarusian football player
Ivan Bubnov (1872–1919), Russian marine engineer
(1858–1943), Russian medievalist and linguist, whose specialist field was the medieval mathematics of Western Europe
Varvara Bubnova (1886–1983), Russian painter, graphic artist and pedagogue
Vladimir Bubnov (born 1940), Soviet and Russian football player and coach
See also
:ru:Бубнов, a more extensive list in Russian Wikipedia
References
Russian-language surnames
|
Nibong Tebal is a federal constituency in South Seberang Perai District, Penang, Malaysia, that has been represented in the Dewan Rakyat since 1974.
The federal constituency was created in the 1974 redistribution and is mandated to return a single member to the Dewan Rakyat under the first past the post voting system.
Demographics
https://live.chinapress.com.my/ge15/parliament/PENANG
History
Polling districts
According to the federal gazette issued on 18 July 2023, the Nibong Tebal constituency is divided into 25 polling districts.
Representation history
State constituency
Current state assembly members
Local governments
Election results
References
Penang federal constituencies
|
Sozopolis in Pisidia (), which had been called Apollonia (Ἀπολλωνία) and Apollonias (Ἀπολλωνίας) during Seleucid times, was a town in the former Roman province of Pisidia, and is not to be confused with the Thracian Sozopolis in Haemimonto in present-day Bulgaria. Its site may correspond to present-day Uluborlu in Isparta Province, Turkey.
Location
Sozopolis in Pisidia must have been situated in the border region of that province, since some ancient accounts place it in Phrygia. Whereas older source locate it "Souzon, south of Aglasoun"., modern scholars locate its site near Uluborlu, Isparta Province.
History
Stephanus of Byzantium says that Apollonia in Pisidia (Sozopolis) was originally called Mordiaeon or Mordiaïon (Μορδιάιον), and was celebrated for its quinces. The coins of Apollonia record Alexander the Great as the founder, and also the name of a stream that flowed; by it, the Hippopharas. Two Greek inscriptions of the Roman period copied by Francis Arundell give the full title of the town in that age, "the Boule and Demus of the Apolloniatae Lycii Thraces Coloni," by which he concluded that the city was founded by a Thracian colony established in Lycia, but that conclusion is not universally accepted.
Fragments of the Res Gestae Divi Augusti in Greek have been found in the area.
Sozopolis in Pisidia was the birthplace of Severus of Antioch (born around 456).
The icon of the Theotokos of Pisidian Sozopolis, celebrated by Eastern Orthodox Christians on 3 September, originated in this city. As many other places in the region, the town venerated especially the Archangel Michael and had a church dedicated to him.
Bishopric
Sozopolis sent its bishop and possibly two other representatives to the Council of Constantinople in 381, and its bishop attended the Council of Ephesus in 431.
The see is included in the Catholic Church's list of titular sees.
References
Sources
Seleucid colonies in Anatolia
Former populated places in Turkey
Populated places in Pisidia
Roman towns and cities in Turkey
Titular sees in Asia
|
```glsl
#extension GL_OES_EGL_image_external : require
precision highp float;
varying highp vec2 textureCoordinate;
uniform samplerExternalOES inputImageTexture;
uniform sampler2D curve;
uniform sampler2D greyFrame;
uniform sampler2D layerImage;
void main()
{
lowp vec4 textureColor;
vec4 greyColor;
vec4 layerColor;
float xCoordinate = textureCoordinate.x;
float yCoordinate = textureCoordinate.y;
highp float redCurveValue;
highp float greenCurveValue;
highp float blueCurveValue;
textureColor = texture2D( inputImageTexture, vec2(xCoordinate, yCoordinate));
greyColor = texture2D(greyFrame, vec2(xCoordinate, yCoordinate));
layerColor = texture2D(layerImage, vec2(xCoordinate, yCoordinate));
// step1 curve
redCurveValue = texture2D(curve, vec2(textureColor.r, 0.0)).r;
greenCurveValue = texture2D(curve, vec2(textureColor.g, 0.0)).g;
blueCurveValue = texture2D(curve, vec2(textureColor.b, 0.0)).b;
// step2 curve with mask
textureColor = vec4(redCurveValue, greenCurveValue, blueCurveValue, 1.0);
redCurveValue = texture2D(curve, vec2(textureColor.r, 0.0)).a;
greenCurveValue = texture2D(curve, vec2(textureColor.g, 0.0)).a;
blueCurveValue = texture2D(curve, vec2(textureColor.b, 0.0)).a;
lowp vec4 textureColor2 = vec4(redCurveValue, greenCurveValue, blueCurveValue, 1.0);
// step3 screen with 60%
lowp vec4 base = vec4(mix(textureColor.rgb, textureColor2.rgb, 1.0 - greyColor.r), textureColor.a);
lowp vec4 overlayer = vec4(layerColor.r, layerColor.g, layerColor.b, 1.0);
// screen blending
textureColor = 1.0 - ((1.0 - base) * (1.0 - overlayer));
textureColor = (textureColor - base) * 0.6 + base;
redCurveValue = texture2D(curve, vec2(textureColor.r, 1.0)).r;
greenCurveValue = texture2D(curve, vec2(textureColor.g, 1.0)).g;
blueCurveValue = texture2D(curve, vec2(textureColor.b, 1.0)).b;
textureColor = vec4(redCurveValue, greenCurveValue, blueCurveValue, 1.0);
gl_FragColor = vec4(textureColor.r, textureColor.g, textureColor.b, 1.0);
}
```
|
```html
<html xmlns="path_to_url"
xmlns:ui="path_to_url"
xmlns:h="path_to_url"
xmlns:f="path_to_url"
xmlns:p="path_to_url">
<h:head>
<title>Panel, PanelGrid, PanelMenu</title>
<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form>
<p:panel id="Panel1" closable="true" toggleable="true">
<f:facet name="options">
<p:menu>
<p:menuitem value="Primefaces Tutorials"></p:menuitem>
<p:menuitem value="Hibernate Tutorials"></p:menuitem>
<p:menuitem value="JPA Tutorials"></p:menuitem>
</p:menu>
</f:facet>
<p:ajax event="toggle" listener="#{panelManagedBean.toggleHandle}"></p:ajax>
<p:ajax event="close" listener="#{panelManagedBean.closeHandle}"></p:ajax>
<f:facet name="header">
<p:outputLabel value="Tutorials Provided"></p:outputLabel>
</f:facet>
<p:outputLabel value="Name of tutorial you're looking for:"></p:outputLabel>
<p:inputText value="#{panelManagedBean.tutorial}"></p:inputText>
<p:commandButton value="Search" action="#{panelManagedBean.search}" update="result"></p:commandButton>
<p:dataTable value="#{panelManagedBean.tutorials}" var="tutorial" id="result">
<p:column>
<f:facet name="header">
<p:outputLabel value="Tutorial Name"></p:outputLabel>
</f:facet>
<p:outputLabel value="#{tutorial}"></p:outputLabel>
</p:column>
<f:facet name="footer">
<p:outputLabel value="Provided By Jouranldev.com"></p:outputLabel>
</f:facet>
</p:dataTable>
</p:panel>
</h:form>
</html>
```
|
Kookaburras are birds native to Australia and New Guinea, of the genus Dacelo.
Kookaburra may also refer to:
Kookaburra (aircraft), an airplane involved in the death of Keith Anderson and Bobby Hitchcock
Kookaburras (hockey), an Australian national men's hockey team
"Kookaburra" (song), a popular children's song
Kookaburra (rocket), an Australian sounding rocket
Australian Silver Kookaburra, a silver bullion coin
Kookaburra Sport, a sports equipment company
"Kookaburra", a song by Cocteau Twins from the 1985 album Aikea-Guinea
(A331), Royal Australian Navy
Dulmont Magnum, an Australian early laptop computer known as the Kookaburra
Schneider ES-52 Kookaburra, an Australian-designed and -built glider from the 1950s
See also
Kookooburra, a former Sydney Harbour ferry
|
```powershell
<#
.SYNOPSIS
This is a Powershell script to bootstrap a Cake build.
.DESCRIPTION
This Powershell script will download NuGet if missing, restore NuGet tools (including Cake)
and execute your Cake build script with the parameters you provide.
.PARAMETER Script
The build script to execute.
.PARAMETER Target
The build script target to run.
.PARAMETER Configuration
The build configuration to use.
.PARAMETER Verbosity
Specifies the amount of information to be displayed.
.PARAMETER Experimental
Tells Cake to use the latest Roslyn release.
.PARAMETER WhatIf
Performs a dry run of the build script.
No tasks will be executed.
.PARAMETER Mono
Tells Cake to use the Mono scripting engine.
.PARAMETER SkipToolPackageRestore
Skips restoring of packages.
.PARAMETER ScriptArgs
Remaining arguments are added here.
.LINK
path_to_url
#>
[CmdletBinding()]
Param(
[string]$Script = "build.cake",
[string]$Target = "Default",
[ValidateSet("Release", "Debug")]
[string]$Configuration = "Debug",
[ValidateSet("Quiet", "Minimal", "Normal", "Verbose", "Diagnostic")]
[string]$Verbosity = "Normal",
[switch]$Experimental = $true,
[Alias("DryRun","Noop")]
[switch]$WhatIf,
[switch]$Mono,
[switch]$SkipToolPackageRestore,
[Parameter(Position=0,Mandatory=$false,ValueFromRemainingArguments=$true)]
[string[]]$ScriptArgs
)
[Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null
function MD5HashFile([string] $filePath)
{
if ([string]::IsNullOrEmpty($filePath) -or !(Test-Path $filePath -PathType Leaf))
{
return $null
}
[System.IO.Stream] $file = $null;
[System.Security.Cryptography.MD5] $md5 = $null;
try
{
$md5 = [System.Security.Cryptography.MD5]::Create()
$file = [System.IO.File]::OpenRead($filePath)
return [System.BitConverter]::ToString($md5.ComputeHash($file))
}
finally
{
if ($file -ne $null)
{
$file.Dispose()
}
}
}
Write-Host "Preparing to run build script..."
if(!$PSScriptRoot){
$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
}
$TOOLS_DIR = Join-Path $PSScriptRoot "tools"
$NUGET_EXE = Join-Path $TOOLS_DIR "nuget.exe"
$CAKE_EXE = Join-Path $TOOLS_DIR "Cake/Cake.exe"
$NUGET_URL = "path_to_url"
$PACKAGES_CONFIG = Join-Path $TOOLS_DIR "packages.config"
$PACKAGES_CONFIG_MD5 = Join-Path $TOOLS_DIR "packages.config.md5sum"
# Should we use mono?
$UseMono = "";
if($Mono.IsPresent) {
Write-Verbose -Message "Using the Mono based scripting engine."
$UseMono = "-mono"
}
# Should we use the new Roslyn?
$UseExperimental = "";
if($Experimental.IsPresent -and !($Mono.IsPresent)) {
Write-Verbose -Message "Using experimental version of Roslyn."
$UseExperimental = "-experimental"
}
# Is this a dry run?
$UseDryRun = "";
if($WhatIf.IsPresent) {
$UseDryRun = "-dryrun"
}
# Make sure tools folder exists
if ((Test-Path $PSScriptRoot) -and !(Test-Path $TOOLS_DIR)) {
Write-Verbose -Message "Creating tools directory..."
New-Item -Path $TOOLS_DIR -Type directory | out-null
}
# Make sure that packages.config exist.
if (!(Test-Path $PACKAGES_CONFIG)) {
Write-Verbose -Message "Downloading packages.config..."
try { (New-Object System.Net.WebClient).DownloadFile("path_to_url", $PACKAGES_CONFIG) } catch {
Throw "Could not download packages.config."
}
}
# Try find NuGet.exe in path if not exists
if (!(Test-Path $NUGET_EXE)) {
Write-Verbose -Message "Trying to find nuget.exe in PATH..."
$existingPaths = $Env:Path -Split ';' | Where-Object { (![string]::IsNullOrEmpty($_)) -and (Test-Path $_) }
$NUGET_EXE_IN_PATH = Get-ChildItem -Path $existingPaths -Filter "nuget.exe" | Select -First 1
if ($NUGET_EXE_IN_PATH -ne $null -and (Test-Path $NUGET_EXE_IN_PATH.FullName)) {
Write-Verbose -Message "Found in PATH at $($NUGET_EXE_IN_PATH.FullName)."
$NUGET_EXE = $NUGET_EXE_IN_PATH.FullName
}
}
# Try download NuGet.exe if not exists
if (!(Test-Path $NUGET_EXE)) {
Write-Verbose -Message "Downloading NuGet.exe..."
try {
(New-Object System.Net.WebClient).DownloadFile($NUGET_URL, $NUGET_EXE)
} catch {
Throw "Could not download NuGet.exe."
}
}
# Save nuget.exe path to environment to be available to child processed
$ENV:NUGET_EXE = $NUGET_EXE
# Restore tools from NuGet?
if(-Not $SkipToolPackageRestore.IsPresent) {
Push-Location
Set-Location $TOOLS_DIR
# Check for changes in packages.config and remove installed tools if true.
[string] $md5Hash = MD5HashFile($PACKAGES_CONFIG)
if((!(Test-Path $PACKAGES_CONFIG_MD5)) -Or
($md5Hash -ne (Get-Content $PACKAGES_CONFIG_MD5 ))) {
Write-Verbose -Message "Missing or changed package.config hash..."
Remove-Item * -Recurse -Exclude packages.config,nuget.exe
}
Write-Verbose -Message "Restoring tools from NuGet..."
$NuGetOutput = Invoke-Expression "&`"$NUGET_EXE`" install -ExcludeVersion -OutputDirectory `"$TOOLS_DIR`""
if ($LASTEXITCODE -ne 0) {
Throw "An error occured while restoring NuGet tools."
}
else
{
$md5Hash | Out-File $PACKAGES_CONFIG_MD5 -Encoding "ASCII"
}
Write-Verbose -Message ($NuGetOutput | out-string)
Pop-Location
}
# Make sure that Cake has been installed.
if (!(Test-Path $CAKE_EXE)) {
Throw "Could not find Cake.exe at $CAKE_EXE"
}
# Start Cake
Write-Host "Running build script..."
Invoke-Expression "& `"$CAKE_EXE`" `"$Script`" -target=`"$Target`" -configuration=`"$Configuration`" -verbosity=`"$Verbosity`" $UseMono $UseDryRun $UseExperimental $ScriptArgs"
exit $LASTEXITCODE
```
|
```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="path_to_url"
xmlns:tools="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".testcase.testMatrix.TestMatrixActivity">
<com.chillingvan.canvasglsample.testcase.testMatrix.TestMatrixTextureView
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
```
|
Joan Bauer (born January 21, 1950) is an American politician who served as a member of the Michigan House of Representatives for the 68th district form 2007 to 2012.
Education
Bauer graduated from Western Michigan University with a Bachelor of Arts degree in history and minors in political science and secondary education.
Career
Bauer was a high school and adult education government teacher and she served as the director of volunteer services at Ingham Regional Medical Center for 21 years. Bauer chaired the Ingham County Women's Commission and served as president of the Michigan Women in Municipal Government from 2004 to 2005.
Lansing City Council
In 1995, Bauer was elected as a member at-large to the Lansing City Council, and re-elected in 1999, and 2003. She served until 2006, when she resigned to run for the Michigan State House of Representatives.
Michigan House of Representatives
Tenure
In her 2006 election to the Michigan House, Bauer defeated first runner-up Jerry Hollister, the son of former Lansing Mayor David Hollister, by nearly six percentage points in the Democratic primary, garnering 32.83% of the vote. Bauer coasted to victory in the general election by receiving 74% of the vote, defeating Republican businessman Harilaos I. Sorovigas.
As a member of the Michigan House of Representatives, Bauer introduced and co-sponsored a number of important bills. Perhaps one of the best known of these is HB 4341, which boasts 33 co-sponsors and would disallow all businesses and restaurants in Michigan from permitting smoking in their establishments. This bill, which provides no exemptions for certain businesses, has been referred to the House Regulatory Reform Committee; due to her efforts and coalition-building, Bauer's colleague, Representative Lee Gonzales, was able to successfully introduce a similar bill on February 19, 2009, which was identical except that it allowed exemptions for Detroit casinos, existing cigar bars, tobacco specialty retail stores, work vehicles and home offices. Bauer was a co-sponsor for this bill, and after months of complex negotiations, was able to see it passed with a bipartisan 73–31 majority. Free from the harmful effects of secondhand smoke, Michigan is now the 38th smoke-free state in the nation.
Bauer sponsored HB 4851 in 2009, would prohibit employers from paying a person less than an amount understood to be of "comparable worth," making doing so a civil rights law violation.
Committee and caucus membership
Bauer was a member of the House Appropriations Committee. She also served on three subcommittees in the House. She was the chair of the Higher Education Subcommittee, vice-chair of the Community Colleges Subcommittee, and a member of the Economic Development Subcommittee. She was appointed by House Speaker Andy Dillon to serve on the Capitol Committee.
Bauer served as chair of the Capital Caucus, co-chair of the Michigan Legislative Women's Caucus, and co-chair of the Local Government Caucus. As a testament to her skills as a legislator and a leader, all of these caucuses are bipartisan as well as bicameral. She is also a member of several other caucuses, including the Urban Caucus, the Children's Caucus, the Tourism Caucus, the Arts Caucus, and the Fire Caucus.
Personal life
Joan Bauer is married to Doug Langham, the former administrator of vocational rehabilitation in the Michigan Workers Compensation Agency, and they live on Lansing's Westside.
References
External links
Official House Democrats webpage
Official campaign website
Joan Bauer's voting record
Living people
Western Michigan University alumni
Democratic Party members of the Michigan House of Representatives
Women state legislators in Michigan
Michigan city council members
Women city councillors in Michigan
Politicians from Lansing, Michigan
20th-century American politicians
20th-century American women politicians
21st-century American politicians
21st-century American women politicians
1950 births
|
```java
/*
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.apache.beam.sdk.io.jdbc;
import static org.apache.beam.sdk.io.jdbc.JdbcUtil.JDBC_DRIVER_MAP;
import static org.apache.beam.sdk.io.jdbc.JdbcUtil.registerJdbcDriver;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThrows;
import java.sql.SQLException;
import java.util.List;
import java.util.Objects;
import java.util.ServiceLoader;
import javax.sql.DataSource;
import org.apache.beam.sdk.io.common.DatabaseTestHelper;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.transforms.SchemaTransformProvider;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.values.PCollectionRowTuple;
import org.apache.beam.sdk.values.Row;
import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class JdbcWriteSchemaTransformProviderTest {
private static final JdbcIO.DataSourceConfiguration DATA_SOURCE_CONFIGURATION =
JdbcIO.DataSourceConfiguration.create(
"org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:memory:testDB;create=true");
private static final DataSource DATA_SOURCE = DATA_SOURCE_CONFIGURATION.buildDatasource();
private String writeTableName;
@Rule public final transient TestPipeline pipeline = TestPipeline.create();
@BeforeClass
public static void beforeClass() throws Exception {
// by default, derby uses a lock timeout of 60 seconds. In order to speed up the test
// and detect the lock faster, we decrease this timeout
System.setProperty("derby.locks.waitTimeout", "2");
System.setProperty("derby.stream.error.file", "build/derby.log");
registerJdbcDriver(
ImmutableMap.of(
"derby", Objects.requireNonNull(DATA_SOURCE_CONFIGURATION.getDriverClassName()).get()));
}
@Before
public void before() throws SQLException {
writeTableName = DatabaseTestHelper.getTestTableName("UT_WRITE");
DatabaseTestHelper.createTable(DATA_SOURCE, writeTableName);
}
@Test
public void testInvalidWriteSchemaOptions() {
assertThrows(
IllegalArgumentException.class,
() -> {
JdbcWriteSchemaTransformProvider.JdbcWriteSchemaTransformConfiguration.builder()
.setDriverClassName("")
.setJdbcUrl("")
.build()
.validate();
});
assertThrows(
IllegalArgumentException.class,
() -> {
JdbcWriteSchemaTransformProvider.JdbcWriteSchemaTransformConfiguration.builder()
.setDriverClassName("ClassName")
.setJdbcUrl("JdbcUrl")
.setLocation("Location")
.setWriteStatement("WriteStatement")
.build()
.validate();
});
assertThrows(
IllegalArgumentException.class,
() -> {
JdbcWriteSchemaTransformProvider.JdbcWriteSchemaTransformConfiguration.builder()
.setDriverClassName("ClassName")
.setJdbcUrl("JdbcUrl")
.build()
.validate();
});
assertThrows(
IllegalArgumentException.class,
() -> {
JdbcWriteSchemaTransformProvider.JdbcWriteSchemaTransformConfiguration.builder()
.setJdbcUrl("JdbcUrl")
.setLocation("Location")
.setJdbcType("invalidType")
.build()
.validate();
});
assertThrows(
IllegalArgumentException.class,
() -> {
JdbcWriteSchemaTransformProvider.JdbcWriteSchemaTransformConfiguration.builder()
.setJdbcUrl("JdbcUrl")
.setLocation("Location")
.build()
.validate();
});
assertThrows(
IllegalArgumentException.class,
() -> {
JdbcWriteSchemaTransformProvider.JdbcWriteSchemaTransformConfiguration.builder()
.setJdbcUrl("JdbcUrl")
.setLocation("Location")
.setDriverClassName("ClassName")
.setJdbcType((String) JDBC_DRIVER_MAP.keySet().toArray()[0])
.build()
.validate();
});
}
@Test
public void testValidWriteSchemaOptions() {
for (String jdbcType : JDBC_DRIVER_MAP.keySet()) {
JdbcWriteSchemaTransformProvider.JdbcWriteSchemaTransformConfiguration.builder()
.setJdbcUrl("JdbcUrl")
.setLocation("Location")
.setJdbcType(jdbcType)
.build()
.validate();
}
}
@Test
public void testWriteToTable() throws SQLException {
JdbcWriteSchemaTransformProvider provider = null;
for (SchemaTransformProvider p : ServiceLoader.load(SchemaTransformProvider.class)) {
if (p instanceof JdbcWriteSchemaTransformProvider) {
provider = (JdbcWriteSchemaTransformProvider) p;
break;
}
}
assertNotNull(provider);
Schema schema =
Schema.of(
Schema.Field.of("id", Schema.FieldType.INT64),
Schema.Field.of("name", Schema.FieldType.STRING));
List<Row> rows =
ImmutableList.of(
Row.withSchema(schema).attachValues(1L, "name1"),
Row.withSchema(schema).attachValues(2L, "name2"));
PCollectionRowTuple.of("input", pipeline.apply(Create.of(rows).withRowSchema(schema)))
.apply(
provider.from(
JdbcWriteSchemaTransformProvider.JdbcWriteSchemaTransformConfiguration.builder()
.setDriverClassName(DATA_SOURCE_CONFIGURATION.getDriverClassName().get())
.setJdbcUrl(DATA_SOURCE_CONFIGURATION.getUrl().get())
.setLocation(writeTableName)
.build()));
pipeline.run();
DatabaseTestHelper.assertRowCount(DATA_SOURCE, writeTableName, 2);
}
@Test
public void testWriteToTableWithJdbcTypeSpecified() throws SQLException {
JdbcWriteSchemaTransformProvider provider = null;
for (SchemaTransformProvider p : ServiceLoader.load(SchemaTransformProvider.class)) {
if (p instanceof JdbcWriteSchemaTransformProvider) {
provider = (JdbcWriteSchemaTransformProvider) p;
break;
}
}
assertNotNull(provider);
Schema schema =
Schema.of(
Schema.Field.of("id", Schema.FieldType.INT64),
Schema.Field.of("name", Schema.FieldType.STRING));
List<Row> rows =
ImmutableList.of(
Row.withSchema(schema).attachValues(1L, "name1"),
Row.withSchema(schema).attachValues(2L, "name2"));
PCollectionRowTuple.of("input", pipeline.apply(Create.of(rows).withRowSchema(schema)))
.apply(
provider.from(
JdbcWriteSchemaTransformProvider.JdbcWriteSchemaTransformConfiguration.builder()
.setJdbcUrl(DATA_SOURCE_CONFIGURATION.getUrl().get())
.setJdbcType("derby")
.setLocation(writeTableName)
.build()));
pipeline.run();
DatabaseTestHelper.assertRowCount(DATA_SOURCE, writeTableName, 2);
}
}
```
|
```c
/*
* SSL server demonstration program using fork() for handling multiple clients
*
*/
#include "mbedtls/build_info.h"
#include "mbedtls/platform.h"
#if !defined(MBEDTLS_BIGNUM_C) || !defined(MBEDTLS_ENTROPY_C) || \
!defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_SRV_C) || \
!defined(MBEDTLS_NET_C) || !defined(MBEDTLS_RSA_C) || \
!defined(MBEDTLS_CTR_DRBG_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) || \
!defined(MBEDTLS_TIMING_C) || !defined(MBEDTLS_FS_IO) || \
!defined(MBEDTLS_PEM_PARSE_C)
int main(int argc, char *argv[])
{
((void) argc);
((void) argv);
mbedtls_printf("MBEDTLS_BIGNUM_C and/or MBEDTLS_ENTROPY_C "
"and/or MBEDTLS_SSL_TLS_C and/or MBEDTLS_SSL_SRV_C and/or "
"MBEDTLS_NET_C and/or MBEDTLS_RSA_C and/or "
"MBEDTLS_CTR_DRBG_C and/or MBEDTLS_X509_CRT_PARSE_C and/or "
"MBEDTLS_TIMING_C and/or MBEDTLS_PEM_PARSE_C not defined.\n");
mbedtls_exit(0);
}
#elif defined(_WIN32)
int main(void)
{
mbedtls_printf("_WIN32 defined. This application requires fork() and signals "
"to work correctly.\n");
mbedtls_exit(0);
}
#else
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "test/certs.h"
#include "mbedtls/x509.h"
#include "mbedtls/ssl.h"
#include "mbedtls/net_sockets.h"
#include "mbedtls/timing.h"
#include <string.h>
#include <signal.h>
#if !defined(_MSC_VER) || defined(EFIX64) || defined(EFI32)
#include <unistd.h>
#endif
#define HTTP_RESPONSE \
"HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n" \
"<h2>Mbed TLS Test Server</h2>\r\n" \
"<p>Successful connection using: %s</p>\r\n"
#define DEBUG_LEVEL 0
static void my_debug(void *ctx, int level,
const char *file, int line,
const char *str)
{
((void) level);
mbedtls_fprintf((FILE *) ctx, "%s:%04d: %s", file, line, str);
fflush((FILE *) ctx);
}
int main(void)
{
int ret = 1, len, cnt = 0, pid;
int exit_code = MBEDTLS_EXIT_FAILURE;
mbedtls_net_context listen_fd, client_fd;
unsigned char buf[1024];
const char *pers = "ssl_fork_server";
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_ssl_context ssl;
mbedtls_ssl_config conf;
mbedtls_x509_crt srvcert;
mbedtls_pk_context pkey;
mbedtls_net_init(&listen_fd);
mbedtls_net_init(&client_fd);
mbedtls_ssl_init(&ssl);
mbedtls_ssl_config_init(&conf);
mbedtls_entropy_init(&entropy);
mbedtls_pk_init(&pkey);
mbedtls_x509_crt_init(&srvcert);
mbedtls_ctr_drbg_init(&ctr_drbg);
#if defined(MBEDTLS_USE_PSA_CRYPTO)
psa_status_t status = psa_crypto_init();
if (status != PSA_SUCCESS) {
mbedtls_fprintf(stderr, "Failed to initialize PSA Crypto implementation: %d\n",
(int) status);
goto exit;
}
#endif /* MBEDTLS_USE_PSA_CRYPTO */
signal(SIGCHLD, SIG_IGN);
/*
* 0. Initial seeding of the RNG
*/
mbedtls_printf("\n . Initial seeding of the random generator...");
fflush(stdout);
if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
(const unsigned char *) pers,
strlen(pers))) != 0) {
mbedtls_printf(" failed! mbedtls_ctr_drbg_seed returned %d\n\n", ret);
goto exit;
}
mbedtls_printf(" ok\n");
/*
* 1. Load the certificates and private RSA key
*/
mbedtls_printf(" . Loading the server cert. and key...");
fflush(stdout);
/*
* This demonstration program uses embedded test certificates.
* Instead, you may want to use mbedtls_x509_crt_parse_file() to read the
* server and CA certificates, as well as mbedtls_pk_parse_keyfile().
*/
ret = mbedtls_x509_crt_parse(&srvcert, (const unsigned char *) mbedtls_test_srv_crt,
mbedtls_test_srv_crt_len);
if (ret != 0) {
mbedtls_printf(" failed! mbedtls_x509_crt_parse returned %d\n\n", ret);
goto exit;
}
ret = mbedtls_x509_crt_parse(&srvcert, (const unsigned char *) mbedtls_test_cas_pem,
mbedtls_test_cas_pem_len);
if (ret != 0) {
mbedtls_printf(" failed! mbedtls_x509_crt_parse returned %d\n\n", ret);
goto exit;
}
ret = mbedtls_pk_parse_key(&pkey, (const unsigned char *) mbedtls_test_srv_key,
mbedtls_test_srv_key_len, NULL, 0,
mbedtls_ctr_drbg_random, &ctr_drbg);
if (ret != 0) {
mbedtls_printf(" failed! mbedtls_pk_parse_key returned %d\n\n", ret);
goto exit;
}
mbedtls_printf(" ok\n");
/*
* 1b. Prepare SSL configuration
*/
mbedtls_printf(" . Configuring SSL...");
fflush(stdout);
if ((ret = mbedtls_ssl_config_defaults(&conf,
MBEDTLS_SSL_IS_SERVER,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
mbedtls_printf(" failed! mbedtls_ssl_config_defaults returned %d\n\n", ret);
goto exit;
}
mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg);
mbedtls_ssl_conf_dbg(&conf, my_debug, stdout);
mbedtls_ssl_conf_ca_chain(&conf, srvcert.next, NULL);
if ((ret = mbedtls_ssl_conf_own_cert(&conf, &srvcert, &pkey)) != 0) {
mbedtls_printf(" failed! mbedtls_ssl_conf_own_cert returned %d\n\n", ret);
goto exit;
}
mbedtls_printf(" ok\n");
/*
* 2. Setup the listening TCP socket
*/
mbedtls_printf(" . Bind on path_to_url ...");
fflush(stdout);
if ((ret = mbedtls_net_bind(&listen_fd, NULL, "4433", MBEDTLS_NET_PROTO_TCP)) != 0) {
mbedtls_printf(" failed! mbedtls_net_bind returned %d\n\n", ret);
goto exit;
}
mbedtls_printf(" ok\n");
while (1) {
/*
* 3. Wait until a client connects
*/
mbedtls_net_init(&client_fd);
mbedtls_ssl_init(&ssl);
mbedtls_printf(" . Waiting for a remote connection ...\n");
fflush(stdout);
if ((ret = mbedtls_net_accept(&listen_fd, &client_fd,
NULL, 0, NULL)) != 0) {
mbedtls_printf(" failed! mbedtls_net_accept returned %d\n\n", ret);
goto exit;
}
/*
* 3.5. Forking server thread
*/
mbedtls_printf(" . Forking to handle connection ...");
fflush(stdout);
pid = fork();
if (pid < 0) {
mbedtls_printf(" failed! fork returned %d\n\n", pid);
goto exit;
}
if (pid != 0) {
mbedtls_printf(" ok\n");
mbedtls_net_close(&client_fd);
if ((ret = mbedtls_ctr_drbg_reseed(&ctr_drbg,
(const unsigned char *) "parent",
6)) != 0) {
mbedtls_printf(" failed! mbedtls_ctr_drbg_reseed returned %d\n\n", ret);
goto exit;
}
continue;
}
mbedtls_net_close(&listen_fd);
pid = getpid();
/*
* 4. Setup stuff
*/
mbedtls_printf("pid %d: Setting up the SSL data.\n", pid);
fflush(stdout);
if ((ret = mbedtls_ctr_drbg_reseed(&ctr_drbg,
(const unsigned char *) "child",
5)) != 0) {
mbedtls_printf(
"pid %d: SSL setup failed! mbedtls_ctr_drbg_reseed returned %d\n\n",
pid, ret);
goto exit;
}
if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0) {
mbedtls_printf(
"pid %d: SSL setup failed! mbedtls_ssl_setup returned %d\n\n",
pid, ret);
goto exit;
}
mbedtls_ssl_set_bio(&ssl, &client_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
mbedtls_printf("pid %d: SSL setup ok\n", pid);
/*
* 5. Handshake
*/
mbedtls_printf("pid %d: Performing the SSL/TLS handshake.\n", pid);
fflush(stdout);
while ((ret = mbedtls_ssl_handshake(&ssl)) != 0) {
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
mbedtls_printf(
"pid %d: SSL handshake failed! mbedtls_ssl_handshake returned %d\n\n",
pid, ret);
goto exit;
}
}
mbedtls_printf("pid %d: SSL handshake ok\n", pid);
/*
* 6. Read the HTTP Request
*/
mbedtls_printf("pid %d: Start reading from client.\n", pid);
fflush(stdout);
do {
len = sizeof(buf) - 1;
memset(buf, 0, sizeof(buf));
ret = mbedtls_ssl_read(&ssl, buf, len);
if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
continue;
}
if (ret <= 0) {
switch (ret) {
case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
mbedtls_printf("pid %d: connection was closed gracefully\n", pid);
break;
case MBEDTLS_ERR_NET_CONN_RESET:
mbedtls_printf("pid %d: connection was reset by peer\n", pid);
break;
default:
mbedtls_printf("pid %d: mbedtls_ssl_read returned %d\n", pid, ret);
break;
}
break;
}
len = ret;
mbedtls_printf("pid %d: %d bytes read\n\n%s", pid, len, (char *) buf);
if (ret > 0) {
break;
}
} while (1);
/*
* 7. Write the 200 Response
*/
mbedtls_printf("pid %d: Start writing to client.\n", pid);
fflush(stdout);
len = sprintf((char *) buf, HTTP_RESPONSE,
mbedtls_ssl_get_ciphersuite(&ssl));
while (cnt++ < 100) {
while ((ret = mbedtls_ssl_write(&ssl, buf, len)) <= 0) {
if (ret == MBEDTLS_ERR_NET_CONN_RESET) {
mbedtls_printf(
"pid %d: Write failed! peer closed the connection\n\n", pid);
goto exit;
}
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
mbedtls_printf(
"pid %d: Write failed! mbedtls_ssl_write returned %d\n\n",
pid, ret);
goto exit;
}
}
len = ret;
mbedtls_printf("pid %d: %d bytes written\n\n%s\n", pid, len, (char *) buf);
mbedtls_net_usleep(1000000);
}
mbedtls_ssl_close_notify(&ssl);
goto exit;
}
exit_code = MBEDTLS_EXIT_SUCCESS;
exit:
mbedtls_net_free(&client_fd);
mbedtls_net_free(&listen_fd);
mbedtls_x509_crt_free(&srvcert);
mbedtls_pk_free(&pkey);
mbedtls_ssl_free(&ssl);
mbedtls_ssl_config_free(&conf);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
#if defined(MBEDTLS_USE_PSA_CRYPTO)
mbedtls_psa_crypto_free();
#endif /* MBEDTLS_USE_PSA_CRYPTO */
mbedtls_exit(exit_code);
}
#endif /* MBEDTLS_BIGNUM_C && MBEDTLS_ENTROPY_C &&
MBEDTLS_SSL_TLS_C && MBEDTLS_SSL_SRV_C && MBEDTLS_NET_C &&
MBEDTLS_RSA_C && MBEDTLS_CTR_DRBG_C && MBEDTLS_PEM_PARSE_C &&
! _WIN32 */
```
|
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>Author</key>
<string>m-dudarev</string>
<key>CodecID</key>
<integer>624</integer>
<key>CodecName</key>
<string>ALC270</string>
<key>Files</key>
<dict>
<key>Layouts</key>
<array>
<dict>
<key>Comment</key>
<string>Mirone Laptop Patch ALC270 v2</string>
<key>Id</key>
<integer>4</integer>
<key>Path</key>
<string>layout4.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Mirone Laptop Patch ALC270 v1</string>
<key>Id</key>
<integer>3</integer>
<key>Path</key>
<string>layout3.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Andres ALC270 Asus A46CB-WX024D by Andres ZeroCross</string>
<key>Id</key>
<integer>21</integer>
<key>Path</key>
<string>layout21.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Custom by m-dudarev</string>
<key>Id</key>
<integer>27</integer>
<key>Path</key>
<string>layout27.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Custom by m-dudarev</string>
<key>Id</key>
<integer>28</integer>
<key>Path</key>
<string>layout28.xml.zlib</string>
</dict>
</array>
<key>Platforms</key>
<array>
<dict>
<key>Comment</key>
<string>Mirone Laptop Patch ALC270 v2</string>
<key>Id</key>
<integer>4</integer>
<key>Path</key>
<string>PlatformsM4.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Mirone Laptop Patch ALC270 v1</string>
<key>Id</key>
<integer>3</integer>
<key>Path</key>
<string>PlatformsM3.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Andres ALC270 Asus A46CB-WX024D by Andres ZeroCross</string>
<key>Id</key>
<integer>21</integer>
<key>Path</key>
<string>Platforms21.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Custom by m-dudarev</string>
<key>Id</key>
<integer>27</integer>
<key>Path</key>
<string>Platforms27.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Custom by m-dudarev</string>
<key>Id</key>
<integer>28</integer>
<key>Path</key>
<string>Platforms28.xml.zlib</string>
</dict>
</array>
</dict>
<key>Patches</key>
<array>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>xgYASIu/aAE=</data>
<key>MinKernel</key>
<integer>18</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>xgYBSIu/aAE=</data>
</dict>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>QcYGAEmLvCQ=</data>
<key>MaxKernel</key>
<integer>13</integer>
<key>MinKernel</key>
<integer>13</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>QcYGAUmLvCQ=</data>
</dict>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>QcYGAEiLu2g=</data>
<key>MinKernel</key>
<integer>14</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>QcYGAUiLu2g=</data>
</dict>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>QcaGQwEAAAA=</data>
<key>MinKernel</key>
<integer>13</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>QcaGQwEAAAE=</data>
</dict>
<dict>
<key>Count</key>
<integer>2</integer>
<key>Find</key>
<data>hQjsEA==</data>
<key>MinKernel</key>
<integer>13</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>AAAAAA==</data>
</dict>
<dict>
<key>Count</key>
<integer>2</integer>
<key>Find</key>
<data>hAjsEA==</data>
<key>MinKernel</key>
<integer>13</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>AAAAAA==</data>
</dict>
<dict>
<key>Count</key>
<integer>2</integer>
<key>Find</key>
<data>ixnUEQ==</data>
<key>MinKernel</key>
<integer>13</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>cALsEA==</data>
</dict>
<dict>
<key>Count</key>
<integer>2</integer>
<key>Find</key>
<data>gxnUEQ==</data>
<key>MaxKernel</key>
<integer>15</integer>
<key>MinKernel</key>
<integer>15</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>AAAAAA==</data>
</dict>
<dict>
<key>Count</key>
<integer>2</integer>
<key>Find</key>
<data>ihnUEQ==</data>
<key>MinKernel</key>
<integer>16</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>AAAAAA==</data>
</dict>
</array>
<key>Revisions</key>
<array>
<integer>1048832</integer>
</array>
<key>Vendor</key>
<string>Realtek</string>
</dict>
</plist>
```
|
Khed Caves, also Bouddh Caves, are a series of ancient Buddhist caves in the city of Khed, Maharashtra, India.
The group of caves comprises a large vihara, with three cells for monks, and with a stupa in the back located in an oblong room. There are also four smaller caves in the group. The caves are in a rather derelict state.
References
External links
Google images
Buddhist caves in India
Caves of Maharashtra
Indian rock-cut architecture
Former populated places in India
Buddhist pilgrimage sites in India
Buddhist monasteries in India
Caves containing pictograms in India
Tourist attractions in Ratnagiri district
|
```kotlin
package net.corda.node.services.persistence
import net.corda.core.crypto.Crypto
import net.corda.core.utilities.hexToByteArray
import net.corda.core.utilities.toHex
import java.security.PublicKey
import javax.persistence.AttributeConverter
import javax.persistence.Converter
/**
* Converts to and from a Public key into a hex encoded string.
* Used by JPA to automatically map a [PublicKey] to a text column
*/
@Converter(autoApply = true)
class PublicKeyToTextConverter : AttributeConverter<PublicKey, String> {
override fun convertToDatabaseColumn(key: PublicKey?): String? = key?.let { Crypto.encodePublicKey(key).toHex() }
override fun convertToEntityAttribute(text: String?): PublicKey? = text?.let { Crypto.decodePublicKey(it.hexToByteArray()) }
}
```
|
Cyperus aureoalatus is a species of sedge that has been found to occur in Somalia, Uganda and Ethiopia.
The species was first formally described by the botanist Kåre Arnstein Lye in 1995.
See also
List of Cyperus species
References
aureoalatus
Plants described in 1995
Flora of Somalia
Flora of Uganda
Flora of Ethiopia
Taxa named by Kåre Arnstein Lye
|
SeaBIOS is an open-source implementation of an x86 BIOS, serving as a freely available firmware for x86 systems. Aiming for compatibility, it supports standard BIOS features and calling interfaces that are implemented by a typical proprietary x86 BIOS. SeaBIOS can either run on bare hardware as a coreboot payload, or can be used directly in emulators such as QEMU and Bochs.
Initially, SeaBIOS was based on the open-source BIOS implementation included with the Bochs emulator. The project was created with intentions to allow native usage on x86 hardware, and to be based on an improved and more easily extendable internal source code implementation.
Features
Features supported by SeaBIOS include the following:
Graphical bootsplash screen (JPEG and BMP)
USB keyboard and mouse support
USB Mass Storage boot support
USB Attached SCSI boot support
ATA support
AHCI support
NVMe support
El Torito optical disc drive boot support
BIOS Boot Specification (BBS)
Rebooting on Control-Alt-Delete key press
Network booting support e.g. iPXE or gPXE
Logical block addressing (LBA)
POST Memory Manager (PMM)
Paravirtualization, Xen HVM, VirtIO
Coreboot Payloads (LZMA compressed)
PCI Firmware Specification
SeaBIOS as a Compatibility Support Module (CSM) for Unified Extensible Firmware Interface (UEFI) and Open Virtual Machine Firmware (OVMF)
Virtual machine host notification of paravirtualized guests which panic via the pvpanic driver
A patch exists to load the SLIC table from a licensed OEM Windows BIOS.
Trusted Platform Module
Enhanced Disk Drive (EDD) (INT 13H extensions)
e820 memory map
Protected mode interfaces, e.g. APM, Legacy PnP, DMI, MPS, SMBIOS, VBE, and ACPI
System Management Mode
It does not support ESCD. SeaBIOS does not support Intel ME or AMD PSP or its modules.
SeaBIOS's boot device selection menu can be accessed by pressing during the boot process.
Uses
SeaBIOS can run natively on x86 hardware, in which case it is loaded by either coreboot or Libreboot as a payload; it runs on 386 and later processors, and requires a minimum of 1 MB of RAM. Compiled SeaBIOS images can be flashed into supported motherboards using flashrom. SeaBIOS also runs inside an emulator; it is the default BIOS for the QEMU and KVM virtualization environments, and can be used with the Bochs emulator. It is also included in some Chromebooks, although it is not used by ChromeOS.
Development
Most of the SeaBIOS source code is written in C, with its build system relying on the standard GNU toolchain. SeaBIOS has been tested with various bootloaders and operating systems, including GNU GRUB, LILO, SYSLINUX, Microsoft Windows, Linux, FreeDOS, FreeBSD, NetBSD and OpenBSD.
See also
BIOS features comparison
TianoCore
References
External links
Find your way through the x86 firmware maze covers the SeaBIOS boot sequence and memory maps
2008 software
Free BIOS implementations
Free software programmed in C
Open-source firmware
|
```c++
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// path_to_url
#include <libs/vmd/test/test_sequence_enum.cxx>
```
|
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>BuildMachineOSBuild</key>
<string>16D32</string>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>AtherosE2200Ethernet</string>
<key>CFBundleIdentifier</key>
<string>com.insanelymac.AtherosE2200Ethernet</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>AtherosE2200Ethernet</string>
<key>CFBundlePackageType</key>
<string>KEXT</string>
<key>CFBundleShortVersionString</key>
<string>2.2.1</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>MacOSX</string>
</array>
<key>CFBundleVersion</key>
<string>2.2.1</string>
<key>DTCompiler</key>
<string>com.apple.compilers.llvm.clang.1_0</string>
<key>DTPlatformBuild</key>
<string>8C1002</string>
<key>DTPlatformVersion</key>
<string>GM</string>
<key>DTSDKBuild</key>
<string>16C58</string>
<key>DTSDKName</key>
<string>macosx10.12</string>
<key>DTXcode</key>
<string>0821</string>
<key>DTXcodeBuild</key>
<string>8C1002</string>
<key>IOKitPersonalities</key>
<dict>
<key>AtherosE2200</key>
<dict>
<key>CFBundleIdentifier</key>
<string>com.insanelymac.AtherosE2200Ethernet</string>
<key>Driver_Version</key>
<string>2.2.1</string>
<key>IOClass</key>
<string>AtherosE2200</string>
<key>IOPCIMatch</key>
<string>0x10901969 0x10911969 0x10A01969 0x10A11969 0xE0911969 0xE0A11969 0xE0B11969</string>
<key>IOProbeScore</key>
<integer>1000</integer>
<key>IOProviderClass</key>
<string>IOPCIDevice</string>
<key>enableCSO6</key>
<true/>
<key>enableTSO4</key>
<true/>
<key>enableTSO6</key>
<true/>
<key>maxIntrRate</key>
<integer>6500</integer>
<key>rxPolling</key>
<true/>
</dict>
</dict>
<key>OSBundleLibraries</key>
<dict>
<key>com.apple.iokit.IONetworkingFamily</key>
<string>1.5.0</string>
<key>com.apple.iokit.IOPCIFamily</key>
<string>1.7</string>
<key>com.apple.kpi.bsd</key>
<string>8.10.0</string>
<key>com.apple.kpi.iokit</key>
<string>8.10.0</string>
<key>com.apple.kpi.libkern</key>
<string>8.10.0</string>
<key>com.apple.kpi.mach</key>
<string>8.10.0</string>
</dict>
<key>OSBundleRequired</key>
<string>Network-Root</string>
</dict>
</plist>
```
|
The Thirteenth Saeima of Latvia was elected in the 2018 Latvian parliamentary election held on 6 October 2018. The Saeima's term commenced on 6 November 2018 and will end on 1 November 2022.
Elections
The 100 members of the Saeima are elected by open list proportional representation from five multi-member constituencies (Kurzeme, Latgale, Riga (in which overseas votes are counted), Vidzeme and Zemgale) between 12 and 35 seats in size. Seats are allocated using the Sainte-Laguë method with a national electoral threshold of 5%.
Composition
Parliamentary groups
After the elections, the parliamentary groups were formed in the Saeima on the party lines, with the exception of MP Julija Stepanenko, who was elected from the Harmony list but didn't join the party's parliamentary group.
Members
123 members have served in the Thirteenth Saeima.
References
2018 in Latvia
Saeima
Political history of Latvia
|
```swift
/*
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
/// A store that allows for reading contacts.
public protocol OCKAnyReadOnlyContactStore: OCKAnyResettableStore {
/// A continuous stream of contacts that exist in the store.
///
/// The stream yields a new value whenever the result changes and yields an error if there's an issue
/// accessing the store or fetching results.
///
/// Supply a query that'll be used to match contacts in the store. If the query doesn't contain a date
/// interval, the result will contain every version of a contact. Multiple versions of the same contact will
/// have the same ``OCKAnyContact/id`` but a different UUID. If the query does contain a date
/// interval, the result will contain the newest version of a contact that exists in the interval.
///
/// - Parameter query: Used to match contacts in the store.
func anyContacts(matching query: OCKContactQuery) -> CareStoreQueryResults<OCKAnyContact>
/// `fetchAnyContacts` asynchronously retrieves an array of contacts from the store.
///
/// - Parameters:
/// - query: A query used to constrain the values that will be fetched.
/// - callbackQueue: The queue that the completion closure should be called on. In most cases this should be the main queue.
/// - completion: A callback that will fire on the provided callback queue.
func fetchAnyContacts(query: OCKContactQuery, callbackQueue: DispatchQueue, completion: @escaping OCKResultClosure<[OCKAnyContact]>)
// MARK: Singular Methods - Implementation Provided
/// `fetchAnyContact` asynchronously retrieves a single contact from the store.
///
/// - Parameters:
/// - id: The identifier of the item to be fetched.
/// - callbackQueue: The queue that the completion closure should be called on. In most cases this should be the main queue.
/// - completion: A callback that will fire on the provided callback queue.
func fetchAnyContact(withID id: String, callbackQueue: DispatchQueue, completion: @escaping OCKResultClosure<OCKAnyContact>)
}
/// Any store able to write to one ore more types conforming to `OCKAnyContact` is considered an `OCKAnyContactStore`.
public protocol OCKAnyContactStore: OCKAnyReadOnlyContactStore {
/// `addAnyContacts` asynchronously adds an array of contacts to the store.
///
/// - Parameters:
/// - contacts: An array of contacts to be added to the store.
/// - callbackQueue: The queue that the completion closure should be called on. In most cases this should be the main queue.
/// - completion: A callback that will fire on the provided callback queue.
func addAnyContacts(_ contacts: [OCKAnyContact], callbackQueue: DispatchQueue, completion: OCKResultClosure<[OCKAnyContact]>?)
/// `updateAnyContacts` asynchronously updates an array of contacts in the store.
///
/// - Parameters:
/// - contacts: An array of contacts to be updated. The contacts must already exist in the store.
/// - callbackQueue: The queue that the completion closure should be called on. In most cases this should be the main queue.
/// - completion: A callback that will fire on the provided callback queue.
func updateAnyContacts(_ contacts: [OCKAnyContact], callbackQueue: DispatchQueue, completion: OCKResultClosure<[OCKAnyContact]>?)
/// `deleteAnyContacts` asynchronously deletes an array of contacts from the store.
///
/// - Parameters:
/// - contacts: An array of contacts to be deleted. The contacts must exist in the store.
/// - callbackQueue: The queue that the completion closure should be called on. In most cases this should be the main queue.
/// - completion: A callback that will fire on the provided callback queue.
func deleteAnyContacts(_ contacts: [OCKAnyContact], callbackQueue: DispatchQueue, completion: OCKResultClosure<[OCKAnyContact]>?)
// MARK: Singular Methods - Implementation Provided
/// `addAnyContact` asynchronously adds a single contact to the store.
///
/// - Parameters:
/// - contact: A single contact to be added to the store.
/// - callbackQueue: The queue that the completion closure should be called on. In most cases this should be the main queue.
/// - completion: A callback that will fire on the provided callback queue.
func addAnyContact(_ contact: OCKAnyContact, callbackQueue: DispatchQueue, completion: OCKResultClosure<OCKAnyContact>?)
/// `updateAnyContact` asynchronously update single contact in the store.
///
/// - Parameters:
/// - contact: A single contact to be updated. The contact must already exist in the store.
/// - callbackQueue: The queue that the completion closure should be called on. In most cases this should be the main queue.
/// - completion: A callback that will fire on the provided callback queue.
func updateAnyContact(_ contact: OCKAnyContact, callbackQueue: DispatchQueue, completion: OCKResultClosure<OCKAnyContact>?)
/// `deleteAnyContact` asynchronously deletes a single contact from the store.
///
/// - Parameters:
/// - contact: A single contact to be deleted. The contact must exist in the store.
/// - callbackQueue: The queue that the completion closure should be called on. In most cases this should be the main queue.
/// - completion: A callback that will fire on the provided callback queue.
func deleteAnyContact(_ contact: OCKAnyContact, callbackQueue: DispatchQueue, completion: OCKResultClosure<OCKAnyContact>?)
}
// MARK: Singular Methods for OCKAnyReadOnlyContactStore
public extension OCKAnyReadOnlyContactStore {
func fetchAnyContact(withID id: String, callbackQueue: DispatchQueue = .main,
completion: @escaping OCKResultClosure<OCKAnyContact>) {
var query = OCKContactQuery(for: Date())
query.limit = 1
query.sortDescriptors = [.effectiveDate(ascending: true)]
query.ids = [id]
fetchAnyContacts(query: query, callbackQueue: callbackQueue, completion:
chooseFirst(then: completion, replacementError: .fetchFailed(reason: "No contact with matching ID")))
}
}
// MARK: Singular Methods for OCKAnyContactStore
public extension OCKAnyContactStore {
func addAnyContact(_ contact: OCKAnyContact, callbackQueue: DispatchQueue = .main, completion: OCKResultClosure<OCKAnyContact>? = nil) {
addAnyContacts([contact], callbackQueue: callbackQueue, completion:
chooseFirst(then: completion, replacementError: .addFailed(reason: "Failed to add contact")))
}
func updateAnyContact(_ contact: OCKAnyContact, callbackQueue: DispatchQueue = .main, completion: OCKResultClosure<OCKAnyContact>? = nil) {
updateAnyContacts([contact], callbackQueue: callbackQueue, completion:
chooseFirst(then: completion, replacementError: .updateFailed(reason: "Failed to update contact")))
}
func deleteAnyContact(_ contact: OCKAnyContact, callbackQueue: DispatchQueue = .main, completion: OCKResultClosure<OCKAnyContact>? = nil) {
deleteAnyContacts([contact], callbackQueue: callbackQueue, completion:
chooseFirst(then: completion, replacementError: .deleteFailed(reason: "Failed to delete contact")))
}
}
// MARK: Async methods for OCKAnyReadOnlyContactStore
public extension OCKAnyReadOnlyContactStore {
/// `fetchAnyContacts` asynchronously retrieves an array of contacts from the store.
///
/// - Parameters:
/// - query: A query used to constrain the values that will be fetched.
func fetchAnyContacts(query: OCKContactQuery) async throws -> [OCKAnyContact] {
try await withCheckedThrowingContinuation { continuation in
fetchAnyContacts(query: query, callbackQueue: .main, completion: continuation.resume)
}
}
// MARK: Singular Methods - Implementation Provided
/// `fetchAnyContact` asynchronously retrieves a single contact from the store.
///
/// - Parameters:
/// - id: The identifier of the item to be fetched.
func fetchAnyContact(withID id: String) async throws -> OCKAnyContact {
try await withCheckedThrowingContinuation { continuation in
fetchAnyContact(withID: id, callbackQueue: .main, completion: continuation.resume)
}
}
}
// MARK: Async methods for OCKAnyContactStore
public extension OCKAnyContactStore {
/// `addAnyContacts` asynchronously adds an array of contacts to the store.
///
/// - Parameters:
/// - contacts: An array of contacts to be added to the store.
func addAnyContacts(_ contacts: [OCKAnyContact]) async throws -> [OCKAnyContact] {
try await withCheckedThrowingContinuation { continuation in
addAnyContacts(contacts, callbackQueue: .main, completion: continuation.resume)
}
}
/// `updateAnyContacts` asynchronously updates an array of contacts in the store.
///
/// - Parameters:
/// - contacts: An array of contacts to be updated. The contacts must already exist in the store.
func updateAnyContacts(_ contacts: [OCKAnyContact]) async throws -> [OCKAnyContact] {
try await withCheckedThrowingContinuation { continuation in
updateAnyContacts(contacts, callbackQueue: .main, completion: continuation.resume)
}
}
/// `deleteAnyContacts` asynchronously deletes an array of contacts from the store.
///
/// - Parameters:
/// - contacts: An array of contacts to be deleted. The contacts must exist in the store.
func deleteAnyContacts(_ contacts: [OCKAnyContact]) async throws -> [OCKAnyContact] {
try await withCheckedThrowingContinuation { continuation in
deleteAnyContacts(contacts, callbackQueue: .main, completion: continuation.resume)
}
}
// MARK: Singular Methods - Implementation Provided
/// `addAnyContact` asynchronously adds a single contact to the store.
///
/// - Parameters:
/// - contact: A single contact to be added to the store.
func addAnyContact(_ contact: OCKAnyContact) async throws -> OCKAnyContact {
try await withCheckedThrowingContinuation { continuation in
addAnyContact(contact, callbackQueue: .main, completion: continuation.resume)
}
}
/// `updateAnyContact` asynchronously update a single contact in the store.
///
/// - Parameters:
/// - contact: A single contact to be updated. The contact must already exist in the store.
func updateAnyContact(_ contact: OCKAnyContact) async throws -> OCKAnyContact {
try await withCheckedThrowingContinuation { continuation in
updateAnyContact(contact, callbackQueue: .main, completion: continuation.resume)
}
}
/// `deleteAnyContact` asynchronously deletes a single contact from the store.
///
/// - Parameters:
/// - contact: A single contact to be deleted. The contact must exist in the store.
func deleteAnyContact(_ contact: OCKAnyContact) async throws -> OCKAnyContact {
try await withCheckedThrowingContinuation { continuation in
deleteAnyContact(contact, callbackQueue: .main, completion: continuation.resume)
}
}
}
```
|
The Palace of Marqués de Grimaldi (Spanish: Palacio del Marqués de Grimaldi) is a palace located in Madrid, Spain. It was declared Bien de Interés Cultural in 2000.
History
Also called the Godoy Palace (Spanish : Palacio de Godoy), it is a stately residence located in Madrid (Spain). It is located in the central street of Bailén, almost in front of the Royal Palace and next to the Senate. It was designed by Francisco Sabatini and carried out during the years 1776 and 1782. Occupied for a few years by Manuel Godoy, at present the palace is the headquarters of the Center for Political and Constitutional Studies, dependent on the Ministry of the Presidency of the Government of Spain.
The building was designed by Francisco Sabatini by order of Carlos III, who wanted to build a dignified residence for his secretary of state, the Marquis de Grimaldi, in the surroundings of the Royal Palace. The new palace was built between 1776 and 1782 in the space located between the Colegio de Doña María de Aragón (current Senate) and the planned Calle Nueva (current Calle Bailén). Sabatini used stone and brick, combining these materials in the style of other monuments that he had designed in the capital, such as the Royal Customs House. Despite giving the building the popular name, the Marquis de Grimaldi was not the first to inhabit the Palace of the Secretaries of State, but his successor, the Count of Floridablanca in 1782.
During the Second Republic, it was proposed to establish the Museum of Popular Art and the Museum of Cars (the royal carriages from the demolished Royal Stables) in the vicinity of the Royal Palace. To this end, in 1934 the architect Luis Moya Blanco devised a new wing, annexed to the Almirantazgo Palace, which extended almost to Calle del Río and with a new and monumental main facade facing Calle Bailén. None of this took place.
Finally, from 1941 to 1943 it was renovated to house the Museum of the Spanish People, it was then that the current façade facing Bailén Street was erected. The museum, however, was only open briefly from 1971 to 1973, when works in the neighboring National Council of the Movement (now the Senate) forced its transfer. Since 1975, the palace has housed the Centre for Political and Constitutional Studies.
During some works in 2019, buried remains of the basements of the demolished part of the palace appeared, in a magnificent state of conservation.
References
External links
Palace of Marqués de Grimaldi
Buildings and structures in Palacio neighborhood, Madrid
Bien de Interés Cultural landmarks in Madrid
|
Maria Josefa Alhama y Valera, religious name Maria Esperanza of Jesus, (30 September 1893 – 8 February 1983) was a Spanish religious sister. She was the founder of both the Handmaids of Merciful Love in 1930 and the Sons of Merciful Love in 1951. ´
Valera was cleared for beatification in 2013 after a miracle that had found to have been attributed to her intercession was cleared. She was beatified on in 2014 by Cardinal Angelo Amato on behalf of Pope Francis.
Biography
Valera was born in 1893 in Spain to poor parents as the eldest of nine children. Her name of Maria Josefa was in honor of her grandmother. Her mother was a housewife while her father served as an agricultural worker. Valera studied as a child under female religious and it was from them she learnt how to do housework.
Valera received the holy communion age of 8, as she herself said, she "stole Jesus Christ". This occurred when the priest was absent and she went to the tabernacle to receive the communion.
At the age of 21 Valera became a member of the Congregation of the Daughters of Calvary in Villena. She established two of her own orders in 1930 and in 1951 for women and for men respectively.
In the 1950s she decided to begin a project that she believed represented the will of God: the construction of a sanctuary that would be dedicated to the love of God. On 22 November 1981, Pope John Paul II visited the sanctuary and visited Valera. In 1982, the pope recognized it as being a "minor basilica". She died in early 1983 and was buried in that church she worked hard to build.
Beatification
The cause of beatification commenced under Pope John Paul II on 9 March 1988 and the Positio - which documented her life of heroic virtue was submitted to the Congregation for the Causes of Saints in 1993. The pope recognized that she had lived a life of heroic virtue and named her to be Venerable on 23 April 2002.
An independent tribunal opened and closed in 2001 in response to a presumed miracle that had occurred. It submitted its findings to the congregation and Pope Francis approved the miracle on 5 July 2013. Cardinal Angelo Amato - on behalf of the pope - celebrated the beatification on 31 May 2014.
References
External links
Hagiography Circle
Saints SQPN
Handmaids of Merciful Love
Collevalenza
Familia Amor del Misericordioso
1893 births
1983 deaths
Spanish beatified people
Beatifications by Pope Francis
20th-century venerated Christians
Founders of Catholic religious communities
Venerated Catholics by Pope John Paul II
|
```xml
<clickhouse>
<remote_servers>
<cluster>
<shard>
<replica>
<host>node_ll</host>
<port>9000</port>
</replica>
<replica>
<host>node_no_ll</host>
<port>9000</port>
</replica>
</shard>
</cluster>
</remote_servers>
</clickhouse>
```
|
Synaphea polymorpha, commonly known as Albany synaphea, is a species of small shrub in the flowering plant family Proteaceae. It is endemic to Western Australia. The Noongar peoples know the plant as bindak.
The shrub can have a slender or rounded habit and typically grows to a height of . It blooms between August and November producing yellow flowers. Found in woodlands on hillsides, low-lying areas and swamps in the Great Southern region of Western Australia where it grows in sandy or clay-sand lateritic soils.
The species was first formally described by the botanist Robert Brown in 1810 in the work On the natural order of plants called Proteaceae in the journal Transactions of the Linnean Society of London.
References
polymorpha
Proteales of Australia
Eudicots of Western Australia
Plants described in 1810
|
Joe Adams (born January 4, 1944) is an American politician. succeeding Rory Ellinger, as a member of the Missouri House of Representatives, from 2015 to 2019. He was succeeded by Maria Chappelle-Nadal for one term, then after she stepped down, was elected again to his old seat in 2020, taking office in 2021. He is a member of the Democratic Party.
Personal
In 1960s, Adams served in the United States Air Force. He was a history professor at St. Louis Community College–Meramec where he taught American and African-American History for over 30 years.
Adams is a 1962 graduate of DeLaSalle High School. He earned his bachelor's degree in history from the University of Missouri-Kansas City in 1970 and went on to receive his an MA in urban American history from UMKC as well in 1971.
He has been a member of the following organizations: Missouri Historic Record Commission, Loop Trolley Board of Directors, National League of Cities, Missouri Commission on Intergovernmental Cooperation, Missouri Episcopal Diocese Commission on Ministry Board and Episcopal Cathedral Chapter Board. He served as President of the St. Louis County Municipal League, Missouri Municipal League and the Mayors of Large Cities of St. Louis County.
Adams received a variety of awards, including the Royal Vagabonds African-American Trailblazer Award; the City of University City Meritorious Service Award; the City of University City Gates of Opportunity Service Award; the St. Louis Legend Award; and the Buzz Westfall Award. In 1998, he was a member of the Leadership St. Louis.
Political career
From 1975 to 1995, Joe Adams served as the Ward 2 Councilman on the City Council of University City, Missouri. In 1995, Adams was elected Mayor of University City. He served as Mayor until 2010. From 2008 to 2009, Adams served as President of the Saint Louis County Municipal League. In 2014, Adams was elected to the Missouri State House of Representatives.
Adams represented District 86, which includes parts of St. Louis County including University City, Pagedale, Vinita Park, Wellston, Vinita Terrace and Hanley Hills in the Missouri House of Representatives. After trying to win the Democratic nomination for state senator in 2018, he ran again for his old seat in the House, winning in 2020.
Electoral history
State representative
State Senate
Committee membership
At the beginning of the 2017 legislative session, Adams served on the following committees:
Local Government – Ranking Minority Member
Elections and Elected Officials
Higher Education
References
1944 births
21st-century American politicians
Educators from Missouri
Living people
Democratic Party members of the Missouri House of Representatives
Politicians from Kansas City, Missouri
Politicians from St. Louis County, Missouri
20th-century American politicians
|
Pterolophia dubiosa is a species of beetle in the family Cerambycidae. It was described by Stephan von Breuning in 1938.
References
dubiosa
Beetles described in 1938
|
The swimming events of the 15th FINA World Aquatics Championships were held July 28 – August 4, 2013, in Barcelona, Spain. The competition was held in a long course pool inside the Palau Sant Jordi. It featured 40 LCM events, split evenly between males and females. Swimming was one of the five aquatic disciplines at the championships.
The United States won the overall medal count, led by Missy Franklin who claimed a record-setting six gold medals. China's Sun Yang won three gold medals en route to "male swimmer of the meet". Katie Ledecky, from the United States, was named "female swimmer of the meet" after setting two world records and winning four gold medals. Four other women's world records were broken during the competition, all four in the women's breaststroke events.
Qualifying criteria
If a nation entered one competitor in an event then they only have to meet the B standard, but if they enter two competitors then in an event then they both have to meet the A standard. Each member nation can enter one relay team in each event. Qualifying standards must have been met between July 1, 2012, and July 1, 2013.
Competition format:
events 200 meters and under: preliminaries-semifinals-finals (top 16 finishers from prelims advanced to semifinals; top-8 in the semifinals advanced to the final).
events 400 meters and longer: prelims/final (top 8 finishers from prelims advanced to the final).
Schedule
Recap
During the World Aquatic Championships, five world records were set (one twice), all by women. Katie Ledecky of the United States broke the world record in the 800-metre freestyle and the 1500-metre freestyle events en route to two gold medals. She also won the 400-metre freestyle to go 3-for-3 in her events. She added a fourth gold, swimming a leg of the 4x200-metre freestyle relay that the United States won. Her performance earned her "female swimmer of the meet," beating out fellow American Missy Franklin based on a formula that does not consider relay events. Franklin became the first woman ever to win six golds in a single World Championships. Kristin Otto of East Germany has achieved this at the 1988 Olympic Games. She won the 100-metre and 200-metre backstroke events and the 200-metre freestyle. She finished fourth in the 100-metre freestyle in personal best-time. She was also a part of all three women's relay events, which the United States swept. The previous record of five golds in a single World Championships was held by America's Tracy Caulkins and Australia's Libby Trickett. Among men, Michael Phelps and Mark Spitz of America, Ian Thorpe of Australia all won at least six golds in a single World Championships or Olympics. Franklin also moved into a tie with Trickett for most all-time gold medals with nine.
Rūta Meilutytė of Lithuania broke both the 50-metre and 100-metre breaststroke records in the semi-final of each event. Denmark's Rikke Møller Pedersen set the 200-metre breatstroke record in that event's semi-finals. However, it was Russia's Yuliya Yefimova who won the gold medal in both the 50-metre and 200-metre events, while Meilutytė took gold in the 100-metre.
On the men's side, Sun Yang claimed three golds by winning the 400-metre, 800-metre, and 1500-metre freestyle events to earn "male swimmer of the meet." He also swam China to bronze in the 4x200-metre freestyle relay despite starting his anchor leg two seconds behind third place. Ryan Lochte from the United States won two gold to bring his overall World Champions haul to 15. In the 4x100-metre medley relay, the United States appeared to finish first by a wide margin but was disqualified because a swimmer left the platform too early. As a result, France moved up to first. Camille Lacourt won France's first ever 50-metre backstroke title. César Cielo became the first three-time World Champion of the 50-metre free, winning a final that featured three Olympic gold medalists.
Medal summary
The United States won the overall medal count with 29 medals (24% of total available) and 13 golds (32%). China won the second most golds (5), but just 9 medals overall (down from 14 in the last World Championships). Australia won 13 medals (3 gold) for second place on the total medal count. Russia won 8 medals, the most for the nation since 1998. Germany, Great Britain, and Italy, all historically strong swimming nations, won just four medals among them.
Medal table
Host nation
Men
Women
Records
The following world and championship records were broken during the competition.
World records
Championship records
Legend: † – en route to final mark
References
2013 World Aquatics Championships
World Championships
Swimming at the World Aquatics Championships
International aquatics competitions hosted by Spain
|
```objective-c
#ifndef PYTHON_COMPAT
#define PYTHON_COMPAT
#include <torch/csrc/utils/pythoncapi_compat.h>
#ifdef __cplusplus
extern "C" {
#endif
// PyTorch-only compat functions
#define IS_PYTHON_3_11_PLUS PY_VERSION_HEX >= 0x030B00C1
#define IS_PYTHON_3_12_PLUS PY_VERSION_HEX >= 0x030C0000
#define IS_PYTHON_3_13_PLUS PY_VERSION_HEX >= 0x030D0000
#define IS_PYTHON_3_14_PLUS PY_VERSION_HEX >= 0x030E0000
PYCAPI_COMPAT_STATIC_INLINE(int)
PyCode_GetNCellvars(PyCodeObject* code) {
// gh-26364 added co_ncellvars to Python 3.11.0rc1
#if IS_PYTHON_3_11_PLUS
return code->co_ncellvars;
#else
return PyTuple_GET_SIZE(code->co_cellvars);
#endif
}
PYCAPI_COMPAT_STATIC_INLINE(int)
PyCode_GetNFreevars(PyCodeObject* code) {
// gh-26364 added co_nfreevars to Python 3.11.0rc1
#if IS_PYTHON_3_11_PLUS
return code->co_nfreevars;
#else
return PyTuple_GET_SIZE(code->co_freevars);
#endif
}
// Provided by CPython but getting the header for them is very hard
extern void _PyWeakref_ClearRef(PyWeakReference* self);
#ifdef __cplusplus
}
#endif
#endif // PYTHON_COMPAT
```
|
Hermanus Lodevicus Willebrordus "Manus" Vrauwdeunt (29 April 1915 – 8 June 1982) is a former Dutch footballer who was active as a midfielder and forward. Vrauwdeunt played his whole career at Feijenoord and won one cap for the Netherlands, a friendly match against Switzerland (2–1 victory) on 7 March 1937.
Honours
1935–36 : Eredivisie winner with Feijenoord
1937–38 : Eredivisie winner with Feijenoord
1939–40 : Eredivisie winner with Feijenoord
References
External links
Profile
1915 births
1982 deaths
Dutch men's footballers
Feyenoord players
Men's association football midfielders
Men's association football forwards
Footballers from Rotterdam
Netherlands men's international footballers
1934 FIFA World Cup players
|
Spaulding is an unincorporated community in the town of City Point, Jackson County, Wisconsin, United States.
Notes
Unincorporated communities in Jackson County, Wisconsin
Unincorporated communities in Wisconsin
|
```java
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.driver;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.oracle.svm.core.option.OptionUtils;
import com.oracle.svm.driver.NativeImage.BuildConfiguration;
import com.oracle.svm.driver.metainf.NativeImageMetaInfWalker;
import com.oracle.svm.core.util.ArchiveSupport;
final class MacroOption {
Path getOptionDirectory() {
return optionDirectory;
}
String getOptionName() {
return optionName;
}
String getDescription(boolean commandLineStyle) {
return kind.getDescriptionPrefix(commandLineStyle) + getOptionName();
}
@SuppressWarnings("serial")
static final class VerboseInvalidMacroException extends RuntimeException {
private final OptionUtils.MacroOptionKind forKind;
private final MacroOption context;
VerboseInvalidMacroException(String arg0, MacroOption context) {
this(arg0, null, context);
}
VerboseInvalidMacroException(String arg0, OptionUtils.MacroOptionKind forKind, MacroOption context) {
super(arg0);
this.forKind = forKind;
this.context = context;
}
public String getMessage(Registry registry) {
StringBuilder sb = new StringBuilder();
String message = super.getMessage();
if (context != null) {
sb.append(context.getDescription(false) + " contains ");
if (!message.isEmpty()) {
sb.append(Character.toLowerCase(message.charAt(0)));
sb.append(message.substring(1));
}
} else {
sb.append(message);
}
Consumer<String> lineOut = s -> sb.append("\n" + s);
registry.showOptions(forKind, context == null, lineOut);
return sb.toString();
}
}
@SuppressWarnings("serial")
static final class AddedTwiceException extends RuntimeException {
private final MacroOption option;
private final MacroOption context;
AddedTwiceException(MacroOption option, MacroOption context) {
this.option = option;
this.context = context;
}
@Override
public String getMessage() {
StringBuilder sb = new StringBuilder();
if (context != null) {
sb.append("MacroOption ").append(context.getDescription(false));
if (option.equals(context)) {
sb.append(" cannot require itself");
} else {
sb.append(" requires ").append(option.getDescription(false)).append(" more than once");
}
} else {
sb.append("Command line option ").append(option.getDescription(true));
sb.append(" used more than once");
}
return sb.toString();
}
}
static final class EnabledOption {
private final MacroOption option;
private final String optionArg;
private final boolean enabledFromCommandline;
private EnabledOption(MacroOption option, String optionArg, boolean enabledFromCommandline) {
this.option = Objects.requireNonNull(option);
this.optionArg = optionArg;
this.enabledFromCommandline = enabledFromCommandline;
}
private String resolvePropertyValue(BuildConfiguration config, String val) {
return NativeImage.resolvePropertyValue(val, optionArg, getOption().optionDirectory, config);
}
String getProperty(BuildConfiguration config, String key, String defaultVal) {
String val = option.properties.get(key);
if (val == null) {
return defaultVal;
}
return resolvePropertyValue(config, val);
}
String getProperty(BuildConfiguration config, String key) {
return getProperty(config, key, null);
}
boolean forEachPropertyValue(BuildConfiguration config, String propertyKey, Consumer<String> target) {
return forEachPropertyValue(config, propertyKey, target, " ");
}
boolean forEachPropertyValue(BuildConfiguration config, String propertyKey, Consumer<String> target, String separatorRegex) {
Function<String, String> resolvePropertyValue = str -> resolvePropertyValue(config, str);
return NativeImage.forEachPropertyValue(option.properties.get(propertyKey), target, resolvePropertyValue, separatorRegex);
}
MacroOption getOption() {
return option;
}
boolean isEnabledFromCommandline() {
return enabledFromCommandline;
}
}
static final class Registry {
private final Map<OptionUtils.MacroOptionKind, Map<String, MacroOption>> supported = new HashMap<>();
private final LinkedHashSet<EnabledOption> enabled = new LinkedHashSet<>();
private static Map<OptionUtils.MacroOptionKind, Map<String, MacroOption>> collectMacroOptions(Path rootDir) throws IOException {
Map<OptionUtils.MacroOptionKind, Map<String, MacroOption>> result = new HashMap<>();
for (OptionUtils.MacroOptionKind kind : OptionUtils.MacroOptionKind.values()) {
Path optionsDir = rootDir.resolve(kind.subdir);
Map<String, MacroOption> collectedOptions = Collections.emptyMap();
if (Files.isDirectory(optionsDir)) {
collectedOptions = Files.list(optionsDir).filter(Files::isDirectory)
.filter(optionDir -> Files.isReadable(optionDir.resolve(NativeImageMetaInfWalker.nativeImagePropertiesFilename)))
.map(MacroOption::create).filter(Objects::nonNull)
.collect(Collectors.toMap(MacroOption::getOptionName, Function.identity()));
}
result.put(kind, collectedOptions);
}
return result;
}
Registry() {
for (OptionUtils.MacroOptionKind kind : OptionUtils.MacroOptionKind.values()) {
supported.put(kind, new HashMap<>());
}
}
void addMacroOptionRoot(Path rootDir) {
/* Discover MacroOptions and add to supported */
try {
collectMacroOptions(rootDir).forEach((optionKind, optionMap) -> {
supported.get(optionKind).putAll(optionMap);
});
} catch (IOException e) {
throw new OptionUtils.InvalidMacroException("Error while discovering supported MacroOptions in " + rootDir + ": " + e.getMessage());
}
}
Set<String> getAvailableOptions(OptionUtils.MacroOptionKind forKind) {
return supported.get(forKind).keySet();
}
void showOptions(OptionUtils.MacroOptionKind forKind, boolean commandLineStyle, Consumer<String> lineOut) {
List<String> optionsToShow = new ArrayList<>();
for (OptionUtils.MacroOptionKind kind : OptionUtils.MacroOptionKind.values()) {
if (forKind != null && !kind.equals(forKind)) {
continue;
}
if (forKind == null && kind == OptionUtils.MacroOptionKind.Macro) {
// skip non-API macro options by default
continue;
}
for (MacroOption option : supported.get(kind).values()) {
if (!option.kind.subdir.isEmpty()) {
String linePrefix = " ";
if (commandLineStyle) {
linePrefix += OptionUtils.MacroOptionKind.macroOptionPrefix;
}
optionsToShow.add(linePrefix + option);
}
}
}
if (!optionsToShow.isEmpty()) {
StringBuilder sb = new StringBuilder().append("Available ");
if (forKind != null) {
sb.append(forKind.toString()).append(' ');
} else {
sb.append("macro-");
}
lineOut.accept(sb.append("options are:").toString());
optionsToShow.stream().sorted().forEachOrdered(lineOut);
}
}
MacroOption getMacroOption(OptionUtils.MacroOptionKind kindPart, String optionName) {
return supported.get(kindPart).get(optionName);
}
boolean enableOption(BuildConfiguration config, String optionString, HashSet<MacroOption> addedCheck, MacroOption context, Consumer<EnabledOption> enabler) {
String specString;
if (context == null) {
if (optionString.startsWith(OptionUtils.MacroOptionKind.macroOptionPrefix)) {
specString = optionString.substring(OptionUtils.MacroOptionKind.macroOptionPrefix.length());
} else {
return false;
}
} else {
specString = optionString;
}
String[] specParts = specString.split(":", 2);
if (specParts.length != 2) {
if (context == null) {
return false;
} else {
throw new VerboseInvalidMacroException("Invalid option specification: " + optionString, context);
}
}
OptionUtils.MacroOptionKind kindPart;
try {
kindPart = OptionUtils.MacroOptionKind.fromString(specParts[0]);
} catch (Exception e) {
if (context == null) {
return false;
} else {
throw new VerboseInvalidMacroException("Unknown kind in option specification: " + optionString, context);
}
}
String specNameParts = specParts[1];
if (specNameParts.isEmpty()) {
throw new VerboseInvalidMacroException("Empty option specification: " + optionString, kindPart, context);
}
if (specNameParts.equals("all")) {
if (!kindPart.allowAll) {
throw new VerboseInvalidMacroException("Empty option specification: " + kindPart + " does no support 'all'", kindPart, context);
}
for (String optionName : getAvailableOptions(kindPart)) {
MacroOption option = getMacroOption(kindPart, optionName);
if (Boolean.parseBoolean(option.properties.getOrDefault("ExcludeFromAll", "false"))) {
continue;
}
enableResolved(config, option, null, addedCheck, context, enabler);
}
return true;
}
String[] parts = specNameParts.split("=", 2);
String optionName = parts[0];
MacroOption option = getMacroOption(kindPart, optionName);
if (option != null) {
String optionArg = parts.length == 2 ? parts[1] : null;
enableResolved(config, option, optionArg, addedCheck, context, enabler);
} else {
throw new VerboseInvalidMacroException("Unknown name in option specification: " + kindPart + ":" + optionName, kindPart, context);
}
return true;
}
private void enableResolved(BuildConfiguration config, MacroOption option, String optionArg, HashSet<MacroOption> addedCheck, MacroOption context, Consumer<EnabledOption> enabler) {
if (addedCheck.contains(option)) {
return;
}
addedCheck.add(option);
EnabledOption enabledOption = new EnabledOption(option, optionArg, context == null);
if (optionArg == null) {
String defaultArg = enabledOption.getProperty(config, "DefaultArg");
if (defaultArg != null) {
enabledOption = new EnabledOption(option, defaultArg, context == null);
}
}
String requires = enabledOption.getProperty(config, "Requires", "");
if (!requires.isEmpty()) {
for (String specString : requires.split(" ")) {
enableOption(config, specString, addedCheck, option, enabler);
}
}
if (option.kind.equals(OptionUtils.MacroOptionKind.Language)) {
MacroOption truffleOption = getMacroOption(OptionUtils.MacroOptionKind.Macro, "truffle");
if (truffleOption == null) {
throw new VerboseInvalidMacroException("Cannot locate the truffle macro", null);
}
if (!addedCheck.contains(truffleOption)) {
/*
* Every language requires Truffle. If it is not specified explicitly as a
* requirement, add it automatically.
*/
enableResolved(config, truffleOption, null, addedCheck, option, enabler);
}
}
enabler.accept(enabledOption);
enabled.add(enabledOption);
}
LinkedHashSet<EnabledOption> getEnabledOptions(OptionUtils.MacroOptionKind kind) {
return enabled.stream().filter(eo -> kind.equals(eo.option.kind)).collect(Collectors.toCollection(LinkedHashSet::new));
}
Stream<EnabledOption> getEnabledOptionsStream(OptionUtils.MacroOptionKind kind, OptionUtils.MacroOptionKind... otherKinds) {
EnumSet<OptionUtils.MacroOptionKind> kindSet = EnumSet.of(kind, otherKinds);
return enabled.stream().filter(eo -> kindSet.contains(eo.option.kind));
}
LinkedHashSet<EnabledOption> getEnabledOptions() {
return enabled;
}
EnabledOption getEnabledOption(MacroOption option) {
return enabled.stream().filter(eo -> eo.getOption().equals(option)).findFirst().orElse(null);
}
}
private final String optionName;
private final Path optionDirectory;
final OptionUtils.MacroOptionKind kind;
private final Map<String, String> properties;
private static MacroOption create(Path macroOptionDirectory) {
try {
return new MacroOption(macroOptionDirectory);
} catch (Exception e) {
return null;
}
}
private MacroOption(Path optionDirectory) {
this.kind = OptionUtils.MacroOptionKind.fromSubdir(optionDirectory.getParent().getFileName().toString());
this.optionName = optionDirectory.getFileName().toString();
this.optionDirectory = optionDirectory;
this.properties = ArchiveSupport.loadProperties(optionDirectory.resolve(NativeImageMetaInfWalker.nativeImagePropertiesFilename));
}
@Override
public String toString() {
return getDescription(false);
}
}
```
|
William Ray Collins Jr. (September 21, 1961 – March 6, 1984) was an American professional boxer who competed from 1981 to 1983. He was undefeated before his career was cut short after his final fight when he sustained serious injuries against Luis Resto in their ten-round bout. Aided by his trainer Panama Lewis, Resto used illegal, tampered gloves with an ounce of the gloves' cushioning removed, along with hand wraps which had been soaked in plaster of Paris.
Professional career
Billy Collins was born to a working-class Irish family in Antioch, Tennessee. His father (whose mother was Native American) was a former welterweight professional boxer who had once fought world champion Curtis Cokes. He trained his son to follow in his footsteps since before kindergarten. Also a welterweight, Collins won his first 14 fights as a professional, among them a decision over future world title challenger Harold Brazier.
Final fight against Luis Resto
Collins was matched against Puerto Rican journeyman Luis Resto at Madison Square Garden in New York on June 16, 1983, on the undercard of the Roberto Durán vs. Davey Moore light middleweight title fight. Collins entered the fight as a betting favorite but took a heavy beating and lost by a unanimous decision.
At the end of the fight, Collins' father and trainer, Billy Sr., noticed that Resto's gloves felt thinner than normal and demanded that they be impounded. A subsequent investigation by the New York State Boxing Commission concluded that Resto's trainer, Panama Lewis, had removed an ounce of padding from each glove, making his punches harder and more damaging to Collins. The fight result was changed to a no contest.
Lewis' New York boxing license was permanently revoked, effectively banning him from any official role in American boxing for life. Resto was suspended indefinitely and never fought again. In 1986, Lewis and Resto were tried and convicted of assault, conspiracy, and criminal possession of a deadly weapon (Resto's plaster of paris wraps); prosecutors felt that Lewis' actions made the fight an illegal assault on Collins. Both served two and a half years in prison.
Injuries and auto accident
In the Resto fight, Collins' eyes were swollen shut. He suffered a torn iris and permanently blurred vision, which left him unable to box again.
On March 6, 1984, Collins was killed when the car in which he and his best friend were driving crashed into a culvert near his home in Antioch, Tennessee, a suburb of Nashville. The autopsy showed he died a short time later at the scene of the accident. According to an account in Sports Illustrated, the crash was intentional.
Legal action
In July 1983, Collins and his family sued Lewis, Resto, fight promoter Top Rank Boxing, the inspectors, the bout's referee and Everlast (the manufacturer of Resto's gloves) for gross negligence and loss of income. The suit against Everlast was dismissed by the Federal Court which found that there was no liability since the gloves had been tampered with after they were delivered by Everlast. Collins, Sr. and Collins' widow Andrea then sued the New York State Boxing Commission for failing to protect Collins. The commission argued that the term "inspection" was so broad that there was no way to determine whether the fight's inspectors could have done more than they did. It also claimed that Top Rank actually hired the inspectors and bore more responsibility for their behavior. A court ruled in favor of the commission, and the court also noted that Collins' death ended any potential future damages. However, Collins' widow, now known as Andrea Collins-Nile, attempted to reopen the suit. The request was denied. The state subsequently changed its rules to prevent a repeat of what happened to Collins. The Collins family never saw any compensation.
Further revelations by Resto
In 2007, Resto made a tearful apology to Collins-Nile for his role in the scheme unexpectedly during the making of a Showtime documentary about the fight. He also admitted that his hand wraps had been soaked in plaster of Paris before the fight. This caused them to harden into plaster casts like those used to set broken bones. The hand wraps were never confiscated and did not figure into the official investigation of the tampering incident. However, the combined effect of the plaster casts and unpadded gloves meant that Resto was effectively striking Collins with rocks. At a 2008 press conference, Resto not only admitted to knowing that Lewis had tampered with the gloves, but had done so at least twice before. The 1983 incident and subsequent aftermath is covered in the 2008 Showtime documentary Assault in the Ring.
Professional boxing record
References
External links
Luis Resto vs. Billy Collins Jr. (1983) – A Retrospective Ring Report at eastsideboxing.com (archived)
Collins vs. Resto (full fight) on YouTube
1961 births
1984 suicides
1984 deaths
Light-middleweight boxers
American male boxers
American people of Irish descent
Road incident deaths in Tennessee
People from Antioch, Tennessee
Sportspeople from the Nashville metropolitan area
Burials at Woodlawn Memorial Park Cemetery (Nashville, Tennessee)
|
Pauline "Polly" Whittier (December 9, 1876 – March 3, 1946) was an American golfer who competed in the 1900 Summer Olympics. She was born in Boston, Massachusetts. Whittier won the silver medal in the women's competition. She was a daughter of Col. Charles A. Whittier, and in 1904 she married Ernest Iselin, son of Adrian Iselin Jr.
References
External links
American female golfers
Amateur golfers
Golfers at the 1900 Summer Olympics
Olympic silver medalists for the United States in golf
Medalists at the 1900 Summer Olympics
Golfers from Massachusetts
Sportspeople from Boston
1876 births
1946 deaths
Iselin family
|
```c
/* pcy_node.c */
/*
* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
* 2004.
*/
/* ====================================================================
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (path_to_url"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (path_to_url"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com). */
#include <openssl/asn1.h>
#include <openssl/mem.h>
#include <openssl/obj.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "pcy_int.h"
static int node_cmp(const X509_POLICY_NODE **a, const X509_POLICY_NODE **b)
{
return OBJ_cmp((*a)->data->valid_policy, (*b)->data->valid_policy);
}
STACK_OF(X509_POLICY_NODE) *policy_node_cmp_new(void)
{
return sk_X509_POLICY_NODE_new(node_cmp);
}
X509_POLICY_NODE *tree_find_sk(STACK_OF(X509_POLICY_NODE) *nodes,
const ASN1_OBJECT *id)
{
X509_POLICY_DATA n;
X509_POLICY_NODE l;
size_t idx;
n.valid_policy = (ASN1_OBJECT *)id;
l.data = &n;
if (!sk_X509_POLICY_NODE_find(nodes, &idx, &l))
return NULL;
return sk_X509_POLICY_NODE_value(nodes, idx);
}
X509_POLICY_NODE *level_find_node(const X509_POLICY_LEVEL *level,
const X509_POLICY_NODE *parent,
const ASN1_OBJECT *id)
{
X509_POLICY_NODE *node;
size_t i;
for (i = 0; i < sk_X509_POLICY_NODE_num(level->nodes); i++) {
node = sk_X509_POLICY_NODE_value(level->nodes, i);
if (node->parent == parent) {
if (!OBJ_cmp(node->data->valid_policy, id))
return node;
}
}
return NULL;
}
X509_POLICY_NODE *level_add_node(X509_POLICY_LEVEL *level,
const X509_POLICY_DATA *data,
X509_POLICY_NODE *parent,
X509_POLICY_TREE *tree)
{
X509_POLICY_NODE *node;
node = OPENSSL_malloc(sizeof(X509_POLICY_NODE));
if (!node)
return NULL;
node->data = data;
node->parent = parent;
node->nchild = 0;
if (level) {
if (OBJ_obj2nid(data->valid_policy) == NID_any_policy) {
if (level->anyPolicy)
goto node_error;
level->anyPolicy = node;
} else {
if (!level->nodes)
level->nodes = policy_node_cmp_new();
if (!level->nodes)
goto node_error;
if (!sk_X509_POLICY_NODE_push(level->nodes, node))
goto node_error;
}
}
if (tree) {
if (!tree->extra_data)
tree->extra_data = sk_X509_POLICY_DATA_new_null();
if (!tree->extra_data)
goto node_error;
if (!sk_X509_POLICY_DATA_push(tree->extra_data, data))
goto node_error;
}
if (parent)
parent->nchild++;
return node;
node_error:
policy_node_free(node);
return 0;
}
void policy_node_free(X509_POLICY_NODE *node)
{
OPENSSL_free(node);
}
/*
* See if a policy node matches a policy OID. If mapping enabled look through
* expected policy set otherwise just valid policy.
*/
int policy_node_match(const X509_POLICY_LEVEL *lvl,
const X509_POLICY_NODE *node, const ASN1_OBJECT *oid)
{
size_t i;
ASN1_OBJECT *policy_oid;
const X509_POLICY_DATA *x = node->data;
if ((lvl->flags & X509_V_FLAG_INHIBIT_MAP)
|| !(x->flags & POLICY_DATA_FLAG_MAP_MASK)) {
if (!OBJ_cmp(x->valid_policy, oid))
return 1;
return 0;
}
for (i = 0; i < sk_ASN1_OBJECT_num(x->expected_policy_set); i++) {
policy_oid = sk_ASN1_OBJECT_value(x->expected_policy_set, i);
if (!OBJ_cmp(policy_oid, oid))
return 1;
}
return 0;
}
```
|
```go
/*
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package record
import (
"fmt"
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/runtime"
)
// FakeRecorder is used as a fake during tests.
type FakeRecorder struct {
Events []string
}
func (f *FakeRecorder) Event(object runtime.Object, eventtype, reason, message string) {
f.Events = append(f.Events, fmt.Sprintf("%s %s %s", eventtype, reason, message))
}
func (f *FakeRecorder) Eventf(object runtime.Object, eventtype, reason, messageFmt string, args ...interface{}) {
f.Events = append(f.Events, fmt.Sprintf(eventtype+" "+reason+" "+messageFmt, args...))
}
func (f *FakeRecorder) PastEventf(object runtime.Object, timestamp unversioned.Time, eventtype, reason, messageFmt string, args ...interface{}) {
}
```
|
Elizabeth Courtney may refer to:
Eliza Courtney (1792–1859), illegitimate daughter of Prime Minister Charles Grey, 2nd Earl Grey and Georgiana, Duchess of Devonshire
See also
Elizabeth Courtenay (disambiguation)
|
```css
Make text unselectable
Determine the opacity of background-colors using the RGBA declaration
Removing the bullets from the `ul`
How to flip an image
`:required` and `:optional` pseudo classes
```
|
```xml
import expect from 'expect';
import { getSuggestionsFactory as getSuggestions } from './useSuggestions';
describe('getSuggestions', () => {
const choices = [
{ id: 1, value: 'one' },
{ id: 2, value: 'two' },
{ id: 3, value: 'three' },
];
const defaultOptions = {
choices,
getChoiceText: ({ value }) => value,
getChoiceValue: ({ id }) => id,
matchSuggestion: undefined,
optionText: 'value',
selectedItem: undefined,
};
it('should return all suggestions when filtered by empty string', () => {
expect(getSuggestions(defaultOptions)('')).toEqual(choices);
});
it('should filter choices according to the filter argument', () => {
expect(getSuggestions(defaultOptions)('o')).toEqual([
{ id: 1, value: 'one' },
{ id: 2, value: 'two' },
]);
expect(
getSuggestions({
...defaultOptions,
choices: [
{ id: 0, value: '0' },
{ id: 1, value: 'one' },
],
})('0')
).toEqual([{ id: 0, value: '0' }]);
});
it('should filter choices according to the filter argument when it contains RegExp reserved characters', () => {
expect(
getSuggestions({
...defaultOptions,
choices: [
{ id: 1, value: '**one' },
{ id: 2, value: 'two' },
{ id: 3, value: 'three' },
],
})('**o')
).toEqual([{ id: 1, value: '**one' }]);
});
it('should add createSuggestion if allowCreate is true', () => {
expect(
getSuggestions({
...defaultOptions,
allowCreate: true,
})('')
).toEqual([
{ id: 1, value: 'one' },
{ id: 2, value: 'two' },
{ id: 3, value: 'three' },
{ id: '@@create', value: 'ra.action.create' },
]);
});
it('should not add createSuggestion if allowCreate is true and the current filter matches exactly the selected item', () => {
expect(
getSuggestions({
...defaultOptions,
selectedItem: { id: 1, value: 'one' },
allowCreate: true,
})('one')
).toEqual([
{ id: 1, value: 'one' },
{ id: 2, value: 'two' },
{ id: 3, value: 'three' },
]);
});
it('should add createSuggestion if allowCreate is true and selectedItem is an array', () => {
expect(
getSuggestions({
...defaultOptions,
selectedItem: [
{ id: 1, value: 'one' },
{ id: 2, value: 'two' },
],
allowCreate: true,
})('')
).toEqual([
{ id: 1, value: 'one' },
{ id: 2, value: 'two' },
{ id: 3, value: 'three' },
{ id: '@@create', value: 'ra.action.create' },
]);
});
it('should limit the number of choices', () => {
expect(
getSuggestions({
...defaultOptions,
suggestionLimit: 2,
})('')
).toEqual([
{ id: 1, value: 'one' },
{ id: 2, value: 'two' },
]);
expect(
getSuggestions({
...defaultOptions,
suggestionLimit: 2,
})('')
).toEqual([
{ id: 1, value: 'one' },
{ id: 2, value: 'two' },
]);
});
it('should return all choices on empty/falsy values', () => {
expect(getSuggestions(defaultOptions)(undefined)).toEqual(choices);
expect(getSuggestions(defaultOptions)(false)).toEqual(choices);
expect(getSuggestions(defaultOptions)(null)).toEqual(choices);
});
it('should return all choices if allowDuplicates is true', () => {
expect(
getSuggestions({
...defaultOptions,
allowDuplicates: true,
selectedItem: choices[0],
})('')
).toEqual([
{ id: 1, value: 'one' },
{ id: 2, value: 'two' },
{ id: 3, value: 'three' },
]);
});
it('should return all the filtered choices if allowDuplicates is true', () => {
expect(
getSuggestions({
...defaultOptions,
allowDuplicates: true,
selectedItem: [choices[0]],
})('o')
).toEqual([
{ id: 1, value: 'one' },
{ id: 2, value: 'two' },
]);
});
});
```
|
Mtara Maecha (born 28 February 1940) is a Comorian politician. He was foreign minister of Comoros from 1990 to 1991. He was replaced by Said Hassane Said Hachim.
References
1940 births
Living people
Foreign ministers of the Comoros
Government ministers of the Comoros
Candidates for President of the Comoros
|
```groff
.\" $OpenBSD: conj.3,v 1.5 2019/01/25 00:19:25 millert Exp $
.\"
.\"
.\" Permission to use, copy, modify, and distribute this software for any
.\" purpose with or without fee is hereby granted, provided that the above
.\" copyright notice and this permission notice appear in all copies.
.\"
.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
.\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
.\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
.\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
.\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
.\"
.Dd $Mdocdate: January 25 2019 $
.Dt CONJ 3
.Os
.Sh NAME
.Nm conj ,
.Nm conjf ,
.Nm conjl
.Nd compute the complex conjugate
.Sh SYNOPSIS
.In complex.h
.Ft double complex
.Fn conj "double complex z"
.Ft float complex
.Fn conjf "float complex z"
.Ft long double complex
.Fn conjl "long double complex z"
.Sh DESCRIPTION
The
.Fn conj ,
.Fn conjf
and
.Fn conjl
functions reverse the sign of the imaginary part of
.Fa z ,
producing the complex conjugate.
.Sh RETURN VALUES
The
.Fn conj ,
.Fn conjf
and
.Fn conjl
functions return the complex conjugate of the complex number
.Fa z .
.Sh SEE ALSO
.Xr carg 3
.Sh STANDARDS
The
.Fn conj ,
.Fn conjf
and
.Fn conjl
functions conform to
.St -isoC-99 .
```
|
```go
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// Viper is an application configuration system.
// It believes that applications can be configured a variety of ways
// via flags, ENVIRONMENT variables, configuration files retrieved
// from the file system, or a remote key/value store.
// Each item takes precedence over the item below it:
// overrides
// flag
// env
// config
// key/value store
// default
package viper
import (
"bytes"
"encoding/csv"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/fsnotify/fsnotify"
"github.com/mitchellh/mapstructure"
slog "github.com/sagikazarmark/slog-shim"
"github.com/spf13/afero"
"github.com/spf13/cast"
"github.com/spf13/pflag"
"github.com/spf13/viper/internal/encoding"
"github.com/spf13/viper/internal/encoding/dotenv"
"github.com/spf13/viper/internal/encoding/hcl"
"github.com/spf13/viper/internal/encoding/ini"
"github.com/spf13/viper/internal/encoding/javaproperties"
"github.com/spf13/viper/internal/encoding/json"
"github.com/spf13/viper/internal/encoding/toml"
"github.com/spf13/viper/internal/encoding/yaml"
"github.com/spf13/viper/internal/features"
)
// ConfigMarshalError happens when failing to marshal the configuration.
type ConfigMarshalError struct {
err error
}
// Error returns the formatted configuration error.
func (e ConfigMarshalError) Error() string {
return fmt.Sprintf("While marshaling config: %s", e.err.Error())
}
var v *Viper
type RemoteResponse struct {
Value []byte
Error error
}
func init() {
v = New()
}
type remoteConfigFactory interface {
Get(rp RemoteProvider) (io.Reader, error)
Watch(rp RemoteProvider) (io.Reader, error)
WatchChannel(rp RemoteProvider) (<-chan *RemoteResponse, chan bool)
}
// RemoteConfig is optional, see the remote package.
var RemoteConfig remoteConfigFactory
// UnsupportedConfigError denotes encountering an unsupported
// configuration filetype.
type UnsupportedConfigError string
// Error returns the formatted configuration error.
func (str UnsupportedConfigError) Error() string {
return fmt.Sprintf("Unsupported Config Type %q", string(str))
}
// UnsupportedRemoteProviderError denotes encountering an unsupported remote
// provider. Currently only etcd and Consul are supported.
type UnsupportedRemoteProviderError string
// Error returns the formatted remote provider error.
func (str UnsupportedRemoteProviderError) Error() string {
return fmt.Sprintf("Unsupported Remote Provider Type %q", string(str))
}
// RemoteConfigError denotes encountering an error while trying to
// pull the configuration from the remote provider.
type RemoteConfigError string
// Error returns the formatted remote provider error.
func (rce RemoteConfigError) Error() string {
return fmt.Sprintf("Remote Configurations Error: %s", string(rce))
}
// ConfigFileNotFoundError denotes failing to find configuration file.
type ConfigFileNotFoundError struct {
name, locations string
}
// Error returns the formatted configuration error.
func (fnfe ConfigFileNotFoundError) Error() string {
return fmt.Sprintf("Config File %q Not Found in %q", fnfe.name, fnfe.locations)
}
// ConfigFileAlreadyExistsError denotes failure to write new configuration file.
type ConfigFileAlreadyExistsError string
// Error returns the formatted error when configuration already exists.
func (faee ConfigFileAlreadyExistsError) Error() string {
return fmt.Sprintf("Config File %q Already Exists", string(faee))
}
// A DecoderConfigOption can be passed to viper.Unmarshal to configure
// mapstructure.DecoderConfig options.
type DecoderConfigOption func(*mapstructure.DecoderConfig)
// DecodeHook returns a DecoderConfigOption which overrides the default
// DecoderConfig.DecodeHook value, the default is:
//
// mapstructure.ComposeDecodeHookFunc(
// mapstructure.StringToTimeDurationHookFunc(),
// mapstructure.StringToSliceHookFunc(","),
// )
func DecodeHook(hook mapstructure.DecodeHookFunc) DecoderConfigOption {
return func(c *mapstructure.DecoderConfig) {
c.DecodeHook = hook
}
}
// Viper is a prioritized configuration registry. It
// maintains a set of configuration sources, fetches
// values to populate those, and provides them according
// to the source's priority.
// The priority of the sources is the following:
// 1. overrides
// 2. flags
// 3. env. variables
// 4. config file
// 5. key/value store
// 6. defaults
//
// For example, if values from the following sources were loaded:
//
// Defaults : {
// "secret": "",
// "user": "default",
// "endpoint": "path_to_url"
// }
// Config : {
// "user": "root"
// "secret": "defaultsecret"
// }
// Env : {
// "secret": "somesecretkey"
// }
//
// The resulting config will have the following values:
//
// {
// "secret": "somesecretkey",
// "user": "root",
// "endpoint": "path_to_url"
// }
//
// Note: Vipers are not safe for concurrent Get() and Set() operations.
type Viper struct {
// Delimiter that separates a list of keys
// used to access a nested value in one go
keyDelim string
// A set of paths to look for the config file in
configPaths []string
// The filesystem to read config from.
fs afero.Fs
// A set of remote providers to search for the configuration
remoteProviders []*defaultRemoteProvider
// Name of file to look for inside the path
configName string
configFile string
configType string
configPermissions os.FileMode
envPrefix string
// Specific commands for ini parsing
iniLoadOptions ini.LoadOptions
automaticEnvApplied bool
envKeyReplacer StringReplacer
allowEmptyEnv bool
parents []string
config map[string]any
override map[string]any
defaults map[string]any
kvstore map[string]any
pflags map[string]FlagValue
env map[string][]string
aliases map[string]string
typeByDefValue bool
onConfigChange func(fsnotify.Event)
logger *slog.Logger
// TODO: should probably be protected with a mutex
encoderRegistry *encoding.EncoderRegistry
decoderRegistry *encoding.DecoderRegistry
}
// New returns an initialized Viper instance.
func New() *Viper {
v := new(Viper)
v.keyDelim = "."
v.configName = "config"
v.configPermissions = os.FileMode(0o644)
v.fs = afero.NewOsFs()
v.config = make(map[string]any)
v.parents = []string{}
v.override = make(map[string]any)
v.defaults = make(map[string]any)
v.kvstore = make(map[string]any)
v.pflags = make(map[string]FlagValue)
v.env = make(map[string][]string)
v.aliases = make(map[string]string)
v.typeByDefValue = false
v.logger = slog.New(&discardHandler{})
v.resetEncoding()
return v
}
// Option configures Viper using the functional options paradigm popularized by Rob Pike and Dave Cheney.
// If you're unfamiliar with this style,
// see path_to_url and
// path_to_url
type Option interface {
apply(v *Viper)
}
type optionFunc func(v *Viper)
func (fn optionFunc) apply(v *Viper) {
fn(v)
}
// KeyDelimiter sets the delimiter used for determining key parts.
// By default it's value is ".".
func KeyDelimiter(d string) Option {
return optionFunc(func(v *Viper) {
v.keyDelim = d
})
}
// StringReplacer applies a set of replacements to a string.
type StringReplacer interface {
// Replace returns a copy of s with all replacements performed.
Replace(s string) string
}
// EnvKeyReplacer sets a replacer used for mapping environment variables to internal keys.
func EnvKeyReplacer(r StringReplacer) Option {
return optionFunc(func(v *Viper) {
v.envKeyReplacer = r
})
}
// NewWithOptions creates a new Viper instance.
func NewWithOptions(opts ...Option) *Viper {
v := New()
for _, opt := range opts {
opt.apply(v)
}
v.resetEncoding()
return v
}
// Reset is intended for testing, will reset all to default settings.
// In the public interface for the viper package so applications
// can use it in their testing as well.
func Reset() {
v = New()
SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl", "tfvars", "dotenv", "env", "ini"}
SupportedRemoteProviders = []string{"etcd", "etcd3", "consul", "firestore", "nats"}
}
// TODO: make this lazy initialization instead.
func (v *Viper) resetEncoding() {
encoderRegistry := encoding.NewEncoderRegistry()
decoderRegistry := encoding.NewDecoderRegistry()
{
codec := yaml.Codec{}
encoderRegistry.RegisterEncoder("yaml", codec)
decoderRegistry.RegisterDecoder("yaml", codec)
encoderRegistry.RegisterEncoder("yml", codec)
decoderRegistry.RegisterDecoder("yml", codec)
}
{
codec := json.Codec{}
encoderRegistry.RegisterEncoder("json", codec)
decoderRegistry.RegisterDecoder("json", codec)
}
{
codec := toml.Codec{}
encoderRegistry.RegisterEncoder("toml", codec)
decoderRegistry.RegisterDecoder("toml", codec)
}
{
codec := hcl.Codec{}
encoderRegistry.RegisterEncoder("hcl", codec)
decoderRegistry.RegisterDecoder("hcl", codec)
encoderRegistry.RegisterEncoder("tfvars", codec)
decoderRegistry.RegisterDecoder("tfvars", codec)
}
{
codec := ini.Codec{
KeyDelimiter: v.keyDelim,
LoadOptions: v.iniLoadOptions,
}
encoderRegistry.RegisterEncoder("ini", codec)
decoderRegistry.RegisterDecoder("ini", codec)
}
{
codec := &javaproperties.Codec{
KeyDelimiter: v.keyDelim,
}
encoderRegistry.RegisterEncoder("properties", codec)
decoderRegistry.RegisterDecoder("properties", codec)
encoderRegistry.RegisterEncoder("props", codec)
decoderRegistry.RegisterDecoder("props", codec)
encoderRegistry.RegisterEncoder("prop", codec)
decoderRegistry.RegisterDecoder("prop", codec)
}
{
codec := &dotenv.Codec{}
encoderRegistry.RegisterEncoder("dotenv", codec)
decoderRegistry.RegisterDecoder("dotenv", codec)
encoderRegistry.RegisterEncoder("env", codec)
decoderRegistry.RegisterDecoder("env", codec)
}
v.encoderRegistry = encoderRegistry
v.decoderRegistry = decoderRegistry
}
type defaultRemoteProvider struct {
provider string
endpoint string
path string
secretKeyring string
}
func (rp defaultRemoteProvider) Provider() string {
return rp.provider
}
func (rp defaultRemoteProvider) Endpoint() string {
return rp.endpoint
}
func (rp defaultRemoteProvider) Path() string {
return rp.path
}
func (rp defaultRemoteProvider) SecretKeyring() string {
return rp.secretKeyring
}
// RemoteProvider stores the configuration necessary
// to connect to a remote key/value store.
// Optional secretKeyring to unencrypt encrypted values
// can be provided.
type RemoteProvider interface {
Provider() string
Endpoint() string
Path() string
SecretKeyring() string
}
// SupportedExts are universally supported extensions.
var SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl", "tfvars", "dotenv", "env", "ini"}
// SupportedRemoteProviders are universally supported remote providers.
var SupportedRemoteProviders = []string{"etcd", "etcd3", "consul", "firestore", "nats"}
// OnConfigChange sets the event handler that is called when a config file changes.
func OnConfigChange(run func(in fsnotify.Event)) { v.OnConfigChange(run) }
// OnConfigChange sets the event handler that is called when a config file changes.
func (v *Viper) OnConfigChange(run func(in fsnotify.Event)) {
v.onConfigChange = run
}
// WatchConfig starts watching a config file for changes.
func WatchConfig() { v.WatchConfig() }
// WatchConfig starts watching a config file for changes.
func (v *Viper) WatchConfig() {
initWG := sync.WaitGroup{}
initWG.Add(1)
go func() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
v.logger.Error(fmt.Sprintf("failed to create watcher: %s", err))
os.Exit(1)
}
defer watcher.Close()
// we have to watch the entire directory to pick up renames/atomic saves in a cross-platform way
filename, err := v.getConfigFile()
if err != nil {
v.logger.Error(fmt.Sprintf("get config file: %s", err))
initWG.Done()
return
}
configFile := filepath.Clean(filename)
configDir, _ := filepath.Split(configFile)
realConfigFile, _ := filepath.EvalSymlinks(filename)
eventsWG := sync.WaitGroup{}
eventsWG.Add(1)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok { // 'Events' channel is closed
eventsWG.Done()
return
}
currentConfigFile, _ := filepath.EvalSymlinks(filename)
// we only care about the config file with the following cases:
// 1 - if the config file was modified or created
// 2 - if the real path to the config file changed (eg: k8s ConfigMap replacement)
if (filepath.Clean(event.Name) == configFile &&
(event.Has(fsnotify.Write) || event.Has(fsnotify.Create))) ||
(currentConfigFile != "" && currentConfigFile != realConfigFile) {
realConfigFile = currentConfigFile
err := v.ReadInConfig()
if err != nil {
v.logger.Error(fmt.Sprintf("read config file: %s", err))
}
if v.onConfigChange != nil {
v.onConfigChange(event)
}
} else if filepath.Clean(event.Name) == configFile && event.Has(fsnotify.Remove) {
eventsWG.Done()
return
}
case err, ok := <-watcher.Errors:
if ok { // 'Errors' channel is not closed
v.logger.Error(fmt.Sprintf("watcher error: %s", err))
}
eventsWG.Done()
return
}
}
}()
watcher.Add(configDir)
initWG.Done() // done initializing the watch in this go routine, so the parent routine can move on...
eventsWG.Wait() // now, wait for event loop to end in this go-routine...
}()
initWG.Wait() // make sure that the go routine above fully ended before returning
}
// SetConfigFile explicitly defines the path, name and extension of the config file.
// Viper will use this and not check any of the config paths.
func SetConfigFile(in string) { v.SetConfigFile(in) }
func (v *Viper) SetConfigFile(in string) {
if in != "" {
v.configFile = in
}
}
// SetEnvPrefix defines a prefix that ENVIRONMENT variables will use.
// E.g. if your prefix is "spf", the env registry will look for env
// variables that start with "SPF_".
func SetEnvPrefix(in string) { v.SetEnvPrefix(in) }
func (v *Viper) SetEnvPrefix(in string) {
if in != "" {
v.envPrefix = in
}
}
func GetEnvPrefix() string { return v.GetEnvPrefix() }
func (v *Viper) GetEnvPrefix() string {
return v.envPrefix
}
func (v *Viper) mergeWithEnvPrefix(in string) string {
if v.envPrefix != "" {
return strings.ToUpper(v.envPrefix + "_" + in)
}
return strings.ToUpper(in)
}
// AllowEmptyEnv tells Viper to consider set,
// but empty environment variables as valid values instead of falling back.
// For backward compatibility reasons this is false by default.
func AllowEmptyEnv(allowEmptyEnv bool) { v.AllowEmptyEnv(allowEmptyEnv) }
func (v *Viper) AllowEmptyEnv(allowEmptyEnv bool) {
v.allowEmptyEnv = allowEmptyEnv
}
// TODO: should getEnv logic be moved into find(). Can generalize the use of
// rewriting keys many things, Ex: Get('someKey') -> some_key
// (camel case to snake case for JSON keys perhaps)
// getEnv is a wrapper around os.Getenv which replaces characters in the original
// key. This allows env vars which have different keys than the config object
// keys.
func (v *Viper) getEnv(key string) (string, bool) {
if v.envKeyReplacer != nil {
key = v.envKeyReplacer.Replace(key)
}
val, ok := os.LookupEnv(key)
return val, ok && (v.allowEmptyEnv || val != "")
}
// ConfigFileUsed returns the file used to populate the config registry.
func ConfigFileUsed() string { return v.ConfigFileUsed() }
func (v *Viper) ConfigFileUsed() string { return v.configFile }
// AddConfigPath adds a path for Viper to search for the config file in.
// Can be called multiple times to define multiple search paths.
func AddConfigPath(in string) { v.AddConfigPath(in) }
func (v *Viper) AddConfigPath(in string) {
if in != "" {
absin := absPathify(v.logger, in)
v.logger.Info("adding path to search paths", "path", absin)
if !stringInSlice(absin, v.configPaths) {
v.configPaths = append(v.configPaths, absin)
}
}
}
// AddRemoteProvider adds a remote configuration source.
// Remote Providers are searched in the order they are added.
// provider is a string value: "etcd", "etcd3", "consul", "firestore" or "nats" are currently supported.
// endpoint is the url. etcd requires path_to_url consul requires ip:port, nats requires nats://ip:port
// path is the path in the k/v store to retrieve configuration
// To retrieve a config file called myapp.json from /configs/myapp.json
// you should set path to /configs and set config name (SetConfigName()) to
// "myapp".
func AddRemoteProvider(provider, endpoint, path string) error {
return v.AddRemoteProvider(provider, endpoint, path)
}
func (v *Viper) AddRemoteProvider(provider, endpoint, path string) error {
if !stringInSlice(provider, SupportedRemoteProviders) {
return UnsupportedRemoteProviderError(provider)
}
if provider != "" && endpoint != "" {
v.logger.Info("adding remote provider", "provider", provider, "endpoint", endpoint)
rp := &defaultRemoteProvider{
endpoint: endpoint,
provider: provider,
path: path,
}
if !v.providerPathExists(rp) {
v.remoteProviders = append(v.remoteProviders, rp)
}
}
return nil
}
// AddSecureRemoteProvider adds a remote configuration source.
// Secure Remote Providers are searched in the order they are added.
// provider is a string value: "etcd", "etcd3", "consul", "firestore" or "nats" are currently supported.
// endpoint is the url. etcd requires path_to_url consul requires ip:port
// secretkeyring is the filepath to your openpgp secret keyring. e.g. /etc/secrets/myring.gpg
// path is the path in the k/v store to retrieve configuration
// To retrieve a config file called myapp.json from /configs/myapp.json
// you should set path to /configs and set config name (SetConfigName()) to
// "myapp".
// Secure Remote Providers are implemented with github.com/sagikazarmark/crypt.
func AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error {
return v.AddSecureRemoteProvider(provider, endpoint, path, secretkeyring)
}
func (v *Viper) AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error {
if !stringInSlice(provider, SupportedRemoteProviders) {
return UnsupportedRemoteProviderError(provider)
}
if provider != "" && endpoint != "" {
v.logger.Info("adding remote provider", "provider", provider, "endpoint", endpoint)
rp := &defaultRemoteProvider{
endpoint: endpoint,
provider: provider,
path: path,
secretKeyring: secretkeyring,
}
if !v.providerPathExists(rp) {
v.remoteProviders = append(v.remoteProviders, rp)
}
}
return nil
}
func (v *Viper) providerPathExists(p *defaultRemoteProvider) bool {
for _, y := range v.remoteProviders {
if reflect.DeepEqual(y, p) {
return true
}
}
return false
}
// searchMap recursively searches for a value for path in source map.
// Returns nil if not found.
// Note: This assumes that the path entries and map keys are lower cased.
func (v *Viper) searchMap(source map[string]any, path []string) any {
if len(path) == 0 {
return source
}
next, ok := source[path[0]]
if ok {
// Fast path
if len(path) == 1 {
return next
}
// Nested case
switch next := next.(type) {
case map[any]any:
return v.searchMap(cast.ToStringMap(next), path[1:])
case map[string]any:
// Type assertion is safe here since it is only reached
// if the type of `next` is the same as the type being asserted
return v.searchMap(next, path[1:])
default:
// got a value but nested key expected, return "nil" for not found
return nil
}
}
return nil
}
// searchIndexableWithPathPrefixes recursively searches for a value for path in source map/slice.
//
// While searchMap() considers each path element as a single map key or slice index, this
// function searches for, and prioritizes, merged path elements.
// e.g., if in the source, "foo" is defined with a sub-key "bar", and "foo.bar"
// is also defined, this latter value is returned for path ["foo", "bar"].
//
// This should be useful only at config level (other maps may not contain dots
// in their keys).
//
// Note: This assumes that the path entries and map keys are lower cased.
func (v *Viper) searchIndexableWithPathPrefixes(source any, path []string) any {
if len(path) == 0 {
return source
}
// search for path prefixes, starting from the longest one
for i := len(path); i > 0; i-- {
prefixKey := strings.ToLower(strings.Join(path[0:i], v.keyDelim))
var val any
switch sourceIndexable := source.(type) {
case []any:
val = v.searchSliceWithPathPrefixes(sourceIndexable, prefixKey, i, path)
case map[string]any:
val = v.searchMapWithPathPrefixes(sourceIndexable, prefixKey, i, path)
}
if val != nil {
return val
}
}
// not found
return nil
}
// searchSliceWithPathPrefixes searches for a value for path in sourceSlice
//
// This function is part of the searchIndexableWithPathPrefixes recurring search and
// should not be called directly from functions other than searchIndexableWithPathPrefixes.
func (v *Viper) searchSliceWithPathPrefixes(
sourceSlice []any,
prefixKey string,
pathIndex int,
path []string,
) any {
// if the prefixKey is not a number or it is out of bounds of the slice
index, err := strconv.Atoi(prefixKey)
if err != nil || len(sourceSlice) <= index {
return nil
}
next := sourceSlice[index]
// Fast path
if pathIndex == len(path) {
return next
}
switch n := next.(type) {
case map[any]any:
return v.searchIndexableWithPathPrefixes(cast.ToStringMap(n), path[pathIndex:])
case map[string]any, []any:
return v.searchIndexableWithPathPrefixes(n, path[pathIndex:])
default:
// got a value but nested key expected, do nothing and look for next prefix
}
// not found
return nil
}
// searchMapWithPathPrefixes searches for a value for path in sourceMap
//
// This function is part of the searchIndexableWithPathPrefixes recurring search and
// should not be called directly from functions other than searchIndexableWithPathPrefixes.
func (v *Viper) searchMapWithPathPrefixes(
sourceMap map[string]any,
prefixKey string,
pathIndex int,
path []string,
) any {
next, ok := sourceMap[prefixKey]
if !ok {
return nil
}
// Fast path
if pathIndex == len(path) {
return next
}
// Nested case
switch n := next.(type) {
case map[any]any:
return v.searchIndexableWithPathPrefixes(cast.ToStringMap(n), path[pathIndex:])
case map[string]any, []any:
return v.searchIndexableWithPathPrefixes(n, path[pathIndex:])
default:
// got a value but nested key expected, do nothing and look for next prefix
}
// not found
return nil
}
// isPathShadowedInDeepMap makes sure the given path is not shadowed somewhere
// on its path in the map.
// e.g., if "foo.bar" has a value in the given map, it shadows
//
// "foo.bar.baz" in a lower-priority map
func (v *Viper) isPathShadowedInDeepMap(path []string, m map[string]any) string {
var parentVal any
for i := 1; i < len(path); i++ {
parentVal = v.searchMap(m, path[0:i])
if parentVal == nil {
// not found, no need to add more path elements
return ""
}
switch parentVal.(type) {
case map[any]any:
continue
case map[string]any:
continue
default:
// parentVal is a regular value which shadows "path"
return strings.Join(path[0:i], v.keyDelim)
}
}
return ""
}
// isPathShadowedInFlatMap makes sure the given path is not shadowed somewhere
// in a sub-path of the map.
// e.g., if "foo.bar" has a value in the given map, it shadows
//
// "foo.bar.baz" in a lower-priority map
func (v *Viper) isPathShadowedInFlatMap(path []string, mi any) string {
// unify input map
var m map[string]interface{}
switch miv := mi.(type) {
case map[string]string:
m = castMapStringToMapInterface(miv)
case map[string]FlagValue:
m = castMapFlagToMapInterface(miv)
default:
return ""
}
// scan paths
var parentKey string
for i := 1; i < len(path); i++ {
parentKey = strings.Join(path[0:i], v.keyDelim)
if _, ok := m[parentKey]; ok {
return parentKey
}
}
return ""
}
// isPathShadowedInAutoEnv makes sure the given path is not shadowed somewhere
// in the environment, when automatic env is on.
// e.g., if "foo.bar" has a value in the environment, it shadows
//
// "foo.bar.baz" in a lower-priority map
func (v *Viper) isPathShadowedInAutoEnv(path []string) string {
var parentKey string
for i := 1; i < len(path); i++ {
parentKey = strings.Join(path[0:i], v.keyDelim)
if _, ok := v.getEnv(v.mergeWithEnvPrefix(parentKey)); ok {
return parentKey
}
}
return ""
}
// SetTypeByDefaultValue enables or disables the inference of a key value's
// type when the Get function is used based upon a key's default value as
// opposed to the value returned based on the normal fetch logic.
//
// For example, if a key has a default value of []string{} and the same key
// is set via an environment variable to "a b c", a call to the Get function
// would return a string slice for the key if the key's type is inferred by
// the default value and the Get function would return:
//
// []string {"a", "b", "c"}
//
// Otherwise the Get function would return:
//
// "a b c"
func SetTypeByDefaultValue(enable bool) { v.SetTypeByDefaultValue(enable) }
func (v *Viper) SetTypeByDefaultValue(enable bool) {
v.typeByDefValue = enable
}
// GetViper gets the global Viper instance.
func GetViper() *Viper {
return v
}
// Get can retrieve any value given the key to use.
// Get is case-insensitive for a key.
// Get has the behavior of returning the value associated with the first
// place from where it is set. Viper will check in the following order:
// override, flag, env, config file, key/value store, default
//
// Get returns an interface. For a specific value use one of the Get____ methods.
func Get(key string) any { return v.Get(key) }
func (v *Viper) Get(key string) any {
lcaseKey := strings.ToLower(key)
val := v.find(lcaseKey, true)
if val == nil {
return nil
}
if v.typeByDefValue {
// TODO(bep) this branch isn't covered by a single test.
valType := val
path := strings.Split(lcaseKey, v.keyDelim)
defVal := v.searchMap(v.defaults, path)
if defVal != nil {
valType = defVal
}
switch valType.(type) {
case bool:
return cast.ToBool(val)
case string:
return cast.ToString(val)
case int32, int16, int8, int:
return cast.ToInt(val)
case uint:
return cast.ToUint(val)
case uint32:
return cast.ToUint32(val)
case uint64:
return cast.ToUint64(val)
case int64:
return cast.ToInt64(val)
case float64, float32:
return cast.ToFloat64(val)
case time.Time:
return cast.ToTime(val)
case time.Duration:
return cast.ToDuration(val)
case []string:
return cast.ToStringSlice(val)
case []int:
return cast.ToIntSlice(val)
case []time.Duration:
return cast.ToDurationSlice(val)
}
}
return val
}
// Sub returns new Viper instance representing a sub tree of this instance.
// Sub is case-insensitive for a key.
func Sub(key string) *Viper { return v.Sub(key) }
func (v *Viper) Sub(key string) *Viper {
subv := New()
data := v.Get(key)
if data == nil {
return nil
}
if reflect.TypeOf(data).Kind() == reflect.Map {
subv.parents = append([]string(nil), v.parents...)
subv.parents = append(subv.parents, strings.ToLower(key))
subv.automaticEnvApplied = v.automaticEnvApplied
subv.envPrefix = v.envPrefix
subv.envKeyReplacer = v.envKeyReplacer
subv.config = cast.ToStringMap(data)
return subv
}
return nil
}
// GetString returns the value associated with the key as a string.
func GetString(key string) string { return v.GetString(key) }
func (v *Viper) GetString(key string) string {
return cast.ToString(v.Get(key))
}
// GetBool returns the value associated with the key as a boolean.
func GetBool(key string) bool { return v.GetBool(key) }
func (v *Viper) GetBool(key string) bool {
return cast.ToBool(v.Get(key))
}
// GetInt returns the value associated with the key as an integer.
func GetInt(key string) int { return v.GetInt(key) }
func (v *Viper) GetInt(key string) int {
return cast.ToInt(v.Get(key))
}
// GetInt32 returns the value associated with the key as an integer.
func GetInt32(key string) int32 { return v.GetInt32(key) }
func (v *Viper) GetInt32(key string) int32 {
return cast.ToInt32(v.Get(key))
}
// GetInt64 returns the value associated with the key as an integer.
func GetInt64(key string) int64 { return v.GetInt64(key) }
func (v *Viper) GetInt64(key string) int64 {
return cast.ToInt64(v.Get(key))
}
// GetUint returns the value associated with the key as an unsigned integer.
func GetUint(key string) uint { return v.GetUint(key) }
func (v *Viper) GetUint(key string) uint {
return cast.ToUint(v.Get(key))
}
// GetUint16 returns the value associated with the key as an unsigned integer.
func GetUint16(key string) uint16 { return v.GetUint16(key) }
func (v *Viper) GetUint16(key string) uint16 {
return cast.ToUint16(v.Get(key))
}
// GetUint32 returns the value associated with the key as an unsigned integer.
func GetUint32(key string) uint32 { return v.GetUint32(key) }
func (v *Viper) GetUint32(key string) uint32 {
return cast.ToUint32(v.Get(key))
}
// GetUint64 returns the value associated with the key as an unsigned integer.
func GetUint64(key string) uint64 { return v.GetUint64(key) }
func (v *Viper) GetUint64(key string) uint64 {
return cast.ToUint64(v.Get(key))
}
// GetFloat64 returns the value associated with the key as a float64.
func GetFloat64(key string) float64 { return v.GetFloat64(key) }
func (v *Viper) GetFloat64(key string) float64 {
return cast.ToFloat64(v.Get(key))
}
// GetTime returns the value associated with the key as time.
func GetTime(key string) time.Time { return v.GetTime(key) }
func (v *Viper) GetTime(key string) time.Time {
return cast.ToTime(v.Get(key))
}
// GetDuration returns the value associated with the key as a duration.
func GetDuration(key string) time.Duration { return v.GetDuration(key) }
func (v *Viper) GetDuration(key string) time.Duration {
return cast.ToDuration(v.Get(key))
}
// GetIntSlice returns the value associated with the key as a slice of int values.
func GetIntSlice(key string) []int { return v.GetIntSlice(key) }
func (v *Viper) GetIntSlice(key string) []int {
return cast.ToIntSlice(v.Get(key))
}
// GetStringSlice returns the value associated with the key as a slice of strings.
func GetStringSlice(key string) []string { return v.GetStringSlice(key) }
func (v *Viper) GetStringSlice(key string) []string {
return cast.ToStringSlice(v.Get(key))
}
// GetStringMap returns the value associated with the key as a map of interfaces.
func GetStringMap(key string) map[string]any { return v.GetStringMap(key) }
func (v *Viper) GetStringMap(key string) map[string]any {
return cast.ToStringMap(v.Get(key))
}
// GetStringMapString returns the value associated with the key as a map of strings.
func GetStringMapString(key string) map[string]string { return v.GetStringMapString(key) }
func (v *Viper) GetStringMapString(key string) map[string]string {
return cast.ToStringMapString(v.Get(key))
}
// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
func GetStringMapStringSlice(key string) map[string][]string { return v.GetStringMapStringSlice(key) }
func (v *Viper) GetStringMapStringSlice(key string) map[string][]string {
return cast.ToStringMapStringSlice(v.Get(key))
}
// GetSizeInBytes returns the size of the value associated with the given key
// in bytes.
func GetSizeInBytes(key string) uint { return v.GetSizeInBytes(key) }
func (v *Viper) GetSizeInBytes(key string) uint {
sizeStr := cast.ToString(v.Get(key))
return parseSizeInBytes(sizeStr)
}
// UnmarshalKey takes a single key and unmarshals it into a Struct.
func UnmarshalKey(key string, rawVal any, opts ...DecoderConfigOption) error {
return v.UnmarshalKey(key, rawVal, opts...)
}
func (v *Viper) UnmarshalKey(key string, rawVal any, opts ...DecoderConfigOption) error {
return decode(v.Get(key), defaultDecoderConfig(rawVal, opts...))
}
// Unmarshal unmarshals the config into a Struct. Make sure that the tags
// on the fields of the structure are properly set.
func Unmarshal(rawVal any, opts ...DecoderConfigOption) error {
return v.Unmarshal(rawVal, opts...)
}
func (v *Viper) Unmarshal(rawVal any, opts ...DecoderConfigOption) error {
keys := v.AllKeys()
if features.BindStruct {
// TODO: make this optional?
structKeys, err := v.decodeStructKeys(rawVal, opts...)
if err != nil {
return err
}
keys = append(keys, structKeys...)
}
// TODO: struct keys should be enough?
return decode(v.getSettings(keys), defaultDecoderConfig(rawVal, opts...))
}
func (v *Viper) decodeStructKeys(input any, opts ...DecoderConfigOption) ([]string, error) {
var structKeyMap map[string]any
err := decode(input, defaultDecoderConfig(&structKeyMap, opts...))
if err != nil {
return nil, err
}
flattenedStructKeyMap := v.flattenAndMergeMap(map[string]bool{}, structKeyMap, "")
r := make([]string, 0, len(flattenedStructKeyMap))
for v := range flattenedStructKeyMap {
r = append(r, v)
}
return r, nil
}
// defaultDecoderConfig returns default mapstructure.DecoderConfig with support
// of time.Duration values & string slices.
func defaultDecoderConfig(output any, opts ...DecoderConfigOption) *mapstructure.DecoderConfig {
c := &mapstructure.DecoderConfig{
Metadata: nil,
Result: output,
WeaklyTypedInput: true,
DecodeHook: mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
),
}
for _, opt := range opts {
opt(c)
}
return c
}
// decode is a wrapper around mapstructure.Decode that mimics the WeakDecode functionality.
func decode(input any, config *mapstructure.DecoderConfig) error {
decoder, err := mapstructure.NewDecoder(config)
if err != nil {
return err
}
return decoder.Decode(input)
}
// UnmarshalExact unmarshals the config into a Struct, erroring if a field is nonexistent
// in the destination struct.
func UnmarshalExact(rawVal any, opts ...DecoderConfigOption) error {
return v.UnmarshalExact(rawVal, opts...)
}
func (v *Viper) UnmarshalExact(rawVal any, opts ...DecoderConfigOption) error {
config := defaultDecoderConfig(rawVal, opts...)
config.ErrorUnused = true
keys := v.AllKeys()
if features.BindStruct {
// TODO: make this optional?
structKeys, err := v.decodeStructKeys(rawVal, opts...)
if err != nil {
return err
}
keys = append(keys, structKeys...)
}
// TODO: struct keys should be enough?
return decode(v.getSettings(keys), config)
}
// BindPFlags binds a full flag set to the configuration, using each flag's long
// name as the config key.
func BindPFlags(flags *pflag.FlagSet) error { return v.BindPFlags(flags) }
func (v *Viper) BindPFlags(flags *pflag.FlagSet) error {
return v.BindFlagValues(pflagValueSet{flags})
}
// BindPFlag binds a specific key to a pflag (as used by cobra).
// Example (where serverCmd is a Cobra instance):
//
// serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
// Viper.BindPFlag("port", serverCmd.Flags().Lookup("port"))
func BindPFlag(key string, flag *pflag.Flag) error { return v.BindPFlag(key, flag) }
func (v *Viper) BindPFlag(key string, flag *pflag.Flag) error {
if flag == nil {
return fmt.Errorf("flag for %q is nil", key)
}
return v.BindFlagValue(key, pflagValue{flag})
}
// BindFlagValues binds a full FlagValue set to the configuration, using each flag's long
// name as the config key.
func BindFlagValues(flags FlagValueSet) error { return v.BindFlagValues(flags) }
func (v *Viper) BindFlagValues(flags FlagValueSet) (err error) {
flags.VisitAll(func(flag FlagValue) {
if err = v.BindFlagValue(flag.Name(), flag); err != nil {
return
}
})
return nil
}
// BindFlagValue binds a specific key to a FlagValue.
func BindFlagValue(key string, flag FlagValue) error { return v.BindFlagValue(key, flag) }
func (v *Viper) BindFlagValue(key string, flag FlagValue) error {
if flag == nil {
return fmt.Errorf("flag for %q is nil", key)
}
v.pflags[strings.ToLower(key)] = flag
return nil
}
// BindEnv binds a Viper key to a ENV variable.
// ENV variables are case sensitive.
// If only a key is provided, it will use the env key matching the key, uppercased.
// If more arguments are provided, they will represent the env variable names that
// should bind to this key and will be taken in the specified order.
// EnvPrefix will be used when set when env name is not provided.
func BindEnv(input ...string) error { return v.BindEnv(input...) }
func (v *Viper) BindEnv(input ...string) error {
if len(input) == 0 {
return fmt.Errorf("missing key to bind to")
}
key := strings.ToLower(input[0])
if len(input) == 1 {
v.env[key] = append(v.env[key], v.mergeWithEnvPrefix(key))
} else {
v.env[key] = append(v.env[key], input[1:]...)
}
return nil
}
// MustBindEnv wraps BindEnv in a panic.
// If there is an error binding an environment variable, MustBindEnv will
// panic.
func MustBindEnv(input ...string) { v.MustBindEnv(input...) }
func (v *Viper) MustBindEnv(input ...string) {
if err := v.BindEnv(input...); err != nil {
panic(fmt.Sprintf("error while binding environment variable: %v", err))
}
}
// Given a key, find the value.
//
// Viper will check to see if an alias exists first.
// Viper will then check in the following order:
// flag, env, config file, key/value store.
// Lastly, if no value was found and flagDefault is true, and if the key
// corresponds to a flag, the flag's default value is returned.
//
// Note: this assumes a lower-cased key given.
func (v *Viper) find(lcaseKey string, flagDefault bool) any {
var (
val any
exists bool
path = strings.Split(lcaseKey, v.keyDelim)
nested = len(path) > 1
)
// compute the path through the nested maps to the nested value
if nested && v.isPathShadowedInDeepMap(path, castMapStringToMapInterface(v.aliases)) != "" {
return nil
}
// if the requested key is an alias, then return the proper key
lcaseKey = v.realKey(lcaseKey)
path = strings.Split(lcaseKey, v.keyDelim)
nested = len(path) > 1
// Set() override first
val = v.searchMap(v.override, path)
if val != nil {
return val
}
if nested && v.isPathShadowedInDeepMap(path, v.override) != "" {
return nil
}
// PFlag override next
flag, exists := v.pflags[lcaseKey]
if exists && flag.HasChanged() {
switch flag.ValueType() {
case "int", "int8", "int16", "int32", "int64":
return cast.ToInt(flag.ValueString())
case "bool":
return cast.ToBool(flag.ValueString())
case "stringSlice", "stringArray":
s := strings.TrimPrefix(flag.ValueString(), "[")
s = strings.TrimSuffix(s, "]")
res, _ := readAsCSV(s)
return res
case "intSlice":
s := strings.TrimPrefix(flag.ValueString(), "[")
s = strings.TrimSuffix(s, "]")
res, _ := readAsCSV(s)
return cast.ToIntSlice(res)
case "durationSlice":
s := strings.TrimPrefix(flag.ValueString(), "[")
s = strings.TrimSuffix(s, "]")
slice := strings.Split(s, ",")
return cast.ToDurationSlice(slice)
case "stringToString":
return stringToStringConv(flag.ValueString())
case "stringToInt":
return stringToIntConv(flag.ValueString())
default:
return flag.ValueString()
}
}
if nested && v.isPathShadowedInFlatMap(path, v.pflags) != "" {
return nil
}
// Env override next
if v.automaticEnvApplied {
envKey := strings.Join(append(v.parents, lcaseKey), ".")
// even if it hasn't been registered, if automaticEnv is used,
// check any Get request
if val, ok := v.getEnv(v.mergeWithEnvPrefix(envKey)); ok {
return val
}
if nested && v.isPathShadowedInAutoEnv(path) != "" {
return nil
}
}
envkeys, exists := v.env[lcaseKey]
if exists {
for _, envkey := range envkeys {
if val, ok := v.getEnv(envkey); ok {
return val
}
}
}
if nested && v.isPathShadowedInFlatMap(path, v.env) != "" {
return nil
}
// Config file next
val = v.searchIndexableWithPathPrefixes(v.config, path)
if val != nil {
return val
}
if nested && v.isPathShadowedInDeepMap(path, v.config) != "" {
return nil
}
// K/V store next
val = v.searchMap(v.kvstore, path)
if val != nil {
return val
}
if nested && v.isPathShadowedInDeepMap(path, v.kvstore) != "" {
return nil
}
// Default next
val = v.searchMap(v.defaults, path)
if val != nil {
return val
}
if nested && v.isPathShadowedInDeepMap(path, v.defaults) != "" {
return nil
}
if flagDefault {
// last chance: if no value is found and a flag does exist for the key,
// get the flag's default value even if the flag's value has not been set.
if flag, exists := v.pflags[lcaseKey]; exists {
switch flag.ValueType() {
case "int", "int8", "int16", "int32", "int64":
return cast.ToInt(flag.ValueString())
case "bool":
return cast.ToBool(flag.ValueString())
case "stringSlice", "stringArray":
s := strings.TrimPrefix(flag.ValueString(), "[")
s = strings.TrimSuffix(s, "]")
res, _ := readAsCSV(s)
return res
case "intSlice":
s := strings.TrimPrefix(flag.ValueString(), "[")
s = strings.TrimSuffix(s, "]")
res, _ := readAsCSV(s)
return cast.ToIntSlice(res)
case "stringToString":
return stringToStringConv(flag.ValueString())
case "stringToInt":
return stringToIntConv(flag.ValueString())
case "durationSlice":
s := strings.TrimPrefix(flag.ValueString(), "[")
s = strings.TrimSuffix(s, "]")
slice := strings.Split(s, ",")
return cast.ToDurationSlice(slice)
default:
return flag.ValueString()
}
}
// last item, no need to check shadowing
}
return nil
}
func readAsCSV(val string) ([]string, error) {
if val == "" {
return []string{}, nil
}
stringReader := strings.NewReader(val)
csvReader := csv.NewReader(stringReader)
return csvReader.Read()
}
// mostly copied from pflag's implementation of this operation here path_to_url#L79
// alterations are: errors are swallowed, map[string]any is returned in order to enable cast.ToStringMap.
func stringToStringConv(val string) any {
val = strings.Trim(val, "[]")
// An empty string would cause an empty map
if val == "" {
return map[string]any{}
}
r := csv.NewReader(strings.NewReader(val))
ss, err := r.Read()
if err != nil {
return nil
}
out := make(map[string]any, len(ss))
for _, pair := range ss {
k, vv, found := strings.Cut(pair, "=")
if !found {
return nil
}
out[k] = vv
}
return out
}
// mostly copied from pflag's implementation of this operation here path_to_url#L68
// alterations are: errors are swallowed, map[string]any is returned in order to enable cast.ToStringMap.
func stringToIntConv(val string) any {
val = strings.Trim(val, "[]")
// An empty string would cause an empty map
if val == "" {
return map[string]any{}
}
ss := strings.Split(val, ",")
out := make(map[string]any, len(ss))
for _, pair := range ss {
k, vv, found := strings.Cut(pair, "=")
if !found {
return nil
}
var err error
out[k], err = strconv.Atoi(vv)
if err != nil {
return nil
}
}
return out
}
// IsSet checks to see if the key has been set in any of the data locations.
// IsSet is case-insensitive for a key.
func IsSet(key string) bool { return v.IsSet(key) }
func (v *Viper) IsSet(key string) bool {
lcaseKey := strings.ToLower(key)
val := v.find(lcaseKey, false)
return val != nil
}
// AutomaticEnv makes Viper check if environment variables match any of the existing keys
// (config, default or flags). If matching env vars are found, they are loaded into Viper.
func AutomaticEnv() { v.AutomaticEnv() }
func (v *Viper) AutomaticEnv() {
v.automaticEnvApplied = true
}
// SetEnvKeyReplacer sets the strings.Replacer on the viper object
// Useful for mapping an environmental variable to a key that does
// not match it.
func SetEnvKeyReplacer(r *strings.Replacer) { v.SetEnvKeyReplacer(r) }
func (v *Viper) SetEnvKeyReplacer(r *strings.Replacer) {
v.envKeyReplacer = r
}
// RegisterAlias creates an alias that provides another accessor for the same key.
// This enables one to change a name without breaking the application.
func RegisterAlias(alias, key string) { v.RegisterAlias(alias, key) }
func (v *Viper) RegisterAlias(alias, key string) {
v.registerAlias(alias, strings.ToLower(key))
}
func (v *Viper) registerAlias(alias, key string) {
alias = strings.ToLower(alias)
if alias != key && alias != v.realKey(key) {
_, exists := v.aliases[alias]
if !exists {
// if we alias something that exists in one of the maps to another
// name, we'll never be able to get that value using the original
// name, so move the config value to the new realkey.
if val, ok := v.config[alias]; ok {
delete(v.config, alias)
v.config[key] = val
}
if val, ok := v.kvstore[alias]; ok {
delete(v.kvstore, alias)
v.kvstore[key] = val
}
if val, ok := v.defaults[alias]; ok {
delete(v.defaults, alias)
v.defaults[key] = val
}
if val, ok := v.override[alias]; ok {
delete(v.override, alias)
v.override[key] = val
}
v.aliases[alias] = key
}
} else {
v.logger.Warn("creating circular reference alias", "alias", alias, "key", key, "real_key", v.realKey(key))
}
}
func (v *Viper) realKey(key string) string {
newkey, exists := v.aliases[key]
if exists {
v.logger.Debug("key is an alias", "alias", key, "to", newkey)
return v.realKey(newkey)
}
return key
}
// InConfig checks to see if the given key (or an alias) is in the config file.
func InConfig(key string) bool { return v.InConfig(key) }
func (v *Viper) InConfig(key string) bool {
lcaseKey := strings.ToLower(key)
// if the requested key is an alias, then return the proper key
lcaseKey = v.realKey(lcaseKey)
path := strings.Split(lcaseKey, v.keyDelim)
return v.searchIndexableWithPathPrefixes(v.config, path) != nil
}
// SetDefault sets the default value for this key.
// SetDefault is case-insensitive for a key.
// Default only used when no value is provided by the user via flag, config or ENV.
func SetDefault(key string, value any) { v.SetDefault(key, value) }
func (v *Viper) SetDefault(key string, value any) {
// If alias passed in, then set the proper default
key = v.realKey(strings.ToLower(key))
value = toCaseInsensitiveValue(value)
path := strings.Split(key, v.keyDelim)
lastKey := strings.ToLower(path[len(path)-1])
deepestMap := deepSearch(v.defaults, path[0:len(path)-1])
// set innermost value
deepestMap[lastKey] = value
}
// Set sets the value for the key in the override register.
// Set is case-insensitive for a key.
// Will be used instead of values obtained via
// flags, config file, ENV, default, or key/value store.
func Set(key string, value any) { v.Set(key, value) }
func (v *Viper) Set(key string, value any) {
// If alias passed in, then set the proper override
key = v.realKey(strings.ToLower(key))
value = toCaseInsensitiveValue(value)
path := strings.Split(key, v.keyDelim)
lastKey := strings.ToLower(path[len(path)-1])
deepestMap := deepSearch(v.override, path[0:len(path)-1])
// set innermost value
deepestMap[lastKey] = value
}
// ReadInConfig will discover and load the configuration file from disk
// and key/value stores, searching in one of the defined paths.
func ReadInConfig() error { return v.ReadInConfig() }
func (v *Viper) ReadInConfig() error {
v.logger.Info("attempting to read in config file")
filename, err := v.getConfigFile()
if err != nil {
return err
}
if !stringInSlice(v.getConfigType(), SupportedExts) {
return UnsupportedConfigError(v.getConfigType())
}
v.logger.Debug("reading file", "file", filename)
file, err := afero.ReadFile(v.fs, filename)
if err != nil {
return err
}
config := make(map[string]any)
err = v.unmarshalReader(bytes.NewReader(file), config)
if err != nil {
return err
}
v.config = config
return nil
}
// MergeInConfig merges a new configuration with an existing config.
func MergeInConfig() error { return v.MergeInConfig() }
func (v *Viper) MergeInConfig() error {
v.logger.Info("attempting to merge in config file")
filename, err := v.getConfigFile()
if err != nil {
return err
}
if !stringInSlice(v.getConfigType(), SupportedExts) {
return UnsupportedConfigError(v.getConfigType())
}
file, err := afero.ReadFile(v.fs, filename)
if err != nil {
return err
}
return v.MergeConfig(bytes.NewReader(file))
}
// ReadConfig will read a configuration file, setting existing keys to nil if the
// key does not exist in the file.
func ReadConfig(in io.Reader) error { return v.ReadConfig(in) }
func (v *Viper) ReadConfig(in io.Reader) error {
v.config = make(map[string]any)
return v.unmarshalReader(in, v.config)
}
// MergeConfig merges a new configuration with an existing config.
func MergeConfig(in io.Reader) error { return v.MergeConfig(in) }
func (v *Viper) MergeConfig(in io.Reader) error {
cfg := make(map[string]any)
if err := v.unmarshalReader(in, cfg); err != nil {
return err
}
return v.MergeConfigMap(cfg)
}
// MergeConfigMap merges the configuration from the map given with an existing config.
// Note that the map given may be modified.
func MergeConfigMap(cfg map[string]any) error { return v.MergeConfigMap(cfg) }
func (v *Viper) MergeConfigMap(cfg map[string]any) error {
if v.config == nil {
v.config = make(map[string]any)
}
insensitiviseMap(cfg)
mergeMaps(cfg, v.config, nil)
return nil
}
// WriteConfig writes the current configuration to a file.
func WriteConfig() error { return v.WriteConfig() }
func (v *Viper) WriteConfig() error {
filename, err := v.getConfigFile()
if err != nil {
return err
}
return v.writeConfig(filename, true)
}
// SafeWriteConfig writes current configuration to file only if the file does not exist.
func SafeWriteConfig() error { return v.SafeWriteConfig() }
func (v *Viper) SafeWriteConfig() error {
if len(v.configPaths) < 1 {
return errors.New("missing configuration for 'configPath'")
}
return v.SafeWriteConfigAs(filepath.Join(v.configPaths[0], v.configName+"."+v.configType))
}
// WriteConfigAs writes current configuration to a given filename.
func WriteConfigAs(filename string) error { return v.WriteConfigAs(filename) }
func (v *Viper) WriteConfigAs(filename string) error {
return v.writeConfig(filename, true)
}
// SafeWriteConfigAs writes current configuration to a given filename if it does not exist.
func SafeWriteConfigAs(filename string) error { return v.SafeWriteConfigAs(filename) }
func (v *Viper) SafeWriteConfigAs(filename string) error {
alreadyExists, err := afero.Exists(v.fs, filename)
if alreadyExists && err == nil {
return ConfigFileAlreadyExistsError(filename)
}
return v.writeConfig(filename, false)
}
func (v *Viper) writeConfig(filename string, force bool) error {
v.logger.Info("attempting to write configuration to file")
var configType string
ext := filepath.Ext(filename)
if ext != "" && ext != filepath.Base(filename) {
configType = ext[1:]
} else {
configType = v.configType
}
if configType == "" {
return fmt.Errorf("config type could not be determined for %s", filename)
}
if !stringInSlice(configType, SupportedExts) {
return UnsupportedConfigError(configType)
}
if v.config == nil {
v.config = make(map[string]any)
}
flags := os.O_CREATE | os.O_TRUNC | os.O_WRONLY
if !force {
flags |= os.O_EXCL
}
f, err := v.fs.OpenFile(filename, flags, v.configPermissions)
if err != nil {
return err
}
defer f.Close()
if err := v.marshalWriter(f, configType); err != nil {
return err
}
return f.Sync()
}
func (v *Viper) unmarshalReader(in io.Reader, c map[string]any) error {
buf := new(bytes.Buffer)
buf.ReadFrom(in)
switch format := strings.ToLower(v.getConfigType()); format {
case "yaml", "yml", "json", "toml", "hcl", "tfvars", "ini", "properties", "props", "prop", "dotenv", "env":
err := v.decoderRegistry.Decode(format, buf.Bytes(), c)
if err != nil {
return ConfigParseError{err}
}
}
insensitiviseMap(c)
return nil
}
// Marshal a map into Writer.
func (v *Viper) marshalWriter(f afero.File, configType string) error {
c := v.AllSettings()
switch configType {
case "yaml", "yml", "json", "toml", "hcl", "tfvars", "ini", "prop", "props", "properties", "dotenv", "env":
b, err := v.encoderRegistry.Encode(configType, c)
if err != nil {
return ConfigMarshalError{err}
}
_, err = f.WriteString(string(b))
if err != nil {
return ConfigMarshalError{err}
}
}
return nil
}
func keyExists(k string, m map[string]any) string {
lk := strings.ToLower(k)
for mk := range m {
lmk := strings.ToLower(mk)
if lmk == lk {
return mk
}
}
return ""
}
func castToMapStringInterface(
src map[any]any,
) map[string]any {
tgt := map[string]any{}
for k, v := range src {
tgt[fmt.Sprintf("%v", k)] = v
}
return tgt
}
func castMapStringSliceToMapInterface(src map[string][]string) map[string]any {
tgt := map[string]any{}
for k, v := range src {
tgt[k] = v
}
return tgt
}
func castMapStringToMapInterface(src map[string]string) map[string]any {
tgt := map[string]any{}
for k, v := range src {
tgt[k] = v
}
return tgt
}
func castMapFlagToMapInterface(src map[string]FlagValue) map[string]any {
tgt := map[string]any{}
for k, v := range src {
tgt[k] = v
}
return tgt
}
// mergeMaps merges two maps. The `itgt` parameter is for handling go-yaml's
// insistence on parsing nested structures as `map[any]any`
// instead of using a `string` as the key for nest structures beyond one level
// deep. Both map types are supported as there is a go-yaml fork that uses
// `map[string]any` instead.
func mergeMaps(src, tgt map[string]any, itgt map[any]any) {
for sk, sv := range src {
tk := keyExists(sk, tgt)
if tk == "" {
v.logger.Debug("", "tk", "\"\"", fmt.Sprintf("tgt[%s]", sk), sv)
tgt[sk] = sv
if itgt != nil {
itgt[sk] = sv
}
continue
}
tv, ok := tgt[tk]
if !ok {
v.logger.Debug("", fmt.Sprintf("ok[%s]", tk), false, fmt.Sprintf("tgt[%s]", sk), sv)
tgt[sk] = sv
if itgt != nil {
itgt[sk] = sv
}
continue
}
svType := reflect.TypeOf(sv)
tvType := reflect.TypeOf(tv)
v.logger.Debug(
"processing",
"key", sk,
"st", svType,
"tt", tvType,
"sv", sv,
"tv", tv,
)
switch ttv := tv.(type) {
case map[any]any:
v.logger.Debug("merging maps (must convert)")
tsv, ok := sv.(map[any]any)
if !ok {
v.logger.Error(
"Could not cast sv to map[any]any",
"key", sk,
"st", svType,
"tt", tvType,
"sv", sv,
"tv", tv,
)
continue
}
ssv := castToMapStringInterface(tsv)
stv := castToMapStringInterface(ttv)
mergeMaps(ssv, stv, ttv)
case map[string]any:
v.logger.Debug("merging maps")
tsv, ok := sv.(map[string]any)
if !ok {
v.logger.Error(
"Could not cast sv to map[string]any",
"key", sk,
"st", svType,
"tt", tvType,
"sv", sv,
"tv", tv,
)
continue
}
mergeMaps(tsv, ttv, nil)
default:
v.logger.Debug("setting value")
tgt[tk] = sv
if itgt != nil {
itgt[tk] = sv
}
}
}
}
// ReadRemoteConfig attempts to get configuration from a remote source
// and read it in the remote configuration registry.
func ReadRemoteConfig() error { return v.ReadRemoteConfig() }
func (v *Viper) ReadRemoteConfig() error {
return v.getKeyValueConfig()
}
func WatchRemoteConfig() error { return v.WatchRemoteConfig() }
func (v *Viper) WatchRemoteConfig() error {
return v.watchKeyValueConfig()
}
func (v *Viper) WatchRemoteConfigOnChannel() error {
return v.watchKeyValueConfigOnChannel()
}
// Retrieve the first found remote configuration.
func (v *Viper) getKeyValueConfig() error {
if RemoteConfig == nil {
return RemoteConfigError("Enable the remote features by doing a blank import of the viper/remote package: '_ github.com/spf13/viper/remote'")
}
if len(v.remoteProviders) == 0 {
return RemoteConfigError("No Remote Providers")
}
for _, rp := range v.remoteProviders {
val, err := v.getRemoteConfig(rp)
if err != nil {
v.logger.Error(fmt.Errorf("get remote config: %w", err).Error())
continue
}
v.kvstore = val
return nil
}
return RemoteConfigError("No Files Found")
}
func (v *Viper) getRemoteConfig(provider RemoteProvider) (map[string]any, error) {
reader, err := RemoteConfig.Get(provider)
if err != nil {
return nil, err
}
err = v.unmarshalReader(reader, v.kvstore)
return v.kvstore, err
}
// Retrieve the first found remote configuration.
func (v *Viper) watchKeyValueConfigOnChannel() error {
if len(v.remoteProviders) == 0 {
return RemoteConfigError("No Remote Providers")
}
for _, rp := range v.remoteProviders {
respc, _ := RemoteConfig.WatchChannel(rp)
// Todo: Add quit channel
go func(rc <-chan *RemoteResponse) {
for {
b := <-rc
reader := bytes.NewReader(b.Value)
v.unmarshalReader(reader, v.kvstore)
}
}(respc)
return nil
}
return RemoteConfigError("No Files Found")
}
// Retrieve the first found remote configuration.
func (v *Viper) watchKeyValueConfig() error {
if len(v.remoteProviders) == 0 {
return RemoteConfigError("No Remote Providers")
}
for _, rp := range v.remoteProviders {
val, err := v.watchRemoteConfig(rp)
if err != nil {
v.logger.Error(fmt.Errorf("watch remote config: %w", err).Error())
continue
}
v.kvstore = val
return nil
}
return RemoteConfigError("No Files Found")
}
func (v *Viper) watchRemoteConfig(provider RemoteProvider) (map[string]any, error) {
reader, err := RemoteConfig.Watch(provider)
if err != nil {
return nil, err
}
err = v.unmarshalReader(reader, v.kvstore)
return v.kvstore, err
}
// AllKeys returns all keys holding a value, regardless of where they are set.
// Nested keys are returned with a v.keyDelim separator.
func AllKeys() []string { return v.AllKeys() }
func (v *Viper) AllKeys() []string {
m := map[string]bool{}
// add all paths, by order of descending priority to ensure correct shadowing
m = v.flattenAndMergeMap(m, castMapStringToMapInterface(v.aliases), "")
m = v.flattenAndMergeMap(m, v.override, "")
m = v.mergeFlatMap(m, castMapFlagToMapInterface(v.pflags))
m = v.mergeFlatMap(m, castMapStringSliceToMapInterface(v.env))
m = v.flattenAndMergeMap(m, v.config, "")
m = v.flattenAndMergeMap(m, v.kvstore, "")
m = v.flattenAndMergeMap(m, v.defaults, "")
// convert set of paths to list
a := make([]string, 0, len(m))
for x := range m {
a = append(a, x)
}
return a
}
// flattenAndMergeMap recursively flattens the given map into a map[string]bool
// of key paths (used as a set, easier to manipulate than a []string):
// - each path is merged into a single key string, delimited with v.keyDelim
// - if a path is shadowed by an earlier value in the initial shadow map,
// it is skipped.
//
// The resulting set of paths is merged to the given shadow set at the same time.
func (v *Viper) flattenAndMergeMap(shadow map[string]bool, m map[string]any, prefix string) map[string]bool {
if shadow != nil && prefix != "" && shadow[prefix] {
// prefix is shadowed => nothing more to flatten
return shadow
}
if shadow == nil {
shadow = make(map[string]bool)
}
var m2 map[string]any
if prefix != "" {
prefix += v.keyDelim
}
for k, val := range m {
fullKey := prefix + k
switch val := val.(type) {
case map[string]any:
m2 = val
case map[any]any:
m2 = cast.ToStringMap(val)
default:
// immediate value
shadow[strings.ToLower(fullKey)] = true
continue
}
// recursively merge to shadow map
shadow = v.flattenAndMergeMap(shadow, m2, fullKey)
}
return shadow
}
// mergeFlatMap merges the given maps, excluding values of the second map
// shadowed by values from the first map.
func (v *Viper) mergeFlatMap(shadow map[string]bool, m map[string]any) map[string]bool {
// scan keys
outer:
for k := range m {
path := strings.Split(k, v.keyDelim)
// scan intermediate paths
var parentKey string
for i := 1; i < len(path); i++ {
parentKey = strings.Join(path[0:i], v.keyDelim)
if shadow[parentKey] {
// path is shadowed, continue
continue outer
}
}
// add key
shadow[strings.ToLower(k)] = true
}
return shadow
}
// AllSettings merges all settings and returns them as a map[string]any.
func AllSettings() map[string]any { return v.AllSettings() }
func (v *Viper) AllSettings() map[string]any {
return v.getSettings(v.AllKeys())
}
func (v *Viper) getSettings(keys []string) map[string]any {
m := map[string]any{}
// start from the list of keys, and construct the map one value at a time
for _, k := range keys {
value := v.Get(k)
if value == nil {
// should not happen, since AllKeys() returns only keys holding a value,
// check just in case anything changes
continue
}
path := strings.Split(k, v.keyDelim)
lastKey := strings.ToLower(path[len(path)-1])
deepestMap := deepSearch(m, path[0:len(path)-1])
// set innermost value
deepestMap[lastKey] = value
}
return m
}
// SetFs sets the filesystem to use to read configuration.
func SetFs(fs afero.Fs) { v.SetFs(fs) }
func (v *Viper) SetFs(fs afero.Fs) {
v.fs = fs
}
// SetConfigName sets name for the config file.
// Does not include extension.
func SetConfigName(in string) { v.SetConfigName(in) }
func (v *Viper) SetConfigName(in string) {
if in != "" {
v.configName = in
v.configFile = ""
}
}
// SetConfigType sets the type of the configuration returned by the
// remote source, e.g. "json".
func SetConfigType(in string) { v.SetConfigType(in) }
func (v *Viper) SetConfigType(in string) {
if in != "" {
v.configType = in
}
}
// SetConfigPermissions sets the permissions for the config file.
func SetConfigPermissions(perm os.FileMode) { v.SetConfigPermissions(perm) }
func (v *Viper) SetConfigPermissions(perm os.FileMode) {
v.configPermissions = perm.Perm()
}
// IniLoadOptions sets the load options for ini parsing.
func IniLoadOptions(in ini.LoadOptions) Option {
return optionFunc(func(v *Viper) {
v.iniLoadOptions = in
})
}
func (v *Viper) getConfigType() string {
if v.configType != "" {
return v.configType
}
cf, err := v.getConfigFile()
if err != nil {
return ""
}
ext := filepath.Ext(cf)
if len(ext) > 1 {
return ext[1:]
}
return ""
}
func (v *Viper) getConfigFile() (string, error) {
if v.configFile == "" {
cf, err := v.findConfigFile()
if err != nil {
return "", err
}
v.configFile = cf
}
return v.configFile, nil
}
// Debug prints all configuration registries for debugging
// purposes.
func Debug() { v.Debug() }
func DebugTo(w io.Writer) { v.DebugTo(w) }
func (v *Viper) Debug() { v.DebugTo(os.Stdout) }
func (v *Viper) DebugTo(w io.Writer) {
fmt.Fprintf(w, "Aliases:\n%#v\n", v.aliases)
fmt.Fprintf(w, "Override:\n%#v\n", v.override)
fmt.Fprintf(w, "PFlags:\n%#v\n", v.pflags)
fmt.Fprintf(w, "Env:\n%#v\n", v.env)
fmt.Fprintf(w, "Key/Value Store:\n%#v\n", v.kvstore)
fmt.Fprintf(w, "Config:\n%#v\n", v.config)
fmt.Fprintf(w, "Defaults:\n%#v\n", v.defaults)
}
```
|
Etablissements Borel was a French aircraft manufacturer of the early twentieth century. It was founded by Gabriel Borel (1880–?1960) and manufactured a number of monoplane designs between 1909 and 1914. The factory, located at Mourmelon was temporarily forced to close when the outbreak of World War I saw most of its workers conscripted into the army, but Borel re-opened in November 1915 to produce military aircraft for France under licence from other manufacturers including Caudron, Nieuport and SPAD. In 1918, Borel was restructured as the Société Générale des Constructions Industrielles et Mécaniques (SGCIM) and attempted to re-market one of its torpedo bomber designs as a civil transport. However, neither this nor two new-generation fighter designs were able to keep the company in business.
History
Borel founded the company in late 1910, initially based in Neuilly and then Puteaux. The precise legal relationship with the Morane brothers and Raymond Saulnier isn't known, but the company built several aircraft designed by Saulnier in 1910–1911 before the collaboration ended in late 1911.
Aircraft
Morane-Borel monoplane
Morane-Borel military monoplane
Borel hydro-monoplane
Borel Bo.11
Borel military monoplane
Borel Torpille
Borel-Odier Bo-T
Citations
References
Defunct aircraft manufacturers of France
|
```ruby
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
#
# path_to_url
#
# Unless required by applicable law or agreed to in writing,
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# specific language governing permissions and limitations
module ArrowFlight
class CallOptions
class << self
def try_convert(value)
case value
when Hash
options = new
value.each do |name, value|
options.__send__("#{name}=", value)
end
options
else
nil
end
end
end
def headers=(headers)
clear_headers
headers.each do |name, value|
add_header(name, value)
end
end
def each_header
return to_enum(__method__) unless block_given?
foreach_header do |key, value|
yield(key, value)
end
end
def headers
each_header.to_a
end
end
end
```
|
Alan James Gow (born 23 June 1955) is the chief executive of the British Touring Car Championship (BTCC) and president of the FIA (Fédération Internationale de l'Automobile) Touring Car Commission. He was born in Melbourne, Australia, and lives in Surrey, England.
A lifelong entrant and competitor in Australian motorsport, Gow had business interests in Melbourne-based car dealerships and commercial property developments. From there, he became involved in the famous Australian racing team run by the legendary Peter Brock and would become a partner/managing director/team principal, whilst also helping to found TEGA – the Australian Touring Car Entrants Group – who are the administrators of, and own the rights to, the V8 Supercar Championship.
He emigrated to the UK in 1990 and formed TOCA Limited. TOCA then purchased the rights to the BTCC in 1991 and proceeded to turn the championship into the largest of its type in the world, and one of the most widely watched motorsport series around the globe.
Gow was also a partner in TOCA Australia – which ran the now defunct Australian Super Touring Championship (ASTCC) during the 1990s – as well as in the North American Touring Car Championship (NATCC), which ran for two years. Both series used regulations similar to those found in the BTCC during the same period.
In 2000, TOCA was sold to the American company Octagon Motorsport (part of the US NASDAQ listed Interpublic group) and Gow took a "sabbatical" from managing the BTCC. He retained and licensed the use of the TOCA name for interactive video gaming, and the TOCA Touring Car series became one of the biggest-selling, and most popular, games of its type in the world.
In 2003 Octagon relinquished their ownership of TOCA and the BTCC. A new company (BARC TOCA Ltd) was formed to take over management of the championship and Gow was appointed as chief executive; returning to take charge and rebuild the championship after it had floundered under the previous management.
The series soon saw an upturn in fortunes, with the following season being one Gow felt was the 'best for many years' and has gone from strength to strength ever since.
Under Gow's continued leadership, the BTCC has established itself as largest and highest-profile motor-racing championship in the UK, attracting large spectator numbers and huge television audiences; the latter thanks to a long-standing partnership with ITV that means the series remains on free-to-air TV at a time when many other forms of motorsport are now on subscription channels. It has re-established its status as one of the most popular and highly regarded motorsport championships within the world as a result.
Gow has held a number of other positions alongside his role at the head of the BTCC, both within the UK and overseas. In 2006, he was appointed as the chairman of the board of the governing body of UK motorsport, the MSA (now known as Motorsport UK) – a position he would hold for three terms before retiring from the role at the end of 2017. Gow was also chairman of International Motorsports Ltd – organisers of the British Grand Prix and Wales Rally GB during the same period, and was a board director of the Royal Automobile Club from 2010 through to 2016.
As well as his role with the FIA's Touring Car Commission, which overseas FIA-sanctioned competition at both regional and international level across the globe, Gow has been a board director and trustee of the FIA Foundation since 2012, with the foundation working on many innovative and substantial injury prevention programmes and pilot projects throughout the world.
In 2016, at the House of Lords, Gow received the prestigious Motorsport Industry Association 'Outstanding Contribution to the Motorsport Industry' award in recognition of the work carried out during his career.
Despite his move to the UK, Gow was the long-time manager of champion Australian racing driver James Courtney – with the relationship between the pair going back to the late 1990s when Courtney was racing in the British Formula Ford Championship.
Gow holds an FIA race licence and has contested various races through the years, racing everything from BMWs and MINI Coopers to Citroen 2CVs and C1s – the latter in an outing alongside multiple World Touring Car Championship-winning driver Andy Priaulx in a 24-hour race at Rockingham in 2018. Gow also had the chance to get behind the wheel of a BTCC car himself in 2018 when he drove an Alfa Romeo at Snetterton as part of a magazine feature.
Gow has held a pilot's licence since 1979 and also competed in competition water-skiing at International level during the late 1970s and early 1980s.
Racing record
Britcar 24 Hour results
References
External links
BTCC
Auto racing executives
Living people
1955 births
Australian motorsport people
Britcar 24-hour drivers
|
```yaml
branches:
- develop
plugins:
- '@semantic-release/commit-analyzer'
- '@semantic-release/github'
- 'semantic-release-export-data'
```
|
```toml
[package]
org = "abc"
name = "toplevelnodesduptest"
version= "0.1.0"
```
|
```java
package com.megagao.production.ssm.mapper;
import java.util.List;
import com.megagao.production.ssm.domain.TechnologyPlan;
import com.megagao.production.ssm.domain.TechnologyPlanExample;
import org.apache.ibatis.annotations.Param;
public interface TechnologyPlanMapper {
//mapper
List<TechnologyPlan> find(TechnologyPlan technologyPlan);
int deleteBatch(String[] ids);
List<TechnologyPlan> searchTechnologyPlanByTechnologyPlanId(
String technologyPlanId);
List<TechnologyPlan> searchTechnologyPlanByTechnologyName(
String technologyName);
//mapper
int countByExample(TechnologyPlanExample example);
int deleteByExample(TechnologyPlanExample example);
int deleteByPrimaryKey(String technologyPlanId);
int insert(TechnologyPlan record);
int insertSelective(TechnologyPlan record);
List<TechnologyPlan> selectByExample(TechnologyPlanExample example);
TechnologyPlan selectByPrimaryKey(String technologyPlanId);
int updateByExampleSelective(@Param("record") TechnologyPlan record, @Param("example") TechnologyPlanExample example);
int updateByExample(@Param("record") TechnologyPlan record, @Param("example") TechnologyPlanExample example);
int updateByPrimaryKeySelective(TechnologyPlan record);
int updateByPrimaryKey(TechnologyPlan record);
}
```
|
```xml
import npmPacklist from 'npm-packlist'
export async function packlist (pkgDir: string, opts?: {
packageJsonCache?: Record<string, Record<string, unknown>>
}): Promise<string[]> {
const packageJsonCacheMap = opts?.packageJsonCache
? new Map(Object.entries(opts.packageJsonCache))
: undefined
const files = await npmPacklist({ path: pkgDir, packageJsonCache: packageJsonCacheMap })
// There's a bug in the npm-packlist version that we use,
// it sometimes returns duplicates.
// Related issue: path_to_url
// Unfortunately, we cannot upgrade the library
// newer versions of npm-packlist are very slow.
return Array.from(new Set(files.map((file) => file.replace(/^\.[/\\]/, ''))))
}
```
|
Ian Moore is the eponymous debut album by Ian Moore and was released in 1993 (see 1993 in music).
Track listing
All songs by Ian Moore, except where noted.
"Nothing" - 5:16
"Revelation" - 4:34
"Satisfied" - 4:15
"Blue Sky" - 5:56
"Not in Vain" - 5:16 (Ian Moore, Chris White, Michael Villegas)
"Harlem" - 4:57
"How Does it Feel" - 5:02
"Deliver Me" - 6:16 (Ian Moore, Chris White)
"How Long" - 4:27 (Ian Moore, Michael Dan Ehmig)
"Please God" - 4:47
"Carry On" - 5:43
Personnel
Ian Moore - vocals, guitars
Chris White - bass
Bukka Allen - piano, organ, clavinet
Michael Villegas - drums
with:
Barry Beckett - keyboards, organ
Reese Wynans - B-3 organ on "Satisfied" and "Please God"
Justin Niebank - percussion
Donna McElroy, Justin Niebank, Kathy Burdick, Kelli Bruce, Kim Fleming, Yvonne Hodges - backing vocals
References
1993 debut albums
Albums produced by Barry Beckett
Capricorn Records albums
Ian Moore (musician) albums
|
Eadbeorht (or Eadberht) was a medieval Bishop of Leicester. He was consecrated in 764. He died between 781 and 785.
Citations
References
External links
Bishops of Leicester (ancient)
8th-century English bishops
|
```php
<?php
declare(strict_types=1);
// Settlement, Maturity, Frequency, Basis, Result
return [
[
39217,
'25-Jan-2007',
'15-Nov-2008',
2,
1,
],
[
40568,
'2011-01-01',
'2012-10-25',
4,
],
[
40568,
'2011-01-01',
'2012-10-25',
4,
null,
],
[
'#VALUE!',
'Invalid Date',
'15-Nov-2008',
2,
1,
],
[
'#VALUE!',
'25-Jan-2007',
'Invalid Date',
2,
1,
],
'Invalid Frequency' => [
'#NUM!',
'25-Jan-2007',
'15-Nov-2008',
3,
1,
],
'Non-Numeric Frequency' => [
'#VALUE!',
'25-Jan-2007',
'15-Nov-2008',
'NaN',
1,
],
'Invalid Basis' => [
'#NUM!',
'25-Jan-2007',
'15-Nov-2008',
4,
-1,
],
'Non-Numeric Basis' => [
'#VALUE!',
'25-Jan-2007',
'15-Nov-2008',
4,
'NaN',
],
'Same Date' => [
'#NUM!',
'24-Dec-2000',
'24-Dec-2000',
4,
0,
],
[
36884,
'23-Dec-2000',
'24-Dec-2000',
4,
0,
],
[
36884,
'24-Sep-2000',
'24-Dec-2000',
4,
0,
],
[
36793,
'23-Sep-2000',
'24-Dec-2000',
4,
0,
],
[
44275,
'31-Jan-2021',
'20-Mar-2021',
1,
0,
],
[
44275,
'31-Jan-2021',
'20-Mar-2021',
1,
1,
],
[
43910,
'31-Jan-2020',
'20-Mar-2021',
1,
1,
],
[
44275,
'31-Jan-2021',
'20-Mar-2021',
1,
2,
],
[
44275,
'31-Jan-2021',
'20-Mar-2021',
1,
3,
],
[
44275,
'31-Jan-2021',
'20-Mar-2021',
1,
4,
],
[
44275,
'31-Jan-2021',
'20-Mar-2021',
2,
0,
],
[
44275,
'31-Jan-2021',
'20-Mar-2021',
2,
1,
],
[
43910,
'31-Jan-2020',
'20-Mar-2021',
2,
1,
],
[
44275,
'31-Jan-2021',
'20-Mar-2021',
2,
2,
],
[
44275,
'31-Jan-2021',
'20-Mar-2021',
2,
3,
],
[
44275,
'31-Jan-2021',
'20-Mar-2021',
2,
4,
],
[
44275,
'31-Jan-2021',
'20-Mar-2021',
4,
0,
],
[
44275,
'31-Jan-2021',
'20-Mar-2021',
4,
1,
],
[
43910,
'31-Jan-2020',
'20-Mar-2021',
4,
1,
],
[
44275,
'31-Jan-2021',
'20-Mar-2021',
4,
2,
],
[
44275,
'31-Jan-2021',
'20-Mar-2021',
4,
3,
],
[
44275,
'31-Jan-2021',
'20-Mar-2021',
4,
4,
],
[
44651,
'30-Sep-2021',
'31-Mar-2022',
2,
0,
],
[
44834,
'31-Mar-2022',
'30-Sep-2022',
2,
0,
],
[
43738,
'05-Apr-2019',
'30-Sep-2021',
2,
0,
],
[
43921,
'05-Oct-2019',
'31-Mar-2022',
2,
0,
],
];
```
|
```python
#
#
# 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.
"""Voice activity detection pipelines"""
import tempfile
from copy import deepcopy
from functools import partial
from types import MethodType
from typing import Callable, Optional, Text, Union
import numpy as np
from pyannote.core import Annotation, SlidingWindowFeature
from pyannote.database.protocol import SpeakerDiarizationProtocol
from pyannote.metrics.detection import (
DetectionErrorRate,
DetectionPrecisionRecallFMeasure,
)
from pyannote.pipeline.parameter import Categorical, Integer, LogUniform, Uniform
from pytorch_lightning import Trainer
from torch.optim import SGD
from torch_audiomentations.core.transforms_interface import BaseWaveformTransform
from pyannote.audio import Inference
from pyannote.audio.core.callback import GraduallyUnfreeze
from pyannote.audio.core.io import AudioFile
from pyannote.audio.core.pipeline import Pipeline
from pyannote.audio.pipelines.utils import (
PipelineAugmentation,
PipelineInference,
PipelineModel,
get_augmentation,
get_inference,
get_model,
)
from pyannote.audio.tasks import VoiceActivityDetection as VoiceActivityDetectionTask
from pyannote.audio.utils.signal import Binarize
class OracleVoiceActivityDetection(Pipeline):
"""Oracle voice activity detection pipeline"""
@staticmethod
def apply(file: AudioFile) -> Annotation:
"""Return groundtruth voice activity detection
Parameter
---------
file : AudioFile
Must provide a "annotation" key.
Returns
-------
hypothesis : `pyannote.core.Annotation`
Speech regions
"""
speech = file["annotation"].get_timeline().support()
return speech.to_annotation(generator="string", modality="speech")
class VoiceActivityDetection(Pipeline):
"""Voice activity detection pipeline
Parameters
----------
segmentation : Model, str, or dict, optional
Pretrained segmentation (or voice activity detection) model.
Defaults to "pyannote/segmentation".
See pyannote.audio.pipelines.utils.get_model for supported format.
fscore : bool, optional
Optimize (precision/recall) fscore. Defaults to optimizing detection
error rate.
use_auth_token : str, optional
When loading private huggingface.co models, set `use_auth_token`
to True or to a string containing your hugginface.co authentication
token that can be obtained by running `huggingface-cli login`
inference_kwargs : dict, optional
Keywords arguments passed to Inference.
Hyper-parameters
----------------
onset, offset : float
Onset/offset detection thresholds
min_duration_on : float
Remove speech regions shorter than that many seconds.
min_duration_off : float
Fill non-speech regions shorter than that many seconds.
"""
def __init__(
self,
segmentation: PipelineModel = "pyannote/segmentation",
fscore: bool = False,
use_auth_token: Union[Text, None] = None,
**inference_kwargs,
):
super().__init__()
self.segmentation = segmentation
self.fscore = fscore
# load model and send it to GPU (when available and not already on GPU)
model = get_model(segmentation, use_auth_token=use_auth_token)
inference_kwargs["pre_aggregation_hook"] = lambda scores: np.max(
scores, axis=-1, keepdims=True
)
self._segmentation = Inference(model, **inference_kwargs)
if model.specifications.powerset:
self.onset = self.offset = 0.5
else:
# hyper-parameters used for hysteresis thresholding
self.onset = Uniform(0.0, 1.0)
self.offset = Uniform(0.0, 1.0)
# hyper-parameters used for post-processing i.e. removing short speech regions
# or filling short gaps between speech regions
self.min_duration_on = Uniform(0.0, 1.0)
self.min_duration_off = Uniform(0.0, 1.0)
def default_parameters(self):
if self.segmentation == "pyannote/segmentation":
# parameters optimized for DIHARD 3 development set
return {
"onset": 0.767,
"offset": 0.377,
"min_duration_on": 0.136,
"min_duration_off": 0.067,
}
elif self.segmentation == "pyannote/segmentation-3.0.0":
return {
"min_duration_on": 0.0,
"min_duration_off": 0.0,
}
raise NotImplementedError()
def classes(self):
return ["SPEECH"]
def initialize(self):
"""Initialize pipeline with current set of parameters"""
self._binarize = Binarize(
onset=self.onset,
offset=self.offset,
min_duration_on=self.min_duration_on,
min_duration_off=self.min_duration_off,
)
CACHED_SEGMENTATION = "cache/segmentation/inference"
def apply(self, file: AudioFile, hook: Optional[Callable] = None) -> Annotation:
"""Apply voice activity detection
Parameters
----------
file : AudioFile
Processed file.
hook : callable, optional
Callback called after each major steps of the pipeline as follows:
hook(step_name, # human-readable name of current step
step_artefact, # artifact generated by current step
file=file) # file being processed
Time-consuming steps call `hook` multiple times with the same `step_name`
and additional `completed` and `total` keyword arguments usable to track
progress of current step.
Returns
-------
speech : Annotation
Speech regions.
"""
# setup hook (e.g. for debugging purposes)
hook = self.setup_hook(file, hook=hook)
# apply segmentation model (only if needed)
# output shape is (num_chunks, num_frames, 1)
if self.training:
if self.CACHED_SEGMENTATION in file:
segmentations = file[self.CACHED_SEGMENTATION]
else:
segmentations = self._segmentation(
file, hook=partial(hook, "segmentation", None)
)
file[self.CACHED_SEGMENTATION] = segmentations
else:
segmentations: SlidingWindowFeature = self._segmentation(
file, hook=partial(hook, "segmentation", None)
)
hook("segmentation", segmentations)
speech: Annotation = self._binarize(segmentations)
speech.uri = file["uri"]
return speech.rename_labels({label: "SPEECH" for label in speech.labels()})
def get_metric(self) -> Union[DetectionErrorRate, DetectionPrecisionRecallFMeasure]:
"""Return new instance of detection metric"""
if self.fscore:
return DetectionPrecisionRecallFMeasure(collar=0.0, skip_overlap=False)
return DetectionErrorRate(collar=0.0, skip_overlap=False)
def get_direction(self):
if self.fscore:
return "maximize"
return "minimize"
class AdaptiveVoiceActivityDetection(Pipeline):
"""Adaptive voice activity detection pipeline
Let M be a pretrained voice activity detection model.
For each file f, this pipeline starts by applying the model to obtain a first set of
speech/non-speech labels.
Those (automatic, possibly erroneous) labels are then used to fine-tune M on the very
same file f into a M_f model, in a self-supervised manner.
Finally, the fine-tuned model M_f is applied to file f to obtain the final (and
hopefully better) speech/non-speech labels.
During fine-tuning, frames where the pretrained model M is very confident are weighted
more than those with lower confidence: the intuition is that the model will use these
high confidence regions to adapt to recording conditions (e.g. background noise) and
hence will eventually be better on the parts of f where it was initially not quite
confident.
Conversely, to avoid overfitting too much to those high confidence regions, we use
data augmentation and freeze all but the final few layers of the pretrained model M.
Parameters
----------
segmentation : Model, str, or dict, optional
Pretrained segmentation model.
Defaults to "hbredin/VoiceActivityDetection-PyanNet-DIHARD".
augmentation : BaseWaveformTransform, or dict, optional
torch_audiomentations waveform transform, used during fine-tuning.
Defaults to no augmentation.
fscore : bool, optional
Optimize (precision/recall) fscore.
Defaults to optimizing detection error rate.
Hyper-parameters
----------------
num_epochs : int
Number of epochs (where one epoch = going through the file once).
batch_size : int
Batch size.
learning_rate : float
Learning rate.
See also
--------
pyannote.audio.pipelines.utils.get_inference
"""
def __init__(
self,
segmentation: PipelineInference = "hbredin/VoiceActivityDetection-PyanNet-DIHARD",
augmentation: Optional[PipelineAugmentation] = None,
fscore: bool = False,
):
super().__init__()
# pretrained segmentation model
self.inference: Inference = get_inference(segmentation)
self.augmentation: BaseWaveformTransform = get_augmentation(augmentation)
self.fscore = fscore
self.num_epochs = Integer(0, 10)
self.batch_size = Categorical([1, 2, 4, 8, 16, 32])
self.learning_rate = LogUniform(1e-6, 1)
def apply(self, file: AudioFile) -> Annotation:
# create a copy of file
file = dict(file)
# get segmentation scores from pretrained segmentation model
file["seg"] = self.inference(file)
# infer voice activity detection scores
file["vad"] = np.max(file["seg"], axis=1, keepdims=True)
# apply voice activity detection pipeline with default parameters
vad_pipeline = VoiceActivityDetection("vad").instantiate(
{
"onset": 0.5,
"offset": 0.5,
"min_duration_on": 0.0,
"min_duration_off": 0.0,
}
)
file["annotation"] = vad_pipeline(file)
# do not fine tune the model if num_epochs is zero
if self.num_epochs == 0:
return file["annotation"]
# infer model confidence from segmentation scores
# TODO: scale confidence differently (e.g. via an additional binarisation threshold hyper-parameter)
file["confidence"] = np.min(
np.abs((file["seg"] - 0.5) / 0.5), axis=1, keepdims=True
)
# create a dummy train-only protocol where `file` is the only training file
class DummyProtocol(SpeakerDiarizationProtocol):
name = "DummyProtocol"
def train_iter(self):
yield file
vad_task = VoiceActivityDetectionTask(
DummyProtocol(),
duration=self.inference.duration,
weight="confidence",
batch_size=self.batch_size,
augmentation=self.augmentation,
)
vad_model = deepcopy(self.inference.model)
vad_model.task = vad_task
def configure_optimizers(model):
return SGD(model.parameters(), lr=self.learning_rate)
vad_model.configure_optimizers = MethodType(configure_optimizers, vad_model)
with tempfile.TemporaryDirectory() as default_root_dir:
trainer = Trainer(
max_epochs=self.num_epochs,
accelerator="gpu",
devices=1,
callbacks=[GraduallyUnfreeze(epochs_per_stage=self.num_epochs + 1)],
enable_checkpointing=False,
default_root_dir=default_root_dir,
)
trainer.fit(vad_model)
inference = Inference(
vad_model,
device=self.inference.device,
batch_size=self.inference.batch_size,
)
file["vad"] = inference(file)
return vad_pipeline(file)
def get_metric(self) -> Union[DetectionErrorRate, DetectionPrecisionRecallFMeasure]:
"""Return new instance of detection metric"""
if self.fscore:
return DetectionPrecisionRecallFMeasure(collar=0.0, skip_overlap=False)
return DetectionErrorRate(collar=0.0, skip_overlap=False)
def get_direction(self):
if self.fscore:
return "maximize"
return "minimize"
```
|
```java
package arg.marshon.publiclibrary.autoviewpager;
import android.content.Context;
import android.view.animation.Interpolator;
import android.widget.Scroller;
public class AutoScrollFactorScroller extends Scroller {
private double factor = 1;
public AutoScrollFactorScroller(Context context) {
super(context);
}
public AutoScrollFactorScroller(Context context, Interpolator interpolator) {
super(context, interpolator);
}
public void setFactor(double factor) {
this.factor = factor;
}
public double getFactor() {
return factor;
}
@Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
super.startScroll(startX, startY, dx, dy, (int)(duration * factor));
}
}
```
|
George Horatio Charles Cholmondeley, 5th Marquess of Cholmondeley (; 19 May 1883 – 16 September 1968), styled Earl of Rocksavage from birth until 1923, was a British peer. He was the Lord Great Chamberlain of England in 1936 and also between 1952 and 1966.
Personal life
Cholmondeley was a direct descendant of Sir Robert Walpole, the first Prime Minister of Great Britain. He was born in Cholmondeley Castle, near Malpas, Cheshire, the son of George Cholmondeley, 4th Marquess of Cholmondeley and Winifred Ida Kingscote. In the years before he succeeded to his father's title, he was a well-known tennis and polo player.
He was also an authority on penmanship, championing a script which became known as the "Cholmondeley Italic", and was the first president of the Society for Italic Handwriting. In 1950, he established the Cholmondeley Prize, a handwriting contest between the students of Eton and Harrow. Winchester joined in 1952 and the schools have continued the annual competition since.
Military career
Cholmondeley fought in the Second Boer War (1899–1901), serving as a "Railway Staff Officer", first with the Royal Sussex Regiment and from October 1901 as Second Lieutenant of the 9th Lancers. In 1905, he attained the rank of Lieutenant in the 9th Lancers. He was Aide-de-Camp to the Viceroy of India, and he fought in the First World War, during which he gained the rank of Captain in the 9th Lancers.
In 1923 Cholmondeley succeeded to his father's estates and peerages, becoming known by the highest of those titles, Marquess of Cholmondeley. In the 1953 Coronation Honours he was made a Knight Grand Cross of the Royal Victorian Order.
Lands and estates
The family seats are Houghton Hall, Norfolk, and Cholmondeley Castle, which is surrounded by a estate near Malpas, Cheshire.
The Cholmondeleys bought Wenbans near Wadhurst in Sussex in the mid-1890s. After major restoration work in the 1920s and 1930s, the rustic farm only from London was reported to have been used as a romantic getaway by the then Prince of Wales, who later became Edward VIII. The property was sold around the time of the abdication crisis of 1936 and the accession of George VI.
Lord Great Chamberlain
The ancient office of Lord Great Chamberlain changes at the beginning of each monarch’s reign, as the right to it is divided between three families; one moiety of that right belongs to the Marquesses of Cholmondeley, having come to them as a result of the marriage of the first Marquess to Lady Georgiana Charlotte Bertie, daughter of Peregrine Bertie, 3rd Duke of Ancaster and Kesteven. The second, fourth, fifth, sixth and seventh holders of the marquessate have all held this office.
The 5th Marquess succeeded to the office in 1936, at the beginning of the reign of Edward VIII, which proved to be short. He bore the Royal Standard at the Coronation of King George VI in 1937. He was again appointed at the beginning of the reign of Elizabeth II in 1952.
Family
The wealth of the Cholmondeley family was greatly enhanced by Cholmondeley's marriage to Sybil Sassoon (1894–1989), a member of the Sassoon family and the Rothschild family, Jewish banking families, with origins in Baghdad, India, Germany, and France. She was heiress to her brother Sir Philip Sassoon. The couple were married on 6 August 1913, and they had two sons and one daughter:
Lady Aline Caroline Cholmondeley (5 October 1916 – 30 June 2015)
George Henry Hugh, 6th Marquess of Cholmondeley (24 April 1919 – 1990)
Lord John George Cholmondeley (15 November 1920 – October 1986)
Cholmondeley died in 1968 and is buried in the Church of St Martin on the Houghton Hall estate.
His great-grandson is actor Jack Huston.
Further reading
1953 – A Handlist of the Cholmondeley (Houghton) MSS.: Sir Robert Walpole's archive (with Gilbert Allen Chinnery). Cambridge: Cambridge University Library. OCLC 3372466
1959 – The Houghton Pictures: by kind permission of The Marquess and Marchioness of Cholmondeley, [Exhibition] in aid of King George's Fund for Sailors, 6 May – 6 June 1959. London: Thomas Agnew & Sons.
See also
Cholmondeley Award (poetry), established by the marchioness in 1966
References
John Debrett, Charles Kidd, David Williamson. (1990). Debrett's Peerage and Baronetage. New York: Macmillan.
Stansky, Peter. (2003). Sassoon: the worlds of Philip and Sybil. x:.
External links
Houghton Hall
Cholmondeley Castle
1883 births
1968 deaths
Knights Grand Cross of the Royal Victorian Order
Lord Great Chamberlains
People educated at Eton College
George
British male tennis players
5
Tennis people from Cheshire
People from Houghton, Norfolk
|
```smalltalk
/*
This file is part of the iText (R) project.
Authors: Apryse Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at path_to_url For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
*/
using System;
using iText.IO.Font.Woff2.W3c;
namespace iText.IO.Font.Woff2.W3c.Decoder {
public class ValidationOff099Test : W3CWoff2DecodeTest {
protected internal override String GetFontName() {
return "validation-off-099";
}
protected internal override String GetTestInfo() {
return "Valid WOFF file from the fire format tests, the decoded file should run through a font validator to confirm the OFF structure validity.";
}
protected internal override bool IsFontValid() {
return true;
}
}
}
```
|
The London, Midland and Scottish Railway (LMS) Rebuilt Jubilee Class consisted of two 4-6-0 steam locomotives.
History
Both were rebuilt in 1942 from the LMS Jubilee Class engines—5736 Phoenix in April 1942 and 5735 Comet a month later. They were the second and third examples of the 2A-boilered locomotives, following on from the 1935 pioneer rebuild 6170 British Legion. Both Jubilees had been built in 1936 at Crewe Works, and therefore their original type 3A boilers were not life expired and hence were refurbished and reused on different engines rather than being scrapped. They were given the power classification 6P.
From 1943, it was decided not to repeat the conversion on the remaining 189 members of the Jubilee Class. Rather it was decided to rebuild members of the LMS Royal Scot Class into the LMS Rebuilt Royal Scot Class.
British Railways service
Both were inherited by British Railways in 1948, and had 40000 added to their numbers so that they became 45735/6. 45736 Phoenix was withdrawn in September 1964 and 45735 Comet followed in October. Neither was preserved.
External links
Jubilees page for (4)5735 Comet
Jubilees page for (4)5736 Phoenix
rebuilds
7 Jubilee
Standard gauge steam locomotives of Great Britain
Scrapped locomotives
Rebuilt locomotives
4-6-0 locomotives
|
Mohamed Lamine Dansoko (born 15 March 1998) is a Guinean male sprinter, specializing in the 100 metres. He represented his nation Guinea at the 2016 Summer Olympics in Rio de Janeiro, and also achieved a personal best of 10.93 seconds in his signature race at the 2015 All-Africa Games in Brazzaville, Republic of the Congo.
At the 2016 Summer Olympics, Dansoko competed for the Guinean squad in the men's 100 metres. There, he ran the first of three heats against seven other sprinters with a sixth-place time of 11.05 seconds, failing to progress from the preliminary round.
References
External links
1998 births
Living people
Guinean male sprinters
Sportspeople from Conakry
World Athletics Championships athletes for Guinea
Athletes (track and field) at the 2016 Summer Olympics
Olympic athletes for Guinea
|
Hiawanda's Cross is a 1913 silent short drama film directed and written by Romaine Fielding with scenario by Jeanette Spiess. Mary Ryan returns as costar. It was produced by the Lubin Manufacturing Company and distributed through the General Film Company.
It was filmed in Las Vegas, New Mexico.
Cast
Romaine Fielding - The Missionary
Mary Ryan - Hiawanda
Jeanette Spiess -
Rose Powers -
Chella Van Petten -
Ethel Danziger -
Carl Ilfeld - Gray Eagle
Hans Lewis -
References
External links
Hiawanda's Cross at IMDb.com
1913 films
American silent short films
1913 short films
American black-and-white films
Films directed by Romaine Fielding
Lubin Manufacturing Company films
Silent American drama films
1913 drama films
1910s American films
|
```objective-c
/**
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef zzdeps_common_memory_utils_common_h
#define zzdeps_common_memory_utils_common_h
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include "../zz.h"
char *zz_vm_read_string(const zpointer address);
zpointer zz_vm_search_data(const zpointer start_addr, const zpointer end_addr, zbyte *data,
zsize data_len);
zaddr zz_vm_align_floor(zaddr address, zsize range_size);
zaddr zz_vm_align_ceil(zaddr address, zsize range_size);
#endif
```
|
Sir Arthur Harold Marshall, KBE (2 August 1870 – 18 January 1956) was an English Liberal Party politician. He was Member of Parliament (MP) for Wakefield 1910–1918 and for Huddersfield 1922–1923.
Background
Arthur Harold Marshall was born in Ashton-under-Lyne, Lancashire, a son of Methodist Minister Rev. H.T. Marshall DD and Mary Keats of Hanley. He was educated privately and at Yorkshire College (University of Leeds). He travelled extensively in South Africa, Canada, U.S.A. and Europe. In 1896 he married Louie Hepworth, the third daughter of Joseph Hepworth JP of Leeds, Torquay and Harrogate. In 1918 he became a Knight of the British Empire. In 1948 his wife died.
Profession
In 1904 Marshall qualified as a barrister, being called to the Bar by Gray's Inn. He practiced on the North-Eastern Circuit. He was a director of the Legal Insurance Company and of J Hepworth & Son (Limited). He was director of Bradford & District Newspaper Company Limited.
Political
Marshall was elected to Harrogate Town Council, serving for six years.
In December 1910 he was elected to parliament as Liberal MP for Wakefield. He gained his seat from the Conservatives. He was the first Liberal to win the division since 1880. From 1910-1918 he served as a Liberal Whip. He was Chairman and Honorary Secretary of the Yorkshire Liberal Federation. He was Chairman of the Central Billeting Board. He was a member of the National War Savings Committee and of the National War Aims Committee.
In December 1918 he lost his seat to the Unionist he had defeated eight years earlier. There were two significant differences from 1910, firstly a Labour candidate intervened and secondly the endorsement from the wartime Coalition Government went to his Unionist opponent. In 1920 when a Conservative vacancy occurred in Ashton-under-Lyne, the town of his birth, he became the Liberal candidate for the by-election. Although no Liberal had stood in 1918 the party held the seat after the January 1910 elections. However, in a close contest between Unionist and Labour, he trailed in third place. At the next general election in 1922 he sought a return to parliament at Huddersfield. The division had returned a Coalition Government backed Liberal in 1918 against an official Liberal. Marshall had the support of Huddersfield Liberal Association and the defending member sought re-election as a National Liberal with the support of David Lloyd George and the local Conservatives. A Labour candidate made it a three-way contest. Marshall narrowly gained the seat for the Liberal Party. In parliament he again served as a Liberal Whip. A year later there was another general election. This time the Liberals were united and Marshall sought re-election against Labour and Unionist challengers. Marshall managed to increase his vote but his Labour opponent managed to do the same and beat Marshall by just 26 votes. In 1924 another general election was called and Marshall was again Liberal candidate for Huddersfield. In another close three-party contest, he was edged into third place by the Unionist. He did not stand for parliament again.
Electoral record
References
External links
1870 births
1956 deaths
Liberal Party (UK) MPs for English constituencies
Knights Commander of the Order of the British Empire
UK MPs 1910–1918
UK MPs 1922–1923
Politics of Wakefield
Politics of Huddersfield
Alumni of the University of Leeds
|
Catephia mesonephele is a species of moth of the family Erebidae. It is found in Eritrea, Ethiopia and Kenya.
The wingspan is about 24 mm. The forewings are grey-white, tinged with brown. The basal area is partly suffused with dark brown. The subbasal line is black and sinuous and the antemedial line is black, defined on the inner side by white. The medial area has an oblique bright red-brown fascia. The claviform spot is defined by black and the orbicular and reniform spots are white and incompletely defined by brown. The postmedial line is black with a faint brown line beyond it. There is an oblique red-brown shade from the apex and a faint postmedial line, as well as a waved black terminal line forming points at the interspaces. The hindwings are pure white, with a fuscous brown terminal area.
References
Catephia
Moths described in 1916
Moths of Africa
|
The election for the Chancellorship of the University of Cambridge, 1748 chose a new Chancellor of the University. The election was triggered by the retirement of the previous incumbent, Charles Seymour, 6th Duke of Somerset, in February 1748.
There were two candidates for the post: the heir to the throne, Frederick, Prince of Wales, and the cabinet minister Thomas Pelham-Holles, 1st Duke of Newcastle.
A contest ensued, and on 6 July, the Duke of Newcastle was duly declared elected. According to Elisabeth Leedham-Green, Newcastle's victory "had been the result of much strenuous political activity by his supporters." William Coxe wrote in his Memoirs of the "mortification" felt by the Prince at his failure to secure election.
Edmund Pyle, the king's chaplain, later wrote of Newcastle's "pitiful passion for the Chancellorship of Cambridge" and of his having made promises of Church of England preferments in the course of his campaign.
Notes
See also
List of chancellors of the University of Cambridge
1748
1748 in politics
1748 in England
Elections in the Kingdom of Great Britain
Non-partisan elections
|
Eupithecia thaica is a moth in the family Geometridae that is endemic to Thailand.
The wingspan is about . The forewings are brownish ochreous and the hindwings are pale yellowish white.
References
Moths described in 2009
Endemic fauna of Thailand
Moths of Asia
thaica
|
```java
package com.fishercoder.solutions.thirdthousand;
public class _2278 {
public static class Solution1 {
public int percentageLetter(String s, char letter) {
int count = 0;
for (char c : s.toCharArray()) {
if (c == letter) {
count++;
}
}
return (int) Math.floor((count * 100.0 / s.length()));
}
}
}
```
|
Kosiorów may refer to the following places in Poland:
Kosiorów, Łódź Voivodeship (central Poland)
Kosiorów, Gmina Wilków in Lublin Voivodeship (east Poland)
Kosiorów, Gmina Łaziska in Lublin Voivodeship (east Poland)
|
David Peltier (born 26 September 1963) is a retired Barbadian sprinter who specialized in the 400 metres.
At the 1984 Olympic Games he finished seventh in the 4 x 400 metres relay, together with teammates Richard Louis, Clyde Edwards and Elvis Forde. Their time of 3:01.60 minutes is still the Barbadian record. Peltier also competed in the individual distance at the 1984 Olympics.
References
External links
1963 births
Living people
Barbadian male sprinters
Athletes (track and field) at the 1984 Summer Olympics
Olympic athletes for Barbados
|
The Mon-Dak Conference (MDC) is a junior college conference for eight Tech and Community Colleges located in Montana and North Dakota, and it is a conference in the National Junior College Athletic Association (NJCAA). Conference championships are held in most sports and some individuals can be named to All-Conference and All-Academic teams.
Member schools
Current members
The Mon-Dak currently has eight full members, all but one are public schools:
Notes
See also
National Junior College Athletic Association (NJCAA)
Minnesota College Athletic Conference, also in NJCAA Region 13
External links
Mon-Dak Conference Website
NJCAA Website
NJCAA conferences
College sports in Montana
College sports in North Dakota
|
Charles Lee Smith (1887 – October 26, 1964) was an American atheist and white supremacist author and activist widely known for being the last successful conviction for blasphemy in the United States.
Biography
Raised a Methodist in Maud, Oklahoma, he entered Epworth University in Oklahoma City to study theology; however, study and debate there led him to become an atheist instead.
In November 1925, he founded the American Association for the Advancement of Atheism (A.A.A.A. or "the 4A's") in New York City, which lasted until the death of his successor James Hervey Johnson. It attempted to organize student affiliates at universities and high schools, creating at least 30 student chapters. The Los Angeles branch, "The Devil's Angels" included among its members Queen Silver, whose activities with the 4A's inspired the fictionalized movie The Godless Girl. The Rochester Chapter was known as "The Damned Souls", at Philadelphia "God's Black Sheep", at the University of Wisconsin "The Circle of the Godless", and "The Legion of the Damned" at the University of North Dakota. However, the organization declined over time.
Between 1926 and 1928, Smith came into conflict with John Roach Straton, which resulted in Straton suing Smith for harassment via the mails.
His two most famous debates were with William Landon Oliphant, a Minister, Oak Cliff Church of Christ, Dallas, Texas. This debate was held in the meeting house of the brethren in Shawnee, Oklahoma. This debate took place on August 15 and 16, 1929, and debated the propositions, "There is a Supreme Being (God, Creator)"; "Atheism is Beneficial to the Race, and is most conducive to Morality of any Theory Known to Man"; and "All Things exist as to the result of Evolution, Directed by no Intelligence." This debate was published four times in book form from 1929 to 2013.
On March 20, 1934, Smith debated Aimee Semple McPherson over evolution.
In 1935 Smith published The Bible in the Balance, which criticizes the Bible as unworthy of belief, and became a popular pamphlet for the A.A.A.A.
In 1937 Smith took over as an editor of The Truth Seeker, a free-thought magazine in New York City, where he continued as editor until his 1964 death. During his editorship, he subtitled The Truth Seeker as "The Journal for Reasoners and Racists".
Blasphemy conviction
In 1928 Smith undertook a course that ended with him the last documented person to be convicted of blasphemy in the United States. That year, Smith rented a store-front in Little Rock, Arkansas, where he gave out free anti-religious atheist literature. The sign in the window read: "Evolution Is True. The Bible's a Lie. God's a Ghost." For that, he was charged with violating the city ordinance against blasphemy.
Because he was an atheist, he therefore refused to swear the court's religious oath to tell the truth and so was not permitted to testify in his own defense. The judge then dismissed the original charge and replaced it with one of distributing obscene, slanderous, or scurrilous literature. Smith was convicted, fined $25, and served most of a 26-day jail sentence. His high-profile fast behind bars drew national media attention.
Upon his release, he immediately resumed his atheistic activities, was again charged with blasphemy, and this time convicted. In his trial, he was once more denied the right to testify and was sentenced to ninety days in jail and a fine of $100. Released on $1,000 bail, Smith appealed the verdict. The case then dragged on for several years until it was finally dismissed.
The local fundamentalist Baptist minister Ben M. Bogard, known for successfully lobbying for an Arkansas state law banning the teaching of evolution in the public schools, unexpectedly defended Smith's right to free speech in the belief that he could defeat him in a fair debate.
Late life
In 1956 Smith published the two-volume tome Sensism: The Philosophy of the West, promoting a pure atheistic philosophy, viewing all supernatural religions and thought patterns as rubbish.
During the 1959–1963 proceedings of Murray v. Curlett, Smith provided financial assistance to Madalyn Murray O'Hair to cover part of the case's legal expenses; he said that he had also provided assistance to Vashti McCollum in her 1945–1947 case.
Smith died on October 26, 1964, in San Diego, California.
Smith's ideology
Smith outlined his ideological views in the book: Sensism: The Philosophy of the West (1956). He was an anti-Semite, anti-Marxist and white supremacist. Smith denied the existence of God and was a staunch atheist and evolutionist. He believed that evolutionary processes also affected humanity. As a supporter of social Darwinism, Smith denied equality between human races. Christianity and Marxism proclaimed equality between people. Therefore, Smith was an anti-Marxist. Smith believed that Christianity and Marxism were invented by the Jews in order to seize power over humanity. Therefore, Smith was an anti-Semite.
Works
Evolution Illustrated. By Charles Smith. American Association for the Advancement of Atheism, Incorporated. 2 p. 192?
Godless Evolution. By Charles Smith. American Association for the Advancement of Atheism, Incorporated. 4 p. 192?
A Debate Between W. L. Oliphant, Minister, Oak Cliff Church of Christ, Dallas, Texas and Charles Smith, President, American Association for the Advancement of Atheism, New York City: Held in the Church of Christ, Shawnee, Oklahoma, August 15 and 16, 1929 / F. L. Rowe, 177 p. 1929.
2-nd edition: Gospel Advocate Company, Nashville, Tennessee. 177 p. 1952.
3-nd edition: M. Lynwood Smith Publications, Wesson, Mississippi. 177 p. 1983
4-nd edition: CreateSpace Independent Publishing Platform. 180 p. 2013
The Bible in the Balance. By Charles Smith. American Association for the Advancement of Atheism, Incorporated. 4 p. 1935
Sensism: The Philosophy of the West: In two vol. Vol. 1. By Charles Smith. The Truth Seeker Company, New York, First Edition, LVI, 732 p. 1956.
References
External links
The Bible in the Balance
A Debate Between W. L. Oliphant ... and Charles Smith
1887 births
1964 deaths
20th-century atheists
Activists from New York (state)
American atheism activists
American critics of Christianity
Freethought writers
Activists from Little Rock, Arkansas
Persecution of atheists
|
```c
/*
*
*/
/**
* @brief This file is only applicable to the touch hardware version3
* Version 3 includes ESP32-P4
*/
#include <inttypes.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "soc/soc_caps.h"
#include "soc/clk_tree_defs.h"
#include "soc/touch_sensor_periph.h"
#include "soc/rtc.h"
#include "hal/hal_utils.h"
#include "driver/touch_sens.h"
#include "esp_private/rtc_ctrl.h"
#include "esp_private/periph_ctrl.h"
#include "esp_clk_tree.h"
#include "esp_sleep.h"
#include "../../common/touch_sens_private.h"
#if CONFIG_TOUCH_ENABLE_DEBUG_LOG
// The local log level must be defined before including esp_log.h
// Set the maximum log level for this source file
#define LOG_LOCAL_LEVEL ESP_LOG_DEBUG
#endif
#include "esp_check.h"
static const char *TAG = "touch";
portMUX_TYPE g_touch_spinlock = portMUX_INITIALIZER_UNLOCKED;
/******************************************************************************
* Scope: touch driver private *
******************************************************************************/
void touch_priv_enable_module(bool enable)
{
TOUCH_ENTER_CRITICAL(TOUCH_RTC_LOCK);
touch_ll_enable_module_clock(enable);
touch_ll_enable_out_gate(enable);
#if SOC_TOUCH_SENSOR_VERSION >= 2
// Reset the benchmark after finished the scanning
touch_ll_reset_chan_benchmark(TOUCH_LL_FULL_CHANNEL_MASK);
#endif
TOUCH_EXIT_CRITICAL(TOUCH_RTC_LOCK);
}
void IRAM_ATTR touch_priv_default_intr_handler(void *arg)
{
/* If the touch controller object has not been allocated, return directly */
if (!g_touch) {
return;
}
bool need_yield = false;
uint32_t status = touch_ll_get_intr_status_mask();
g_touch->is_meas_timeout = false;
touch_ll_intr_clear(status);
touch_base_event_data_t data;
touch_ll_get_active_channel_mask(&data.status_mask);
data.chan = g_touch->ch[touch_ll_get_current_meas_channel()];
/* If the channel is not registered, return directly */
if (!data.chan) {
return;
}
data.chan_id = data.chan->id;
if (status & TOUCH_LL_INTR_MASK_DONE) {
if (g_touch->cbs.on_measure_done) {
need_yield |= g_touch->cbs.on_measure_done(g_touch, &data, g_touch->user_ctx);
}
}
if (status & TOUCH_LL_INTR_MASK_SCAN_DONE) {
if (g_touch->cbs.on_scan_done) {
need_yield |= g_touch->cbs.on_scan_done(g_touch, &data, g_touch->user_ctx);
}
}
if (status & TOUCH_LL_INTR_MASK_PROX_DONE) {
data.chan->prox_cnt++;
/* The proximity sensing result only accurate when the scanning times equal to the sample_cfg_num */
if (data.chan->prox_cnt == g_touch->sample_cfg_num) {
data.chan->prox_cnt = 0;
for (uint32_t i = 0; i < g_touch->sample_cfg_num; i++) {
touch_ll_read_chan_data(data.chan_id, i, TOUCH_LL_READ_BENCHMARK, &data.chan->prox_val[i]);
}
if (g_touch->cbs.on_proximity_meas_done) {
need_yield |= g_touch->cbs.on_proximity_meas_done(g_touch, &data, g_touch->user_ctx);
}
}
}
if (status & TOUCH_LL_INTR_MASK_ACTIVE) {
/* When the guard ring activated, disable the scanning of other channels to avoid fake touch */
TOUCH_ENTER_CRITICAL_SAFE(TOUCH_PERIPH_LOCK);
if (g_touch->immersion_proof && data.chan == g_touch->guard_chan) {
touch_ll_enable_scan_mask(~BIT(data.chan->id), false);
}
TOUCH_EXIT_CRITICAL_SAFE(TOUCH_PERIPH_LOCK);
if (g_touch->cbs.on_active) {
need_yield |= g_touch->cbs.on_active(g_touch, &data, g_touch->user_ctx);
}
}
if (status & TOUCH_LL_INTR_MASK_INACTIVE) {
/* When the guard ring inactivated, enable the scanning of other channels again */
TOUCH_ENTER_CRITICAL_SAFE(TOUCH_PERIPH_LOCK);
if (g_touch->immersion_proof && data.chan == g_touch->guard_chan) {
touch_ll_enable_scan_mask(g_touch->chan_mask & (~BIT(g_touch->shield_chan->id)), true);
}
TOUCH_EXIT_CRITICAL_SAFE(TOUCH_PERIPH_LOCK);
if (g_touch->cbs.on_inactive) {
need_yield |= g_touch->cbs.on_inactive(g_touch, &data, g_touch->user_ctx);
}
}
if (status & TOUCH_LL_INTR_MASK_TIMEOUT) {
g_touch->is_meas_timeout = true;
touch_ll_force_done_curr_measurement();
if (g_touch->cbs.on_timeout) {
need_yield |= g_touch->cbs.on_timeout(g_touch, &data, g_touch->user_ctx);
}
}
if (need_yield) {
portYIELD_FROM_ISR();
}
}
static esp_err_t s_touch_convert_to_hal_config(touch_sensor_handle_t sens_handle, const touch_sensor_config_t *sens_cfg, touch_hal_config_t *hal_cfg)
{
TOUCH_NULL_POINTER_CHECK(sens_cfg);
TOUCH_NULL_POINTER_CHECK(hal_cfg);
TOUCH_NULL_POINTER_CHECK(hal_cfg->sample_cfg);
ESP_RETURN_ON_FALSE(sens_cfg->sample_cfg_num && sens_cfg->sample_cfg, ESP_ERR_INVALID_ARG, TAG,
"at least one sample configuration required");
ESP_RETURN_ON_FALSE(sens_cfg->sample_cfg_num <= TOUCH_SAMPLE_CFG_NUM, ESP_ERR_INVALID_ARG, TAG,
"at most %d sample configurations supported", (int)(TOUCH_SAMPLE_CFG_NUM));
/* Get the source clock frequency for the first time */
if (!sens_handle->src_freq_hz) {
/* Touch sensor actually uses dynamic fast clock LP_DYN_FAST_CLK, but it will only switch to the slow clock during sleep,
* This driver only designed for wakeup case (sleep case should use ULP driver), so we only need to consider RTC_FAST here */
ESP_RETURN_ON_ERROR(esp_clk_tree_src_get_freq_hz(SOC_MOD_CLK_RTC_FAST, ESP_CLK_TREE_SRC_FREQ_PRECISION_CACHED, &sens_handle->src_freq_hz),
TAG, "get clock frequency failed");
ESP_LOGD(TAG, "touch rtc clock source: RTC_FAST, frequency: %"PRIu32" Hz", sens_handle->src_freq_hz);
}
uint32_t src_freq_hz = sens_handle->src_freq_hz;
uint32_t src_freq_mhz = src_freq_hz / 1000000;
hal_cfg->power_on_wait_ticks = (uint32_t)sens_cfg->power_on_wait_us * src_freq_mhz;
hal_cfg->meas_interval_ticks = (uint32_t)(sens_cfg->meas_interval_us * src_freq_mhz);
hal_cfg->timeout_ticks = (uint32_t)sens_cfg->max_meas_time_us * src_freq_mhz;
ESP_RETURN_ON_FALSE(hal_cfg->timeout_ticks <= TOUCH_LL_TIMEOUT_MAX, ESP_ERR_INVALID_ARG, TAG,
"max_meas_time_ms should within %"PRIu32, TOUCH_LL_TIMEOUT_MAX / src_freq_mhz);
hal_cfg->sample_cfg_num = sens_cfg->sample_cfg_num;
hal_cfg->output_mode = sens_cfg->output_mode;
for (uint32_t smp_cfg_id = 0; smp_cfg_id < sens_cfg->sample_cfg_num; smp_cfg_id++) {
const touch_sensor_sample_config_t *sample_cfg = &(sens_cfg->sample_cfg[smp_cfg_id]);
ESP_RETURN_ON_FALSE(sample_cfg->div_num > 0, ESP_ERR_INVALID_ARG, TAG,
"div_num can't be 0");
/* Assign the hal configurations */
hal_cfg->sample_cfg[smp_cfg_id].div_num = sample_cfg->div_num;
hal_cfg->sample_cfg[smp_cfg_id].charge_times = sample_cfg->charge_times;
hal_cfg->sample_cfg[smp_cfg_id].rc_filter_res = sample_cfg->rc_filter_res;
hal_cfg->sample_cfg[smp_cfg_id].rc_filter_cap = sample_cfg->rc_filter_cap;
hal_cfg->sample_cfg[smp_cfg_id].low_drv = sample_cfg->low_drv;
hal_cfg->sample_cfg[smp_cfg_id].high_drv = sample_cfg->high_drv;
hal_cfg->sample_cfg[smp_cfg_id].bias_volt = sample_cfg->bias_volt;
}
return ESP_OK;
}
esp_err_t touch_priv_config_controller(touch_sensor_handle_t sens_handle, const touch_sensor_config_t *sens_cfg)
{
#if CONFIG_TOUCH_ENABLE_DEBUG_LOG
esp_log_level_set(TAG, ESP_LOG_DEBUG);
#endif
/* Check and convert the configuration to hal configurations */
touch_hal_sample_config_t sample_cfg[TOUCH_SAMPLE_CFG_NUM] = {};
touch_hal_config_t hal_cfg = {
.sample_cfg = sample_cfg,
};
ESP_RETURN_ON_ERROR(s_touch_convert_to_hal_config(sens_handle, sens_cfg, &hal_cfg),
TAG, "parse the configuration failed due to the invalid configuration");
sens_handle->sample_cfg_num = sens_cfg->sample_cfg_num;
/* Configure the hardware */
TOUCH_ENTER_CRITICAL(TOUCH_PERIPH_LOCK);
touch_hal_config_controller(&hal_cfg);
TOUCH_EXIT_CRITICAL(TOUCH_PERIPH_LOCK);
return ESP_OK;
}
esp_err_t touch_priv_config_channel(touch_channel_handle_t chan_handle, const touch_channel_config_t *chan_cfg)
{
uint8_t sample_cfg_num = chan_handle->base->sample_cfg_num;
// Check the validation of the channel active threshold
for (uint8_t smp_cfg_id = 0; smp_cfg_id < sample_cfg_num; smp_cfg_id++) {
ESP_RETURN_ON_FALSE(chan_cfg->active_thresh[smp_cfg_id] <= TOUCH_LL_ACTIVE_THRESH_MAX, ESP_ERR_INVALID_ARG,
TAG, "the active threshold out of range 0~%d", TOUCH_LL_ACTIVE_THRESH_MAX);
}
TOUCH_ENTER_CRITICAL(TOUCH_PERIPH_LOCK);
for (uint8_t smp_cfg_id = 0; smp_cfg_id < sample_cfg_num; smp_cfg_id++) {
touch_ll_set_chan_active_threshold(chan_handle->id, smp_cfg_id, chan_cfg->active_thresh[smp_cfg_id]);
}
TOUCH_EXIT_CRITICAL(TOUCH_PERIPH_LOCK);
return ESP_OK;
}
esp_err_t touch_priv_deinit_controller(touch_sensor_handle_t sens_handle)
{
/* Disable the additional functions */
if (sens_handle->proximity_en) {
touch_sensor_config_proximity_sensing(sens_handle, NULL);
}
if (sens_handle->sleep_en) {
touch_sensor_config_sleep_wakeup(sens_handle, NULL);
}
if (sens_handle->waterproof_en) {
touch_sensor_config_waterproof(sens_handle, NULL);
}
return ESP_OK;
}
esp_err_t touch_priv_channel_read_data(touch_channel_handle_t chan_handle, touch_chan_data_type_t type, uint32_t *data)
{
ESP_RETURN_ON_FALSE_ISR(type >= TOUCH_CHAN_DATA_TYPE_SMOOTH && type <= TOUCH_CHAN_DATA_TYPE_PROXIMITY,
ESP_ERR_INVALID_ARG, TAG, "The channel data type is invalid");
#if CONFIG_TOUCH_CTRL_FUNC_IN_IRAM
ESP_RETURN_ON_FALSE_ISR(esp_ptr_internal(data), ESP_ERR_INVALID_ARG, TAG, "user context not in internal RAM");
#endif
uint8_t sample_cfg_num = chan_handle->base->sample_cfg_num;
if (type < TOUCH_CHAN_DATA_TYPE_PROXIMITY) {
uint32_t internal_type = 0;
switch (type) {
default: // fall through
case TOUCH_CHAN_DATA_TYPE_SMOOTH:
internal_type = TOUCH_LL_READ_SMOOTH;
break;
case TOUCH_CHAN_DATA_TYPE_BENCHMARK:
internal_type = TOUCH_LL_READ_BENCHMARK;
break;
}
if (type <= TOUCH_CHAN_DATA_TYPE_BENCHMARK) {
TOUCH_ENTER_CRITICAL_SAFE(TOUCH_PERIPH_LOCK);
for (int i = 0; i < sample_cfg_num; i++) {
touch_ll_read_chan_data(chan_handle->id, i, internal_type, &data[i]);
}
TOUCH_EXIT_CRITICAL_SAFE(TOUCH_PERIPH_LOCK);
}
} else {
if (!chan_handle->is_prox_chan) {
ESP_EARLY_LOGW(TAG, "This is not a proximity sensing channel");
}
TOUCH_ENTER_CRITICAL_SAFE(TOUCH_PERIPH_LOCK);
/* Get the proximity value from the stored data.
* The proximity value are updated in the isr when proximity scanning is done */
for (int i = 0; i < sample_cfg_num; i++) {
data[i] = chan_handle->prox_val[i];
}
TOUCH_EXIT_CRITICAL_SAFE(TOUCH_PERIPH_LOCK);
}
return ESP_OK;
}
void touch_priv_config_benchmark(touch_channel_handle_t chan_handle, const touch_chan_benchmark_config_t *benchmark_cfg)
{
if (benchmark_cfg->do_reset) {
touch_ll_reset_chan_benchmark(BIT(chan_handle->id));
}
}
/******************************************************************************
* Scope: public APIs *
******************************************************************************/
esp_err_t touch_sensor_config_filter(touch_sensor_handle_t sens_handle, const touch_sensor_filter_config_t *filter_cfg)
{
TOUCH_NULL_POINTER_CHECK(sens_handle);
if (filter_cfg) {
ESP_RETURN_ON_FALSE(filter_cfg->benchmark.denoise_lvl >= 0 && filter_cfg->benchmark.denoise_lvl <= 4,
ESP_ERR_INVALID_ARG, TAG, "denoise_lvl is out of range");
}
esp_err_t ret = ESP_OK;
xSemaphoreTake(sens_handle->mutex, portMAX_DELAY);
TOUCH_ENTER_CRITICAL(TOUCH_PERIPH_LOCK);
if (filter_cfg) {
touch_ll_filter_enable(true);
/* Configure the benchmark filter and update strategy */
touch_ll_filter_set_filter_mode(filter_cfg->benchmark.filter_mode);
if (filter_cfg->benchmark.filter_mode == TOUCH_BM_JITTER_FILTER) {
touch_ll_filter_set_jitter_step(filter_cfg->benchmark.jitter_step);
}
touch_ll_filter_set_denoise_level(filter_cfg->benchmark.denoise_lvl);
/* Configure the touch data filter */
touch_ll_filter_set_smooth_mode(filter_cfg->data.smooth_filter);
touch_ll_filter_set_active_hysteresis(filter_cfg->data.active_hysteresis);
touch_ll_filter_set_debounce(filter_cfg->data.debounce_cnt);
} else {
touch_ll_filter_enable(false);
}
TOUCH_EXIT_CRITICAL(TOUCH_PERIPH_LOCK);
xSemaphoreGive(sens_handle->mutex);
return ret;
}
esp_err_t touch_sensor_config_sleep_wakeup(touch_sensor_handle_t sens_handle, const touch_sleep_config_t *sleep_cfg)
{
TOUCH_NULL_POINTER_CHECK(sens_handle);
esp_err_t ret = ESP_OK;
int dp_slp_chan_id = -1;
touch_hal_sample_config_t sample_cfg[TOUCH_SAMPLE_CFG_NUM] = {};
touch_hal_config_t hal_cfg = {
.sample_cfg = sample_cfg,
};
touch_hal_config_t *hal_cfg_ptr = NULL;
xSemaphoreTake(sens_handle->mutex, portMAX_DELAY);
ESP_GOTO_ON_FALSE(!sens_handle->is_enabled, ESP_ERR_INVALID_STATE, err, TAG, "Please disable the touch sensor first");
if (sleep_cfg) {
ESP_GOTO_ON_FALSE(sleep_cfg->slp_wakeup_lvl == TOUCH_LIGHT_SLEEP_WAKEUP || sleep_cfg->slp_wakeup_lvl == TOUCH_DEEP_SLEEP_WAKEUP,
ESP_ERR_INVALID_ARG, err, TAG, "Invalid sleep level");
/* Enabled touch sensor as wake-up source */
ESP_GOTO_ON_ERROR(esp_sleep_enable_touchpad_wakeup(), err, TAG, "Failed to enable touch sensor wakeup");
#if SOC_PM_SUPPORT_RC_FAST_PD
ESP_GOTO_ON_ERROR(esp_sleep_pd_config(ESP_PD_DOMAIN_RC_FAST, ESP_PD_OPTION_ON), err, TAG, "Failed to keep touch sensor module clock during the sleep");
#endif
/* If set the deep sleep channel (i.e., enable deep sleep wake-up),
configure the deep sleep related settings. */
if (sleep_cfg->slp_wakeup_lvl == TOUCH_DEEP_SLEEP_WAKEUP) {
ESP_GOTO_ON_FALSE(sleep_cfg->deep_slp_chan, ESP_ERR_INVALID_ARG, err, TAG, "deep sleep waken channel can't be NULL");
dp_slp_chan_id = sleep_cfg->deep_slp_chan->id;
/* Check and convert the configuration to hal configurations */
if (sleep_cfg->deep_slp_sens_cfg) {
hal_cfg_ptr = &hal_cfg;
ESP_GOTO_ON_ERROR(s_touch_convert_to_hal_config(sens_handle, (const touch_sensor_config_t *)sleep_cfg->deep_slp_sens_cfg, hal_cfg_ptr),
err, TAG, "parse the configuration failed due to the invalid configuration");
}
sens_handle->sleep_en = true;
sens_handle->deep_slp_chan = sleep_cfg->deep_slp_chan;
TOUCH_ENTER_CRITICAL(TOUCH_PERIPH_LOCK);
/* Set sleep threshold */
for (uint8_t smp_cfg_id = 0; smp_cfg_id < TOUCH_SAMPLE_CFG_NUM; smp_cfg_id++) {
touch_ll_sleep_set_threshold(smp_cfg_id, sleep_cfg->deep_slp_thresh[smp_cfg_id]);
}
TOUCH_EXIT_CRITICAL(TOUCH_PERIPH_LOCK);
}
} else {
/* Disable the touch sensor as wake-up source */
esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_TOUCHPAD);
#if SOC_PM_SUPPORT_RC_FAST_PD
esp_sleep_pd_config(ESP_PD_DOMAIN_RC_FAST, ESP_PD_OPTION_AUTO);
#endif
sens_handle->sleep_en = false;
}
/* Save or update the sleep config */
TOUCH_ENTER_CRITICAL(TOUCH_PERIPH_LOCK);
touch_hal_save_sleep_config(dp_slp_chan_id, hal_cfg_ptr);
TOUCH_EXIT_CRITICAL(TOUCH_PERIPH_LOCK);
err:
xSemaphoreGive(sens_handle->mutex);
return ret;
}
// Water proof can be enabled separately
esp_err_t touch_sensor_config_waterproof(touch_sensor_handle_t sens_handle, const touch_waterproof_config_t *wp_cfg)
{
TOUCH_NULL_POINTER_CHECK(sens_handle);
esp_err_t ret = ESP_OK;
xSemaphoreTake(sens_handle->mutex, portMAX_DELAY);
ESP_GOTO_ON_FALSE(!sens_handle->is_enabled, ESP_ERR_INVALID_STATE, err, TAG, "Please disable the touch sensor first");
if (wp_cfg) {
// Check the validation of the waterproof configuration
TOUCH_NULL_POINTER_CHECK(wp_cfg->shield_chan);
TOUCH_ENTER_CRITICAL(TOUCH_PERIPH_LOCK);
sens_handle->waterproof_en = true;
sens_handle->immersion_proof = wp_cfg->flags.immersion_proof;
sens_handle->guard_chan = wp_cfg->guard_chan;
sens_handle->shield_chan = wp_cfg->shield_chan;
touch_ll_waterproof_set_guard_chan(wp_cfg->guard_chan ? wp_cfg->guard_chan->id : TOUCH_LL_NULL_CHANNEL);
touch_ll_waterproof_set_shield_chan_mask(BIT(wp_cfg->shield_chan->id));
// need to disable the scanning of the shield channel
touch_ll_enable_scan_mask(BIT(wp_cfg->shield_chan->id), false);
touch_ll_waterproof_set_shield_driver(wp_cfg->shield_drv);
touch_ll_waterproof_enable(true);
TOUCH_EXIT_CRITICAL(TOUCH_PERIPH_LOCK);
} else {
TOUCH_ENTER_CRITICAL(TOUCH_PERIPH_LOCK);
touch_ll_waterproof_enable(false);
touch_ll_waterproof_set_guard_chan(TOUCH_LL_NULL_CHANNEL);
touch_ll_waterproof_set_shield_chan_mask(0);
if (sens_handle->shield_chan) {
touch_ll_enable_scan_mask(BIT(sens_handle->shield_chan->id), true);
}
touch_ll_waterproof_set_shield_driver(0);
sens_handle->guard_chan = NULL;
sens_handle->shield_chan = NULL;
sens_handle->immersion_proof = false;
sens_handle->waterproof_en = false;
TOUCH_EXIT_CRITICAL(TOUCH_PERIPH_LOCK);
}
err:
xSemaphoreGive(sens_handle->mutex);
return ret;
}
esp_err_t touch_sensor_config_proximity_sensing(touch_sensor_handle_t sens_handle, const touch_proximity_config_t *prox_cfg)
{
TOUCH_NULL_POINTER_CHECK(sens_handle);
esp_err_t ret = ESP_OK;
xSemaphoreTake(sens_handle->mutex, portMAX_DELAY);
ESP_GOTO_ON_FALSE(!sens_handle->is_enabled, ESP_ERR_INVALID_STATE, err, TAG, "Please disable the touch sensor first");
TOUCH_ENTER_CRITICAL(TOUCH_PERIPH_LOCK);
/* Reset proximity sensing part of all channels */
FOR_EACH_TOUCH_CHANNEL(i) {
if (sens_handle->ch[i] && sens_handle->ch[i]->is_prox_chan) {
sens_handle->ch[i]->is_prox_chan = false;
sens_handle->ch[i]->prox_cnt = 0;
for (int i = 0; i < TOUCH_SAMPLE_CFG_NUM; i++) {
sens_handle->ch[i]->prox_val[i] = 0;
}
}
}
if (prox_cfg) {
sens_handle->proximity_en = true;
uint8_t sample_cfg_num = sens_handle->sample_cfg_num;
for (int i = 0; i < TOUCH_PROXIMITY_CHAN_NUM; i++) {
if (prox_cfg->proximity_chan[i]) {
prox_cfg->proximity_chan[i]->is_prox_chan = true;
touch_ll_set_proximity_sensing_channel(i, prox_cfg->proximity_chan[i]->id);
} else {
touch_ll_set_proximity_sensing_channel(i, TOUCH_LL_NULL_CHANNEL);
}
}
touch_ll_proximity_set_total_scan_times(prox_cfg->scan_times * sample_cfg_num);
for (uint8_t smp_cfg_id = 0; smp_cfg_id < sample_cfg_num; smp_cfg_id++) {
touch_ll_proximity_set_charge_times(smp_cfg_id, prox_cfg->charge_times[smp_cfg_id]);
}
} else {
for (int i = 0; i < TOUCH_PROXIMITY_CHAN_NUM; i++) {
touch_ll_set_proximity_sensing_channel(i, TOUCH_LL_NULL_CHANNEL);
}
sens_handle->proximity_en = false;
}
TOUCH_EXIT_CRITICAL(TOUCH_PERIPH_LOCK);
err:
xSemaphoreGive(sens_handle->mutex);
return ret;
}
```
|
(born 17 December 1953), also known as Ikue Ile, is a drummer, electronic musician, composer, and graphic designer. Mori was awarded a "Genius grant" from the MacArthur Foundation in 2022.
Biography
Ikue Mori was born and raised in Japan. She says she had little interest in music before hearing punk rock. In 1977, she went to New York City, initially for a visit, but she became involved in the music scene, and has remained in New York since.
Her first musical experience was as the drummer for seminal no wave band DNA, which also featured East Village musician Arto Lindsay. Though she had little prior musical experience (and had never played drums), Mori quickly developed a distinctive style: One critic describes her as "a tight, tireless master of shifting asymmetrical rhythm", while Lester Bangs wrote that she "cuts Sunny Murray in my book" His comment is no small praise, as Murray is widely considered a major free jazz drummer.
After DNA disbanded, Mori became active in the New York experimental music scene. She abandoned her drum set, and began playing drum machines, which she sometimes modified to play various samples. According to Mori, she was trying to make the drum machines "sound broken." Critic Adam Strohm writes that she "founded a new world for the instrument, taking it far beyond backing rhythms and robotic fills." In recent years she has used a laptop as her primary instrument, but is still sometimes credited with "electronic percussion".
In 1995, she began collaborating with Japanese bass guitarist Kato Hideki (from Ground Zero), and together with experimental guitarist Fred Frith (from Henry Cow), they formed Death Ambient. The trio released three albums, Death Ambient (1995), Synaesthesia (1999) and Drunken Forest (2007).
Beyond her solo recordings, she has recorded or performed with Dave Douglas, Butch Morris, Kim Gordon, Thurston Moore, and many others, including as Hemophiliac, a trio with John Zorn and singer Mike Patton, as well as being a member of Zorn's Electric Masada. With Zeena Parkins, she records and tours as duo project Phantom Orchard. She often records on Tzadik, as well as designing the covers for many of their albums.
Mori has drawn inspiration from visual arts. Her 2000 release, One Hundred Aspects of the Moon was inspired by famed Japanese artist Yoshitoshi. Her 2005 recording, Myrninerest, is inspired by outsider artist Madge Gill.
Mori received a 2005-2006 Foundation for Contemporary Arts Grants to Artists Award.
In 2022 Mori received the MacArthur Fellowship award ("Genius Grant").
Discography
Painted Desert (with Robert Quine and Marc Ribot; 1995)
Hex Kitchen (1995)
Garden (1996)
David Watson / Jim Denley / Rik Rue / Amanda Stewart / Ikue Mori - Bit-Part Actor (Braille Records, 1996)
B/Side (1998)
One Hundred Aspects of the Moon (2000)
Labyrinth (2001)
Phantom Orchard (2004)
Myrninerest (2005)
Bhima Swarga (2007)
Class Insecta (2009)
Near Nadir (with Mark Nauseef, Evan Parker and Bill Laswell; 2011)
The Nows (Paul Lytton/Nate Wooley + Ikue Mori/Ken Vandermark; Clean Feed, 2012)
Highsmith (with Craig Taborn; Tzadik, 2017)
Sand Storm (with Kaze) (Atypeek Diffusion / Circum-Disc, 2021)
With Lotte Anker & Sylvie Courvoisier
Alien Huddle (Intakt, 2008)
With Mephista (Mori, Sylvie Courvoisier and Susie Ibarra)
Black Narcissus (Tzadik, 2002)
Entomological Reflections (Tzadik, 2004)
With Cyro Baptista
Infinito (Tzadik, 2009)
With Dave Douglas
Freak In (RCA, 2003)
With Erik Friedlander
Claws and Wings (Skipstone, 2013)
With Fred Frith and Ensemble Modern
Traffic Continues (Winter & Winter, 2000)
Later... (Les Disques VICTO, 2000)
A Mountain Doesn't Know It's Tall (Intakt Records, 2015)
With Maybe Monday
Unsquare (Intakt, 2008)
With Rova::Orchestrova
Electric Ascension (Atavistic, 2005)
With Kim Gordon and DJ Olive
SYR5: ミュージカル パースペクティブ (Sonic Youth Recordings, 2000)
With George Spanos
Dreams Beyond (Evolver Records, 2014)
With John Zorn
Locus Solus (Rift, 1983)
The Bribe (Tzadik, 1986 [1998])
Godard/Spillane (Tzadik, 1987 [1999])
Filmworks III: 1990–1995 (Toy's Factory, 1995)
Filmworks VI: 1996 (Tzadik, 1996)
Cobra: John Zorn's Game Pieces Volume 2 (Tzadik, 2002)
Hemophiliac (Tzadik, 2002) with Hemophiliac
Voices in the Wilderness (Tzadik, 2003)
The Unknown Masada (Tzadik, 2003)
50th Birthday Celebration Volume 4 (Tzadik, 2004) with Electric Masada
50th Birthday Celebration Volume 6 (Tzadik, 2004) with Hemophiliac
Mysterium (Tzadik, 2005)
Electric Masada: At the Mountains of Madness (Tzadik, 2005) with Electric Masada
Filmworks XVI: Workingman's Death (Tzadik, 2005)
Six Litanies for Heliogabalus (Tzadik, 2007)
Femina (Tzadik, 2009)
Interzone (Tzadik, 2010)
Rimbaud (Tzadik, 2012)
In Lambeth (Tzadik, 2013) with the Gnostic Trio
On Leaves of Grass (Tzadik, 2014) with the Nova Quartet
With Medicine Singers
Medicine Singers(Joyful Noise Recordings)
References
External links
IkueMori.com (official site)
Ikue Mori (myspace)
Discography of Ikue Mori
Ikue Mori, Interviewed by Theresa Stern, November 1997
Phantom Orchard
Discography by Patrice Roussel
1953 births
Living people
Musicians from Tokyo
Tzadik Records artists
American women drummers
American women composers
American jazz composers
American rock drummers
American women jazz musicians
Japanese expatriates in the United States
Japanese experimental musicians
Japanese rock drummers
No wave musicians
Japanese women in electronic music
American women in electronic music
20th-century American drummers
20th-century American women musicians
Intakt Records artists
21st-century American women
American women graphic designers
Japanese women graphic designers
|
Scott Archer Boorman (born February 1, 1949) is a mathematical sociologist at Yale University.
Life
His father, Howard L. Boorman, was a Foreign Service Officer in Beijing, China, and he was born there as Chinese Communists troops entered the city. He received no formal education before enrolling at Harvard College, and had largely completed work on his book, The Protracted Game, which was published in 1971.
He earned his B.A. in Applied Mathematics, and was a Harvard Junior Fellow. He received his Ph.D. in Sociology from Harvard University and was appointed to a full professorship at Penn before moving to Yale. He is also a graduate of Yale Law School.
Works
While still a teenager, Boorman wrote The Protracted Game : A Wei-Ch'i Interpretation of Maoist Revolutionary Strategy (1969), an analysis of the U.S. involvement in Vietnam. He shows that the U.S. thought it was playing Chess, while in fact the game was Wei-Ch'i (also known as Go).
He systematically explores the similarity between the military strategies of Chinese Communist insurgency and the Chinese board game wei-ch’i, in contrast to parallel U.S. analyses of the same events. Boorman also argues that wei-chi's analysis of a strategic system presents a more sophisticated and flexible form of game theory than the traditional western models of strategic choice.
His book, Genetics of Altruism (1980) uses mathematical population genetics to analyze the development of sociality and altruism through three modes of selection: group, kin and reciprocity.
Notes
External links
Faculty website at Yale
List of publication
http://www.zonaeuropa.com/20050605_1.htm -(Quotes a James Pinkerton editorial invoking The Protracted Game)
American sociologists
Yale Law School alumni
1949 births
Living people
Harvard Graduate School of Arts and Sciences alumni
Yale University faculty
|
Bulbophyllum remiferum is a species of orchid in the genus Bulbophyllum.
References
External links
The Bulbophyllum-Checklist
Photo of Bulbophyllum remiferum in situ from Orchids of Sumatra
remiferum
|
```smarty
const chai = require('chai');
const <%=modName%> = require('licia/<%=modName%>');
const expect = chai.expect;
describe('<%=modName%>', function () {
<%=testHelper%>
<%=data%>
});
```
|
```java
/*
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
package org.webrtc;
import android.media.MediaCodecInfo;
import androidx.annotation.Nullable;
import java.util.Arrays;
/** Factory for Android hardware VideoDecoders. */
public class HardwareVideoDecoderFactory extends MediaCodecVideoDecoderFactory {
private final static Predicate<MediaCodecInfo> defaultAllowedPredicate =
new Predicate<MediaCodecInfo>() {
@Override
public boolean test(MediaCodecInfo arg) {
return MediaCodecUtils.isHardwareAccelerated(arg);
}
};
/** Creates a HardwareVideoDecoderFactory that does not use surface textures. */
@Deprecated // Not removed yet to avoid breaking callers.
public HardwareVideoDecoderFactory() {
this(null);
}
/**
* Creates a HardwareVideoDecoderFactory that supports surface texture rendering.
*
* @param sharedContext The textures generated will be accessible from this context. May be null,
* this disables texture support.
*/
public HardwareVideoDecoderFactory(@Nullable EglBase.Context sharedContext) {
this(sharedContext, /* codecAllowedPredicate= */ null);
}
/**
* Creates a HardwareVideoDecoderFactory that supports surface texture rendering.
*
* @param sharedContext The textures generated will be accessible from this context. May be null,
* this disables texture support.
* @param codecAllowedPredicate predicate to filter codecs. It is combined with the default
* predicate that only allows hardware codecs.
*/
public HardwareVideoDecoderFactory(@Nullable EglBase.Context sharedContext,
@Nullable Predicate<MediaCodecInfo> codecAllowedPredicate) {
super(sharedContext,
(codecAllowedPredicate == null ? defaultAllowedPredicate
: codecAllowedPredicate.and(defaultAllowedPredicate)));
}
}
```
|
Rama Koirala Paudel is a Nepalese politician, belonging to the Nepali Congress Party. She is currently serving as a member of the 2nd Federal Parliament of Nepal. In the 2022 Nepalese general election she was elected as a proportional representative from the Khas people category.
References
Living people
Nepal MPs 2022–present
Year of birth missing (living people)
|
```smalltalk
namespace WalletWasabi.Tor.Control.Messages.StreamStatus;
/// <seealso href="path_to_url">See section "4.1.2. Stream status changed".</seealso>
public enum Purpose
{
/// <summary>This stream is generated internally to Tor for fetching directory information.</summary>
DIR_FETCH,
/// <summary>An internal stream for uploading information to a directory authority.</summary>
DIR_UPLOAD,
/// <summary>A stream we're using to test our own directory port to make sure it's reachable.</summary>
DIRPORT_TEST,
/// <summary>A user-initiated DNS request.</summary>
DNS_REQUEST,
/// <summary>This stream is handling user traffic, OR it's internal to Tor, but it doesn't match one of the purposes above.</summary>
USER,
/// <summary>Reserved for unknown values.</summary>
UNKNOWN,
}
```
|
```c
/*
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <config.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <termios.h>
#include <limits.h>
#include "sudo_compat.h"
#include "sudo_debug.h"
#include "sudo_util.h"
/* Compatibility with older tty systems. */
#if !defined(TIOCGWINSZ) && defined(TIOCGSIZE)
# define TIOCGWINSZ TIOCGSIZE
# define winsize ttysize
# define ws_col ts_cols
# define ws_row ts_lines
#endif
#ifdef TIOCGWINSZ
static int
get_ttysize_ioctl(int *rowp, int *colp)
{
struct winsize wsize;
debug_decl(get_ttysize_ioctl, SUDO_DEBUG_UTIL)
if (ioctl(STDERR_FILENO, TIOCGWINSZ, &wsize) == 0 &&
wsize.ws_row != 0 && wsize.ws_col != 0) {
*rowp = wsize.ws_row;
*colp = wsize.ws_col;
debug_return_int(0);
}
debug_return_int(-1);
}
#else
static int
get_ttysize_ioctl(int *rowp, int *colp)
{
return -1;
}
#endif /* TIOCGWINSZ */
void
sudo_get_ttysize_v1(int *rowp, int *colp)
{
debug_decl(sudo_get_ttysize, SUDO_DEBUG_UTIL)
if (get_ttysize_ioctl(rowp, colp) == -1) {
char *p;
/* Fall back on $LINES and $COLUMNS. */
if ((p = getenv("LINES")) == NULL ||
(*rowp = strtonum(p, 1, INT_MAX, NULL)) <= 0) {
*rowp = 24;
}
if ((p = getenv("COLUMNS")) == NULL ||
(*colp = strtonum(p, 1, INT_MAX, NULL)) <= 0) {
*colp = 80;
}
}
debug_return;
}
```
|
```java
/*
*
*
* 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.
*/
package me.lucko.luckperms.common.plugin.scheduler;
/**
* Represents a scheduled task
*/
public interface SchedulerTask {
/**
* Cancels the task.
*/
void cancel();
}
```
|
The LPGA Corning Classic was an annual golf tournament for professional female golfers on the LPGA Tour. It took place every year from 1979 through 2009 at the Corning Country Club in Corning, New York.
It was one of the longest running tournaments on the LPGA Tour and the longest with a single sponsor. The title sponsor since the beginning was Corning Incorporated, an American manufacturer of glass, ceramics and related materials, primarily for industrial and scientific applications.
Production and operation of the tournament was a large community effort by the citizens of Corning. As with most tournaments on the LPGA Tour, proceeds went to charity. Beneficiaries of the Corning Classic were local hospitals and camps for disabled children. Net charitable proceeds since 1979 exceeded $5 million.
On April 20, 2009, the Classic's title sponsor, Corning Incorporated, announced it would not be able to sponsor the tournament after the 2009 tournament. The tournament's executives confirmed that efforts to secure additional sponsors had been unsuccessful and that the tournament would not continue after 2009.
Tournament names through the years:
1979-1983: Corning Classic
1984-2009: LPGA Corning Classic
Winners
* Championship won in sudden-death playoff.
Tournament record
References
External links
Tournament results (1979-2009) at GolfObserver.com
LPGA official tournament microsite
Former LPGA Tour events
Golf in New York (state)
Corning, New York
Recurring sporting events established in 1979
Recurring sporting events disestablished in 2009
1979 establishments in New York (state)
2009 disestablishments in New York (state)
History of women in New York (state)
|
```java
/**
*
* GFW.Press
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see <path_to_url
*
**/
package press.gfw;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Timestamp;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.crypto.SecretKey;
import javax.net.ServerSocketFactory;
import org.json.simple.JSONObject;
/**
*
* GFW.Press
*
* @author chinashiyu ( chinashiyu@gfw.press ; path_to_url )
*
*/
public class Server extends Thread {
public static void main(String[] args) throws IOException {
Server server = new Server();
server.service();
}
private File lockFile = null;
private String proxyHost = "127.0.0.1"; //
private int proxyPort = 3128; // HTTP
private int listenPort = 0;
private String password = null;
private SecretKey key = null;
private Encrypt encrypt = null;
private boolean kill = false;
private Config config = null;
private ServerSocket serverSocket = null;
/**
*
*/
public Server() {
lockFile = new File("server.lock");
config = new Config();
loadConfig(); //
}
/**
*
*
* @param proxyHost
* @param proxyPort
* @param listenPort
* @param password
*/
public Server(String proxyHost, int proxyPort, int listenPort, String password) {
super();
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
this.listenPort = listenPort;
this.password = password;
encrypt = new Encrypt();
if (encrypt.isPassword(this.password)) {
key = encrypt.getPasswordKey(this.password);
}
}
/**
*
*
* @param proxyHost
* @param proxyPort
* @param listenPort
* @param password
*/
public Server(String proxyHost, int proxyPort, String listenPort, String password) {
this(proxyHost, proxyPort, (listenPort != null && (listenPort = listenPort.trim()).matches("\\d+")) ? Integer.valueOf(listenPort) : 0, password);
}
/**
*
*
* @param m
*/
private void _sleep(long m) {
try {
sleep(m);
} catch (InterruptedException ie) {
}
}
/**
*
*
* @return
*/
public synchronized String getPassword() {
return password;
}
/**
* @return the kill
*/
public synchronized boolean isKill() {
return kill;
}
public synchronized void kill() {
kill = true;
if (serverSocket != null && !serverSocket.isClosed()) {
try {
serverSocket.close();
} catch (IOException ex) {
}
serverSocket = null;
}
}
/**
*
*/
private void loadConfig() {
JSONObject json = config.getServerConfig();
if (json != null) {
String _proxyHost = (String) json.get("ProxyHost");
proxyHost = (_proxyHost == null || (_proxyHost = _proxyHost.trim()).length() == 0) ? proxyHost : _proxyHost;
String _proxyPort = (String) json.get("ProxyPort");
proxyPort = (_proxyPort == null || !(_proxyPort = _proxyPort.trim()).matches("\\d+")) ? proxyPort : Integer.valueOf(_proxyPort);
}
}
/**
*
*
* @param o
*/
private void log(Object o) {
String time = (new Timestamp(System.currentTimeMillis())).toString().substring(0, 19);
System.out.println("[" + time + "] " + o.toString());
}
/**
*
*/
@Override
@SuppressWarnings("preview")
public void run() {
// log("" + listenPort);
if (encrypt == null || listenPort < 1024 || listenPort > 65536) {
kill = true;
log("" + listenPort + " ");
return;
}
try {
serverSocket = ServerSocketFactory.getDefault().createServerSocket(listenPort);
} catch (IOException ex) {
kill = true;
log("" + listenPort + " ");
return;
}
while (!kill) {
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException ex) {
if (kill) {
break;
}
if (serverSocket != null && !serverSocket.isClosed()) {
log("" + listenPort + " 3");
_sleep(3000L);
continue;
} else {
log("" + listenPort + " ");
break;
}
}
ServerThread serverThread = new ServerThread(clientSocket, proxyHost, proxyPort, key);
// startVirtualThread(serverThread);
serverThread.start();
}
kill = true;
if (serverSocket != null && !serverSocket.isClosed()) {
try {
serverSocket.close();
} catch (IOException ex) {
}
serverSocket = null;
}
}
/**
*
*/
@SuppressWarnings("preview")
public void service() {
if (System.currentTimeMillis() - lockFile.lastModified() < 30 * 1000L) {
log("");
log(" " + lockFile.getAbsolutePath() + "");
return;
}
try {
lockFile.createNewFile();
} catch (IOException ioe) {
}
lockFile.deleteOnExit();
log("GFW.Press......");
log("" + proxyHost);
log("" + proxyPort);
Hashtable<String, String> users = null; //
Hashtable<String, Server> threads = new Hashtable<>(); //
while (true) {
lockFile.setLastModified(System.currentTimeMillis());
users = config.getUser(); //
if (users == null || users.size() == 0) {
_sleep(10 * 1000L); // 10
continue;
}
Enumeration<String> threadPorts = threads.keys(); //
while (threadPorts.hasMoreElements()) { //
String threadPort = threadPorts.nextElement();
String userPassword = users.remove(threadPort);
if (userPassword == null) { //
threads.remove(threadPort).kill();
log("" + threadPort);
} else {
Server thread = threads.get(threadPort);
if (!userPassword.equals(thread.getPassword())) { //
log("" + threadPort);
threads.remove(threadPort);
thread.kill();
thread = new Server(proxyHost, proxyPort, threadPort, userPassword);
threads.put(threadPort, thread);
// startVirtualThread(thread);
thread.start();
}
}
}
Enumeration<String> userPorts = users.keys();
while (userPorts.hasMoreElements()) { //
String userPort = userPorts.nextElement();
Server thread = new Server(proxyHost, proxyPort, userPort, users.get(userPort));
threads.put(userPort, thread);
// startVirtualThread(thread);
thread.start();
}
users.clear();
_sleep(20 * 1000L); // 20
}
}
}
```
|
Ahn Byong-man (8 February 1941 – 31 May 2022) was a South Korean academic, and the former President of Hankuk University of Foreign Studies. He received his bachelor's and master's degrees from the Seoul National University in 1964 and 1967, and went on to the University of Florida for doctoral studies, graduating in 1973. In 1975 he joined the faculty of Hankuk University of Foreign Studies in Seoul, South Korea. While at this institution he served as the Dean of Student Affairs, Dean of the Graduate School, and in 1994 he was named president. He served in this capacity until 2004.
Ahn was a Fulbright Scholar-in-Residence at the University of Delaware, and received an honorary doctorate of humane letters from the University of Delaware in 2004. He was also a visiting professor at the university. He also received a University of Florida Distinguished Alumnus Award in May 2005.
A non-party politician, he served as Minister for Education, Science and Technology in the Lee Myung-bak government from 6 August 2008 until 30 August 2010. During his tenure, he pushed through an ambitious reform of English-as-a-foreign-language education in South Korea to reduce the reliance on hagwon in teaching the language. One of the first steps he took in this regard was to begin the development of a new English proficiency test modeled on Japan's STEP Eiken test, the National English Ability Test, with the aim of replacing the TOEIC and TOEFL for domestic purposes such as university admissions and job candidate selection. Around the same time, he also requested the resignations of seven senior officials in the Ministry.
References
1941 births
2022 deaths
Academics from Seoul
Kyunggi High School alumni
Seoul National University School of Law alumni
University of Florida alumni
Academic staff of Myongji University
South Korean political scientists
Presidents of universities and colleges in South Korea
Education ministers of South Korea
Academic staff of Hankuk University of Foreign Studies
Juksan An clan
Fulbright alumni
|
```c++
/* -*-mode:c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
#include "../../vp8/util/memory.hh"
#include <string>
#include <cassert>
#include <iostream>
#include <fstream>
#ifdef _WIN32
#include <fcntl.h>
#endif
#include "bitops.hh"
#include "component_info.hh"
#include "uncompressed_components.hh"
#include "jpgcoder.hh"
#include "vp8_encoder.hh"
#include "bool_encoder.hh"
#include "model.hh"
#include "numeric.hh"
#include "../vp8/model/model.hh"
#include "../vp8/encoder/encoder.hh"
#include "../io/MuxReader.hh"
#include "lepton_codec.hh"
extern unsigned char ujgversion;
using namespace std;
typedef Sirikata::MuxReader::ResizableByteBuffer ResizableByteBuffer;
void printContext(FILE * fp) {
#ifdef ANNOTATION_ENABLED
for (int cm= 0;cm< 3;++cm) {
for (int y = 0;y < Context::H/8; ++y) {
for (int x = 0;x < Context::W/8; ++x) {
for (int by = 0; by < 8; ++by){
for (int bx = 0; bx < 8; ++bx) {
for (int ctx = 0;ctx < NUMCONTEXT;++ctx) {
for (int dim = 0; dim < 3; ++dim) {
int val = 0;
val = gctx->p[cm][y][x][by][bx][ctx][dim];
const char *nam = "UNKNOWN";
switch (ctx) {
case ZDSTSCAN:nam = "ZDSTSCAN";break;
case ZEROS7x7:nam = "ZEROS7x7";break;
case EXPDC:nam = "EXPDC";break;
case RESDC:nam = "RESDC";break;
case SIGNDC:nam = "SIGNDC";break;
case EXP7x7:nam = "EXP7x7";break;
case RES7x7:nam = "RES7x7";break;
case SIGN7x7:nam = "SIGN7x7";break;
case ZEROS1x8:nam = "ZEROS1x8";break;
case ZEROS8x1:nam = "ZEROS8x1";break;
case EXP8:nam = "EXP8";break;
case THRESH8: nam = "THRESH8"; break;
case RES8:nam = "RES8";break;
case SIGN8:nam = "SI#include "emmintrin.h"GN8";break;
default:break;
}
if (val != -1 && ctx != ZDSTSCAN) {
fprintf(fp, "col[%02d] y[%02d]x[%02d] by[%02d]x[%02d] [%s][%d] = %d\n",
cm, y, x, by, bx, nam, dim, val);
}
}
}
}
}
}
}
}
#endif
}
template <class ArithmeticCoder>
VP8ComponentEncoder<ArithmeticCoder>::VP8ComponentEncoder(bool do_threading, bool use_ans_encoder)
: LeptonCodec<ArithmeticCoder>(do_threading){
this->mUseAnsEncoder = use_ans_encoder;
}
template <class ArithmeticCoder>
CodingReturnValue VP8ComponentEncoder<ArithmeticCoder>::encode_chunk(const UncompressedComponents *input,
IOUtil::FileWriter *output,
const ThreadHandoff *selected_splits,
unsigned int num_selected_splits)
{
return vp8_full_encoder(input, output, selected_splits, num_selected_splits, this->mUseAnsEncoder);
}
template <class ArithmeticCoder>
template<class Left, class Middle, class Right, class BoolEncoder>
void VP8ComponentEncoder<ArithmeticCoder>::process_row(ProbabilityTablesBase &pt,
Left & left_model,
Middle& middle_model,
Right& right_model,
int curr_y,
const UncompressedComponents * const colldata,
Sirikata::Array1d<ConstBlockContext,
(uint32_t)ColorChannel::NumBlockTypes> &context,
BoolEncoder &bool_encoder) {
uint32_t block_width = colldata->full_component_nosync((int)middle_model.COLOR).block_width();
if (block_width > 0) {
ConstBlockContext state = context.at((int)middle_model.COLOR);
const AlignedBlock &block = state.here();
#ifdef ANNOTATION_ENABLED
gctx->cur_cmp = component; // for debug purposes only, not to be used in production
gctx->cur_jpeg_x = 0;
gctx->cur_jpeg_y = curr_y;
#endif
state.num_nonzeros_here->set_num_nonzeros(block.recalculate_coded_length());
serialize_tokens(state,
bool_encoder,
left_model,
pt);
uint32_t offset = colldata->full_component_nosync((int)middle_model.COLOR).next(state,
true,
curr_y);
context.at((int)middle_model.COLOR) = state;
if (offset >= colldata->component_size_in_blocks(middle_model.COLOR)) {
return;
}
}
for ( unsigned int jpeg_x = 1; jpeg_x + 1 < block_width; jpeg_x++ ) {
ConstBlockContext state = context.at((int)middle_model.COLOR);
const AlignedBlock &block = state.here();
#ifdef ANNOTATION_ENABLED
gctx->cur_cmp = component; // for debug purposes only, not to be used in production
gctx->cur_jpeg_x = jpeg_x;
gctx->cur_jpeg_y = curr_y;
#endif
state.num_nonzeros_here->set_num_nonzeros(block.recalculate_coded_length()); //FIXME set edge pixels too
serialize_tokens(state,
bool_encoder,
middle_model,
pt);
uint32_t offset = colldata->full_component_nosync((int)middle_model.COLOR).next(state,
true,
curr_y);
context.at((int)middle_model.COLOR) = state;
if (offset >= colldata->component_size_in_blocks(middle_model.COLOR)) {
return;
}
}
if (block_width > 1) {
ConstBlockContext state = context.at((int)middle_model.COLOR);
const AlignedBlock &block = state.here();
#ifdef ANNOTATION_ENABLED
gctx->cur_cmp = middle_model.COLOR; // for debug purposes only, not to be used in production
gctx->cur_jpeg_x = block_width - 1;
gctx->cur_jpeg_y = curr_y;
#endif
state.num_nonzeros_here->set_num_nonzeros(block.recalculate_coded_length());
serialize_tokens(state,
bool_encoder,
right_model,
pt);
colldata->full_component_nosync((int)middle_model.COLOR).next(state, false, curr_y);
context.at((int)middle_model.COLOR) = state;
}
}
uint32_t aligned_block_cost_scalar(const AlignedBlock &block) {
uint32_t scost = 0;
for (int i = 0; i < 64; ++i) {
scost += 1 + 2 * uint16bit_length(abs(block.raw_data()[i]));
}
return scost;
}
uint32_t aligned_block_cost(const AlignedBlock &block) {
#if defined(__SSE2__) && !defined(USE_SCALAR) /* SSE2 or higher instruction set available { */
const __m128i zero = _mm_setzero_si128();
__m128i v_cost;
for (int i = 0; i < 64; i+= 8) {
__m128i val = _mm_abs_epi16(_mm_load_si128((const __m128i*)(const char*)(block.raw_data() + i)));
v_cost = _mm_set1_epi16(0);
#ifndef __SSE4_1__
while (_mm_movemask_epi8(_mm_cmpeq_epi32(val, zero)) != 0xFFFF)
#else
while (!_mm_test_all_zeros(val, val))
#endif
{
__m128i mask = _mm_cmpgt_epi16(val, zero);
v_cost = _mm_add_epi16(v_cost, _mm_and_si128(mask, _mm_set1_epi16(2)));
val = _mm_srli_epi16(val, 1);
}
v_cost = _mm_add_epi16(v_cost, _mm_srli_si128(v_cost, 8));
v_cost = _mm_add_epi16(v_cost ,_mm_srli_si128(v_cost, 4));
v_cost = _mm_add_epi16(v_cost, _mm_srli_si128(v_cost, 2));
}
return 16 + _mm_extract_epi16(v_cost, 0);
#else /* } No SSE2 instructions { */
return aligned_block_cost_scalar(block);
#endif /* } */
}
#ifdef ALLOW_FOUR_COLORS
#define ProbabilityTablesTuple(left, above, right) \
ProbabilityTables<left && above && right, TEMPLATE_ARG_COLOR0>, \
ProbabilityTables<left && above && right, TEMPLATE_ARG_COLOR1>, \
ProbabilityTables<left && above && right, TEMPLATE_ARG_COLOR2>, \
ProbabilityTables<left && above && right, TEMPLATE_ARG_COLOR3>
#define EACH_BLOCK_TYPE(left, above, right) ProbabilityTables<left&&above&&right, TEMPLATE_ARG_COLOR0>(BlockType::Y, \
left, \
above, \
right), \
ProbabilityTables<left&&above&&right, TEMPLATE_ARG_COLOR1>(BlockType::Cb, \
left, \
above, \
right), \
ProbabilityTables<left&&above&&right, TEMPLATE_ARG_COLOR2>(BlockType::Cr, \
left, \
above, \
right), \
ProbabilityTables<left&&above&&right, TEMPLATE_ARG_COLOR3>(BlockType::Ck, \
left, \
above, \
right)
#else
#define ProbabilityTablesTuple(left, above, right) \
ProbabilityTables<left && above && right, TEMPLATE_ARG_COLOR0>, \
ProbabilityTables<left && above && right, TEMPLATE_ARG_COLOR1>, \
ProbabilityTables<left && above && right, TEMPLATE_ARG_COLOR2>
#define EACH_BLOCK_TYPE(left, above, right) ProbabilityTables<left&&above&&right, TEMPLATE_ARG_COLOR0>(BlockType::Y, \
left, \
above, \
right), \
ProbabilityTables<left&&above&&right, TEMPLATE_ARG_COLOR1>(BlockType::Cb, \
left, \
above, \
right), \
ProbabilityTables<left&&above&&right, TEMPLATE_ARG_COLOR2>(BlockType::Cr, \
left, \
above, \
right)
#endif
tuple<ProbabilityTablesTuple(false, false, false)> corner(EACH_BLOCK_TYPE(false,false,false));
tuple<ProbabilityTablesTuple(true, false, false)> top(EACH_BLOCK_TYPE(true, false, false));
tuple<ProbabilityTablesTuple(false, true, true)> midleft(EACH_BLOCK_TYPE(false, true, true));
tuple<ProbabilityTablesTuple(true, true, true)> middle(EACH_BLOCK_TYPE(true, true, true));
tuple<ProbabilityTablesTuple(true, true, false)> midright(EACH_BLOCK_TYPE(true, true, false));
tuple<ProbabilityTablesTuple(false, true, false)> width_one(EACH_BLOCK_TYPE(false, true, false));
template <class ArithmeticCoder> template <class BoolEncoder>
void VP8ComponentEncoder<ArithmeticCoder>::process_row_range(unsigned int thread_id,
const UncompressedComponents * const colldata,
int min_y,
int max_y,
ResizableByteBuffer *stream,
BoolEncoder *bool_encoder,
Sirikata::Array1d<std::vector<NeighborSummary>,
(uint32_t)ColorChannel::NumBlockTypes
> *num_nonzeros) {
TimingHarness::timing[thread_id][TimingHarness::TS_ARITH_STARTED] = TimingHarness::get_time_us();
using namespace Sirikata;
Array1d<ConstBlockContext, (uint32_t)ColorChannel::NumBlockTypes> context;
for (size_t i = 0; i < context.size(); ++i) {
context[i] = colldata->full_component_nosync(i).begin(num_nonzeros->at(i).begin());
}
uint8_t is_top_row[(uint32_t)ColorChannel::NumBlockTypes];
memset(is_top_row, true, sizeof(is_top_row));
ProbabilityTablesBase *model = nullptr;
if (this->do_threading_) {
LeptonCodec<ArithmeticCoder>::reset_thread_model_state(thread_id);
model = &this->thread_state_[thread_id]->model_;
} else {
LeptonCodec<ArithmeticCoder>::reset_thread_model_state(0);
model = &this->thread_state_[0]->model_;
}
KBlockBasedImagePerChannel<false> image_data;
for (int i = 0; i < colldata->get_num_components(); ++i) {
image_data[i] = &colldata->full_component_nosync((int)i);
}
uint32_t encode_index = 0;
Array1d<uint32_t, (uint32_t)ColorChannel::NumBlockTypes> max_coded_heights = colldata->get_max_coded_heights();
while(true) {
LeptonCodec_RowSpec cur_row = LeptonCodec_row_spec_from_index(encode_index++,
image_data,
colldata->get_mcu_count_vertical(),
max_coded_heights);
if(cur_row.done) {
break;
}
if (cur_row.luma_y >= max_y && thread_id + 1 != NUM_THREADS) {
break;
}
if (cur_row.skip) {
continue;
}
if (cur_row.luma_y < min_y) {
continue;
}
context[cur_row.component]
= image_data.at(cur_row.component)->off_y(cur_row.curr_y,
num_nonzeros->at(cur_row.component).begin());
// DEBUG only fprintf(stderr, "Thread %d min_y %d - max_y %d cmp[%d] y = %d\n", thread_id, min_y, max_y, (int)component, curr_y);
int block_width = image_data.at(cur_row.component)->block_width();
if (is_top_row[cur_row.component]) {
is_top_row[cur_row.component] = false;
switch((BlockType)cur_row.component) {
case BlockType::Y:
process_row(*model,
std::get<(int)BlockType::Y>(corner),
std::get<(int)BlockType::Y>(top),
std::get<(int)BlockType::Y>(top),
cur_row.curr_y,
colldata,
context,
*bool_encoder);
break;
case BlockType::Cb:
process_row(*model,
std::get<(int)BlockType::Cb>(corner),
std::get<(int)BlockType::Cb>(top),
std::get<(int)BlockType::Cb>(top),
cur_row.curr_y,
colldata,
context,
*bool_encoder);
break;
case BlockType::Cr:
process_row(*model,
std::get<(int)BlockType::Cr>(corner),
std::get<(int)BlockType::Cr>(top),
std::get<(int)BlockType::Cr>(top),
cur_row.curr_y,
colldata,
context,
*bool_encoder);
break;
#ifdef ALLOW_FOUR_COLORS
case BlockType::Ck:
process_row(*model,
std::get<(int)BlockType::Ck>(corner),
std::get<(int)BlockType::Ck>(top),
std::get<(int)BlockType::Ck>(top),
cur_row.curr_y,
colldata,
context,
*bool_encoder);
break;
#endif
}
} else if (block_width > 1) {
switch((BlockType)cur_row.component) {
case BlockType::Y:
process_row(*model,
std::get<(int)BlockType::Y>(midleft),
std::get<(int)BlockType::Y>(middle),
std::get<(int)BlockType::Y>(midright),
cur_row.curr_y,
colldata,
context,
*bool_encoder);
break;
case BlockType::Cb:
process_row(*model,
std::get<(int)BlockType::Cb>(midleft),
std::get<(int)BlockType::Cb>(middle),
std::get<(int)BlockType::Cb>(midright),
cur_row.curr_y,
colldata,
context,
*bool_encoder);
break;
case BlockType::Cr:
process_row(*model,
std::get<(int)BlockType::Cr>(midleft),
std::get<(int)BlockType::Cr>(middle),
std::get<(int)BlockType::Cr>(midright),
cur_row.curr_y,
colldata,
context,
*bool_encoder);
break;
#ifdef ALLOW_FOUR_COLORS
case BlockType::Ck:
process_row(*model,
std::get<(int)BlockType::Ck>(midleft),
std::get<(int)BlockType::Ck>(middle),
std::get<(int)BlockType::Ck>(midright),
cur_row.curr_y,
colldata,
context,
*bool_encoder);
break;
#endif
}
} else {
always_assert(block_width == 1);
switch((BlockType)cur_row.component) {
case BlockType::Y:
process_row(*model,
std::get<(int)BlockType::Y>(width_one),
std::get<(int)BlockType::Y>(width_one),
std::get<(int)BlockType::Y>(width_one),
cur_row.curr_y,
colldata,
context,
*bool_encoder);
break;
case BlockType::Cb:
process_row(*model,
std::get<(int)BlockType::Cb>(width_one),
std::get<(int)BlockType::Cb>(width_one),
std::get<(int)BlockType::Cb>(width_one),
cur_row.curr_y,
colldata,
context,
*bool_encoder);
break;
case BlockType::Cr:
process_row(*model,
std::get<(int)BlockType::Cr>(width_one),
std::get<(int)BlockType::Cr>(width_one),
std::get<(int)BlockType::Cr>(width_one),
cur_row.curr_y,
colldata,
context,
*bool_encoder);
break;
#ifdef ALLOW_FOUR_COLORS
case BlockType::Ck:
process_row(*model,
std::get<(int)BlockType::Ck>(width_one),
std::get<(int)BlockType::Ck>(width_one),
std::get<(int)BlockType::Ck>(width_one),
cur_row.curr_y,
colldata,
context,
*bool_encoder);
break;
#endif
}
}
}
LeptonCodec_RowSpec test = ::LeptonCodec_row_spec_from_index(encode_index,
image_data,
colldata->get_mcu_count_vertical(),
max_coded_heights);
if (thread_id == NUM_THREADS - 1 && (test.skip == false || test.done == false)) {
fprintf(stderr, "Row spec test: cmp %d luma %d item %d skip %d done %d\n",
test.component, test.luma_y, test.curr_y, test.skip, test.done);
custom_exit(ExitCode::ASSERTION_FAILURE);
}
bool_encoder->finish(*stream);
TimingHarness::timing[thread_id][TimingHarness::TS_ARITH_FINISHED] = TimingHarness::get_time_us();
}
int load_model_file_fd_output() {
const char * out_model_name = getenv( "LEPTON_COMPRESSION_MODEL_OUT" );
if (!out_model_name) {
return -1;
}
return open(out_model_name, O_CREAT|O_TRUNC|O_WRONLY, 0
#ifndef _WIN32
|S_IWUSR | S_IRUSR
#endif
);
}
int model_file_fd = load_model_file_fd_output();
template <class BoolDecoder>
template<class BoolEncoder> void VP8ComponentEncoder<BoolDecoder>::threaded_encode_inner(const UncompressedComponents * const colldata,
IOUtil::FileWriter *str_out,
const ThreadHandoff * selected_splits,
unsigned int num_selected_splits,
BoolEncoder bool_encoder[MAX_NUM_THREADS],
ResizableByteBuffer stream[Sirikata::MuxReader::MAX_STREAM_ID]) {
using namespace Sirikata;
Array1d<std::vector<NeighborSummary>,
(uint32_t)ColorChannel::NumBlockTypes> num_nonzeros[MAX_NUM_THREADS];
for (unsigned int thread_id = 0; thread_id < NUM_THREADS; ++thread_id) {
bool_encoder[thread_id].init();
for (size_t i = 0; i < num_nonzeros[thread_id].size(); ++i) {
num_nonzeros[thread_id].at(i).resize(colldata->block_width(i) << 1);
}
}
if (this->do_threading()) {
for (unsigned int thread_id = 1; thread_id < NUM_THREADS; ++thread_id) {
this->spin_workers_[thread_id - 1].work
= std::bind(&VP8ComponentEncoder<BoolDecoder>::process_row_range<BoolEncoder>, this,
thread_id,
colldata,
selected_splits[thread_id].luma_y_start,
selected_splits[thread_id].luma_y_end,
&stream[thread_id],
&bool_encoder[thread_id],
&num_nonzeros[thread_id]);
this->spin_workers_[thread_id - 1].activate_work();
}
}
process_row_range(0,
colldata,
selected_splits[0].luma_y_start,
selected_splits[0].luma_y_end,
&stream[0],
&bool_encoder[0],
&num_nonzeros[0]);
if(!this->do_threading()) { // single threading
for (unsigned int thread_id = 1; thread_id < NUM_THREADS; ++thread_id) {
process_row_range(thread_id,
colldata,
selected_splits[thread_id].luma_y_start,
selected_splits[thread_id].luma_y_end,
&stream[thread_id],
&bool_encoder[thread_id],
&num_nonzeros[thread_id]);
}
}
static_assert(MAX_NUM_THREADS * SIMD_WIDTH <= MuxReader::MAX_STREAM_ID,
"Need to have enough mux streams for all threads and simd width");
if (this->do_threading()) {
for (unsigned int thread_id = 1; thread_id < NUM_THREADS; ++thread_id) {
TimingHarness::timing[thread_id][TimingHarness::TS_THREAD_WAIT_STARTED] = TimingHarness::get_time_us();
this->spin_workers_[thread_id - 1].main_wait_for_done();
TimingHarness::timing[thread_id][TimingHarness::TS_THREAD_WAIT_FINISHED] = TimingHarness::get_time_us();
}
}
}
template<class BoolDecoder>
CodingReturnValue VP8ComponentEncoder<BoolDecoder>::vp8_full_encoder(const UncompressedComponents * const colldata,
IOUtil::FileWriter *str_out,
const ThreadHandoff * selected_splits,
unsigned int num_selected_splits,
bool use_ans_encoder)
{
/* cmpc is a global variable with the component count */
using namespace Sirikata;
/* get ready to serialize the blocks */
if (colldata->get_num_components() > (int)BlockType::Y) {
ProbabilityTablesBase::set_quantization_table(BlockType::Y,
colldata->get_quantization_tables(BlockType::Y));
}
if (colldata->get_num_components() > (int)BlockType::Cb) {
ProbabilityTablesBase::set_quantization_table(BlockType::Cb,
colldata->get_quantization_tables(BlockType::Cb));
}
if (colldata->get_num_components() > (int)BlockType::Cr) {
ProbabilityTablesBase::set_quantization_table(BlockType::Cr,
colldata->get_quantization_tables(BlockType::Cr));
}
#ifdef ALLOW_FOUR_COLORS
if (colldata->get_num_components() > (int)BlockType::Ck) {
ProbabilityTablesBase::set_quantization_table(BlockType::Ck,
colldata->get_quantization_tables(BlockType::Ck));
}
#endif
ResizableByteBuffer stream[MuxReader::MAX_STREAM_ID];
if (use_ans_encoder) {
#ifdef ENABLE_ANS_EXPERIMENTAL
ANSBoolWriter bool_encoder[MAX_NUM_THREADS];
this->threaded_encode_inner(colldata,
str_out,
selected_splits,
num_selected_splits,
bool_encoder,
stream);
#else
always_assert(false && "Need to enable ANS compile flag to include ANS");
#endif
} else {
VPXBoolWriter bool_encoder[MAX_NUM_THREADS];
this->threaded_encode_inner(colldata,
str_out,
selected_splits,
num_selected_splits,
bool_encoder,
stream);
}
TimingHarness::timing[0][TimingHarness::TS_STREAM_MULTIPLEX_STARTED] = TimingHarness::get_time_us();
Sirikata::MuxWriter mux_writer(str_out, JpegAllocator<uint8_t>(), ujgversion);
size_t stream_data_offset[MuxReader::MAX_STREAM_ID] = {0};
bool any_written = true;
while (any_written) {
any_written = false;
for (int i = 0; i < MuxReader::MAX_STREAM_ID; ++i) {
if (stream[i].size() > stream_data_offset[i]) {
any_written = true;
size_t max_written = 65536;
if (stream_data_offset[i] == 0) {
max_written = 256;
} else if (stream_data_offset[i] == 256) {
max_written = 4096;
}
auto to_write = std::min(max_written, stream[i].size() - stream_data_offset[i]);
stream_data_offset[i] += mux_writer.Write(i, &(stream[i])[stream_data_offset[i]], to_write).first;
}
}
}
mux_writer.Close();
write_byte_bill(Billing::DELIMITERS, true, mux_writer.getOverhead());
// we can probably exit(0) here
TimingHarness::timing[0][TimingHarness::TS_STREAM_MULTIPLEX_FINISHED] =
TimingHarness::timing[0][TimingHarness::TS_STREAM_FLUSH_STARTED] = TimingHarness::get_time_us();
check_decompression_memory_bound_ok(); // this has to happen before last
// bytes are written
/* possibly write out new probability model */
{
uint32_t out_file_size = str_out->getsize() + 4; // gotta include the final uint32_t
uint32_t file_size = out_file_size;
uint8_t out_buffer[sizeof(out_file_size)] = {};
for (uint8_t i = 0; i < sizeof(out_file_size); ++i) {
out_buffer[i] = out_file_size & 0xff;
out_file_size >>= 8;
}
str_out->Write(out_buffer, sizeof(out_file_size));
write_byte_bill(Billing::HEADER, true, sizeof(out_file_size));
(void)file_size;
always_assert(str_out->getsize() == file_size);
}
if ( model_file_fd >= 0 ) {
const char * msg = "Writing new compression model...\n";
while (write(2, msg, strlen(msg)) < 0 && errno == EINTR){}
std::get<(int)BlockType::Y>(middle).optimize(this->thread_state_[0]->model_);
std::get<(int)BlockType::Y>(middle).serialize(this->thread_state_[0]->model_, model_file_fd );
}
#ifdef ANNOTATION_ENABLED
{
FILE * fp = fopen("/tmp/lepton.ctx","w");
printContext(fp);
fclose(fp);
}
#endif
TimingHarness::timing[0][TimingHarness::TS_STREAM_FLUSH_FINISHED] = TimingHarness::get_time_us();
return CODING_DONE;
}
template class VP8ComponentEncoder<VPXBoolReader>;
#ifdef ENABLE_ANS_EXPERIMENTAL
template class VP8ComponentEncoder<ANSBoolReader>;
#endif
```
|
Sonia Maria Fleury Teixeira also simply known as Sonia Fleury is a Brazilian political scientist, researcher and professor. She has written and published over 120 research articles in scientific magazines and editorials.
Career
Sonia holds a doctorate degree in political science, bachelor's degree in psychology and also pursued her master's degree in sociology. She has been a faculty fellow at the Kellogg Institute at the University of Notre Dame in USA.
She has served as a prominent researcher at the Oswaldo Cruz Foundation in Brazil and also served as a professor at the National School of Public Health in Brazil until 1995. In addition, she has also worked as a consultant for Brazilian social ministries, IDB, UNDP, World Bank, WHO, SELA and CLAD.
She currently serves as a senior researcher at the Escola Brasileira de Administração Pública e de Empresas, Fundação Getulio Vargas. Sonia has also been often critical about Brazilian government's mishandling of the COVID-19 pandemic in Brazil.
References
External links
Living people
20th-century Brazilian women writers
20th-century Brazilian scientists
21st-century Brazilian women
21st-century Brazilian scientists
Brazilian women academics
20th-century Brazilian educators
21st-century Brazilian educators
Brazilian women educators
Brazilian women scientists
Brazilian women writers
Brazilian political scientists
University of Notre Dame faculty
Year of birth missing (living people)
20th-century Brazilian women scientists
|
Aredio Gimona (; 1 February 1924 – 11 February 1994) was an Italian professional football player and coach who played as a midfielder. He represented Italy at the 1952 Summer Olympics.
References
External links
1924 births
1994 deaths
Italian men's footballers
Italy men's international footballers
Serie A players
Serie C players
AC Milan players
US Livorno 1915 players
Palermo FC players
Juventus FC players
Aurora Pro Patria 1919 players
Empoli FC players
Olympic footballers for Italy
Footballers at the 1952 Summer Olympics
Italian football managers
US Pistoiese 1921 managers
SS Arezzo managers
US Livorno 1915 managers
Genoa CFC managers
People from Izola
Men's association football midfielders
AS Pro Gorizia players
|
```ruby
require 'concurrent/synchronization'
module Concurrent
module Collection
# A thread safe observer set implemented using copy-on-read approach:
# observers are added and removed from a thread safe collection; every time
# a notification is required the internal data structure is copied to
# prevent concurrency issues
#
# @api private
class CopyOnNotifyObserverSet < Synchronization::LockableObject
def initialize
super()
synchronize { ns_initialize }
end
# @!macro observable_add_observer
def add_observer(observer = nil, func = :update, &block)
if observer.nil? && block.nil?
raise ArgumentError, 'should pass observer as a first argument or block'
elsif observer && block
raise ArgumentError.new('cannot provide both an observer and a block')
end
if block
observer = block
func = :call
end
synchronize do
@observers[observer] = func
observer
end
end
# @!macro observable_delete_observer
def delete_observer(observer)
synchronize do
@observers.delete(observer)
observer
end
end
# @!macro observable_delete_observers
def delete_observers
synchronize do
@observers.clear
self
end
end
# @!macro observable_count_observers
def count_observers
synchronize { @observers.count }
end
# Notifies all registered observers with optional args
# @param [Object] args arguments to be passed to each observer
# @return [CopyOnWriteObserverSet] self
def notify_observers(*args, &block)
observers = duplicate_observers
notify_to(observers, *args, &block)
self
end
# Notifies all registered observers with optional args and deletes them.
#
# @param [Object] args arguments to be passed to each observer
# @return [CopyOnWriteObserverSet] self
def notify_and_delete_observers(*args, &block)
observers = duplicate_and_clear_observers
notify_to(observers, *args, &block)
self
end
protected
def ns_initialize
@observers = {}
end
private
def duplicate_and_clear_observers
synchronize do
observers = @observers.dup
@observers.clear
observers
end
end
def duplicate_observers
synchronize { @observers.dup }
end
def notify_to(observers, *args)
raise ArgumentError.new('cannot give arguments and a block') if block_given? && !args.empty?
observers.each do |observer, function|
args = yield if block_given?
observer.send(function, *args)
end
end
end
end
end
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.