text
stringlengths 1
22.8M
|
|---|
Karin Lesch (born 18 May 1935) is a Swiss-German stage, cinema, and television actress, of Swiss-Austrian extraction; who hails from a multi-generational family of accomplished German-speaking performers of theatre and cinema.
Lesch was born in Zürich, the daughter of Swiss director, dramatist, and author Walter Lesch (1892–1958), and the Austrian actress Mathilde Danegger (1903–1988). In addition to both of her parents having professional careers in the German-speaking dramatic arts, Lesch comes from a family of Austrian entertainers of music, stage, and cinema. On her maternal side, her grandfather was the Austrian character-actor and director , Snr (1866-1933), and her maternal grandmother Bertha Müller (1866-1938) was an Austrian actress of both stage and silent-film. Her uncle , Jnr, (1889–1948) was an Austrian actor of stage and cinema, whilst her uncle Theodor Danegger (1891–1959) was both an opera singer and recording artist in addition to being an actor of stage and cinema, having performed in both musicals and operettas, as well as in purely dramatic roles.
Early life
Due to Swiss neutrality, Lesh grew up unscathed by the effects of World War II, and the havoc wreaked on her mother's native Austria after its annexation by the Third Reich. After the War, however, Lesch's life changed radically with the breakdown of her parents marriage. Her mother took Lesch from her father and her native Switzerland, when she was only twelve years old, to live first in West Germany in 1947, and then, because of her mother's political convictions, to the newly formed (1949) communist East Germany in 1951, when Lesch was just sixteen.
Education and career
A formally trained actress of both stage and cinema, as well as television, Lesch studied at the Staatlichen Schauspielschule (i.e. the (former) State Drama School, East Berlin), after which she received a contract with the . She often played in different fairy-tale films, such as her role as the miller's daughter Marie in the film adaptation of the fairy tale Rumpelstiltskin in the 1960 television production Das Zaubermännchen.
To English-speaking audiences, Lesch is perhaps best known for her cinema role as the Queen in the 1973 East German – Czechoslovak co-production Three Gifts for Cinderella (the title used for its UK debut), or Three Nuts for Cinderella (the title used for its US debut); but also known as: Three Wishes for Cinderella in various subsequent releases in the English-speaking world (The original German title is: Drei Haselnüsse für Aschenbrödel, and the original Czech title is: Tři oříšky pro Popelku). The film is based on a Bohemian version of the fairy tale Cinderella as written by the Czech National Revivalist writer Božena Němcová, with the storyline more closely related to the German version published by the Brothers Grimm in 1812, versus the somewhat different version more widely known in English that is based on the earlier French version published by Charles Perrault in 1697 (hence the reason for the role of the Queen, a character not found in the Anglo-French version of the fairy tale). The role having proved difficult to cast, once East German actor Rolf Hoppe had been given the part as the King, he suggested Karin Lesch, with whom he had enjoyed a professional relationship, having worked on stage with Lesch several times before. Although initially expected to screen-test, as all the other actresses who had vied for the part, the film's director Václav Vorlíček was so impressed, he gave Lesch the role after only a read-through.
Much like Dinner for One, the film has become a holiday classic being shown on television at Christmas-time every year in Germany, Switzerland, Austria, the Czech Republic, Slovakia, parts of Scandinavia – especially Norway – as well as elsewhere in Europe during the holiday season. The movie was shot in both German and Czech, with the cast members each speaking their lines in their own language, and with extensive post-filming work carried out so that two versions of the original were released, one with the Czech lines dubbed into German, and the other with the German lines dubbed into Czech, and employed what, at the time, was the newly developed technique of synchronisation to create a more visually realistic effect of speech emanating from the lips whenever the dialogue was being dubbed.
Both a gifted linguist, as well as a professional voice artist – in addition to her work as a dramatic actress – after shooting Three Gifts for Cinderella in German, her mother tongue, Lesch dubbed the same role she played for the production's Czech release. This made her one of only three of the fourteen cast members with speaking-parts who were asked to provide their own voices for their respective roles in both the German and Czechoslovak versions; (although Czech actress Vlasta Fialová is credited as having provided the voice used in what became the official release of Tři oříšky pro Popelku).
At least two versions exist in English, viz: One dubbed without lip-synchronisation, whilst another uses an omniscient narrator in voice-over, as the actors can still be faintly heard to give their original lines in their own languages.
Private life
Lesch married East German producer-director (1930–2009), who later became the Director General of DEFA, the state-owned film studio in the former German Democratic Republic.
Lesch remained in the East through the turbulence leading up to the 1990 Reunification of Germany, and the period of adjustment in its aftermath, where she continues to live, now widowed and in retirement, in the Berlin-Brandenburg Metropolitan Region of Brandenburg in eastern Germany.
Her son , born in 1962, is a screenwriter, author, and member of the German Writers Guild, who lives in nearby Berlin.
Post-theatrical Career
Lesch leads a private life, avoiding both public and media attention. On 23 December 2013, however, she granted a very rare interview to the Tagblatt der Stadt Zürich – a paper from her hometown of Zürich – in commemoration of the 40th anniversary of Drei Haselnüsse für Aschenbrödel, where she spoke about both the film, as well as memories of her childhood in Switzerland. Lesch also spoke of her only visit to Zürich in 1991, after the fall of the East Bloc when she was free to travel, and the enjoyment she felt in revisiting old haunts from her childhood after an absence of some forty-four years.
Filmography
Film and television
1953: Matthias Löffelchen, der Osterhase, i.e. Matthias Rabbit-Ears, The Easter Bunny, (a made for Television Movie).
1959: Eine alte Liebe, i.e. An Old Love, in the role of ‘Sabine Schröder’.
1960: Das Zaubermännchen, i.e. The Magic Little Man, an adaptation of Grimm's Rumpelstiltskin, in the role of ‘Marie’, the miller's daughter.
1960: Morgen Abend um sieben, i.e. Tomorrow Evening at Seven, (a made for Television Movie).
1961: Der Tod hat ein Gesicht, i.e. Death has a Face, as the young nun and hospital nurse.
1968: Die Toten bleiben jung, i.e. The Dead Remain Young, in the role of ‘Lenore’.
1970: Die Nächte des Zorns, i.e. Nights of Wrath, in the role of ‘Louise Cordeau’ (a made for Television Movie), directed by her husband Hans-Dieter Mäde of DEFA.
1971: KLK an PTX – Die Rote Kapelle, i.e. (KLK Calling PTZ – The Red Orchestra), in the historical role of anti-Nazi and resistance fighter, physician Elfriede Paul.
1973: Drei Haselnüsse für Aschenbrödel, i.e. (Three Gifts for Cinderella) in the role of ‘the Queen’.
1974: Die Geisterfalle, i.e. The Ghost Trap, (a made for Television Movie), again directed by her husband Hans-Dieter Mäde of DEFA.
References
External links
Drei Haselnüsse für Aschenbrödel: Karin Lesch
DEFA Sternstunden: Karin Lesch (web.archive.org)
Drei Haselnüsse für Aschenbrödel
Märchenkönigin mit Zürcher Wurzeln: Karin Lesch im Weihnachtsklassiker «Drei Haselnüsse für Aschenbrödel». (web.archive.org)
1935 births
Living people
German people of Austrian descent
Actors from Zürich
Swiss stage actresses
Swiss film actresses
Swiss television actresses
German stage actresses
German film actresses
German television actresses
East German actors
East German women
Immigrants to East Germany
20th-century German women
|
Paraspathulina apicomacula is a species of tephritid or fruit flies in the genus Paraspathulina of the family Tephritidae.
Distribution
Australia.
References
Tephritinae
Insects described in 1996
Diptera of Australasia
|
```smalltalk
using System.Collections;
using System.Collections.Generic;
namespace Xamarin.Forms
{
public class DataPackagePropertySetView : IReadOnlyDictionary<string, object>
{
public DataPackagePropertySet _dataPackagePropertySet;
public DataPackagePropertySetView(DataPackagePropertySet dataPackagePropertySet)
{
_ = dataPackagePropertySet ?? throw new System.ArgumentNullException(nameof(dataPackagePropertySet));
_dataPackagePropertySet = dataPackagePropertySet;
}
public object this[string key] => _dataPackagePropertySet[key];
public IEnumerable<string> Keys => _dataPackagePropertySet.Keys;
public IEnumerable<object> Values => _dataPackagePropertySet.Values;
public int Count => _dataPackagePropertySet.Count;
public bool ContainsKey(string key) => _dataPackagePropertySet.ContainsKey(key);
public IEnumerator<KeyValuePair<string, object>> GetEnumerator() => _dataPackagePropertySet.GetEnumerator();
public bool TryGetValue(string key, out object value) => _dataPackagePropertySet.TryGetValue(key, out value);
IEnumerator IEnumerable.GetEnumerator() => _dataPackagePropertySet.GetEnumerator();
}
}
```
|
Wallace F. Gabler III (born June 9, 1944) is a retired professional American football player. He was the starting quarterback for the 1965 Michigan Wolverines football team and played seven seasons in the Canadian Football League (CFL) as the starting quarterback for the Toronto Argonauts (1966–1969), Winnipeg Blue Bombers (1969–1970), and Hamilton Tiger-Cats (1970–1972). In seven years in the CFL, Gabler passed for 13,080 yards and 61 touchdowns.
Early years
Gabler was born in Portsmouth, Ohio, and attended Kimball High School in Royal Oak, Michigan. He attended the New Mexico Military Institute (NMMI) after graduating from high school, with the hopes of qualifying for the United States Naval Academy the following year. At NMMI, Gabler broke Roger Staubach's school records for most passing touchdowns in a game and completion percentage and was selected as a junior college All-American.
University of Michigan
Gabler transferred to the University of Michigan in 1963 without a scholarship and played for the freshman football team. As a junior, Gabler received a tuition-only scholarship, and appeared as a backup to Bob Timberlake on the 1964 Michigan team that won the Big Ten Conference championship.
As a senior in 1965, Gabler began the season as a backup to Dick Vidmer. Gabler got his first start in the second game of the season against Cal. Gabler started five games for the 1965 Wolverines and completed 58 of 126 passes for 825 yards, four touchdowns and two interceptions. He also gained 149 rushing yards.
Following his senior year, Gabler played in the 1965 Blue–Gray Football Classic.
Gabler's younger brother, John H. Gabler, also played football at Michigan, as a halfback from 1966 to 1969.
Canadian Football League
Gabler played seven years in the Canadian Football League after graduating from Michigan in 1966. He began his professional football career as the starting quarterback for the Toronto Argonauts. As a rookie, he passed for 1,659 yards and rushed for another 373 yards. In his history of the Argonauts, Craig Wallace wrote: "In 1966, the offence was based on Wally Gabler running around the backfield looking for open receivers -- and when he couldn't find one, running for his life." Gabler remained with the Argonauts for three years. He had his best year in 1968 when he completed 205 of 365 passes for 3,242 yards and 18 touchdowns. He also rushed for 458 yards and four touchdowns for the 1968 Argonauts.
Interviewed in 1968, Gabler described his adjustment to the Canadian rules: "Of course, changing to three downs makes some difference. You have to be accustomed to putting the ball in the air more in Canada but the rules compensate."
In August 1969, Gabler was traded to the Winnipeg Blue Bombers in exchange for Dave Raimey. Gabler gained 2,288 passing yards for the Blue Bombers in 1969.
During the 1970 season, Gabler was traded to the Hamilton Tiger-Cats. He passed for 1,908 yards for the Tiger-Cats in 1970. He led the team to the Eastern regular season championship in 1970. In November 1970, the Canadian Press published a feature story about Gabler's role in leading the Tiger-Cats. The article described Gabler as "scholarly" and "soft-spoken" and noted:
Wally Gabler's shoulders will be carrying the lion's share of the load Sunday when he directs the Tiger-Cats in the first game of the Eastern Football Conference final against the Montreal Alouettes. And it's ironic in view of the nomadic life the 26-year-old Royal Oak, Mich. native has experienced in his short career in the Canadian Football League. ... Arriving in late September to fill in at quarterback for injured Joe Zuger, Gabler quickly picked up the intricate Hamilton offence and was one of the instruments in the Tiger-Cats' first place finish.
During the off-seasons from 1967 to 1971, Gabler sold securities for Richardson Securities of Canada.
In August 1972, Gabler returned to the Toronto Argonauts, who lost their quarterback Joe Theismann in the season opener. Gabler concluded his playing career in Toronto during the 1972 season, passing for 1,689 yards in 10 games.
In seven years in the CFL, Gabler completed 848 of 1,690 passes for 13,080 yards, 61 touchdowns and 118 interceptions.
Later years
Gabler was a colour commentator on CTV in 1974.
References
1943 births
Players of Canadian football from Michigan
Canadian football quarterbacks
Toronto Argonauts players
Winnipeg Blue Bombers players
Hamilton Tiger-Cats players
American football quarterbacks
Michigan Wolverines football players
Living people
People from Portsmouth, Ohio
Sportspeople from Royal Oak, Michigan
Players of American football from Michigan
Players of American football from Ohio
Canadian Football League announcers
Players of Canadian football from Ohio
|
```objective-c
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_OBJECTS_JS_WEAK_REFS_H_
#define V8_OBJECTS_JS_WEAK_REFS_H_
#include "src/objects/js-objects.h"
#include "torque-generated/bit-fields-tq.h"
// Has to be the last include (doesn't have include guards):
#include "src/objects/object-macros.h"
namespace v8 {
namespace internal {
class NativeContext;
class WeakCell;
// FinalizationRegistry object from the JS Weak Refs spec proposal:
// path_to_url
class JSFinalizationRegistry : public JSObject {
public:
DECL_PRINTER(JSFinalizationRegistry)
EXPORT_DECL_VERIFIER(JSFinalizationRegistry)
DECL_CAST(JSFinalizationRegistry)
DECL_ACCESSORS(native_context, NativeContext)
DECL_ACCESSORS(cleanup, Object)
DECL_ACCESSORS(active_cells, HeapObject)
DECL_ACCESSORS(cleared_cells, HeapObject)
DECL_ACCESSORS(key_map, Object)
DECL_ACCESSORS(next_dirty, Object)
DECL_INT_ACCESSORS(flags)
DECL_BOOLEAN_ACCESSORS(scheduled_for_cleanup)
class BodyDescriptor;
inline static void Register(
Handle<JSFinalizationRegistry> finalization_registry,
Handle<JSReceiver> target, Handle<Object> holdings, Handle<Object> key,
Isolate* isolate);
inline static bool Unregister(
Handle<JSFinalizationRegistry> finalization_registry,
Handle<JSReceiver> unregister_token, Isolate* isolate);
// RemoveUnregisterToken is called from both Unregister and during GC. Since
// it modifies slots in key_map and WeakCells and the normal write barrier is
// disabled during GC, we need to tell the GC about the modified slots via the
// gc_notify_updated_slot function.
template <typename MatchCallback, typename GCNotifyUpdatedSlotCallback>
inline bool RemoveUnregisterToken(
JSReceiver unregister_token, Isolate* isolate,
MatchCallback match_callback,
GCNotifyUpdatedSlotCallback gc_notify_updated_slot);
// Returns true if the cleared_cells list is non-empty.
inline bool NeedsCleanup() const;
// Remove the already-popped weak_cell from its unregister token linked list,
// as well as removing the entry from the key map if it is the only WeakCell
// with its unregister token. This method cannot GC and does not shrink the
// key map. Asserts that weak_cell has a non-undefined unregister token.
//
// It takes raw Addresses because it is called from CSA and Torque.
V8_EXPORT_PRIVATE static void RemoveCellFromUnregisterTokenMap(
Isolate* isolate, Address raw_finalization_registry,
Address raw_weak_cell);
// Layout description.
DEFINE_FIELD_OFFSET_CONSTANTS(
JSObject::kHeaderSize, TORQUE_GENERATED_JS_FINALIZATION_REGISTRY_FIELDS)
// Bitfields in flags.
DEFINE_TORQUE_GENERATED_FINALIZATION_REGISTRY_FLAGS()
OBJECT_CONSTRUCTORS(JSFinalizationRegistry, JSObject);
};
// Internal object for storing weak references in JSFinalizationRegistry.
class WeakCell : public TorqueGeneratedWeakCell<WeakCell, HeapObject> {
public:
DECL_PRINTER(WeakCell)
EXPORT_DECL_VERIFIER(WeakCell)
class BodyDescriptor;
// Provide relaxed load access to target field.
inline HeapObject relaxed_target() const;
// Nullify is called during GC and it modifies the pointers in WeakCell and
// JSFinalizationRegistry. Thus we need to tell the GC about the modified
// slots via the gc_notify_updated_slot function. The normal write barrier is
// not enough, since it's disabled before GC.
template <typename GCNotifyUpdatedSlotCallback>
inline void Nullify(Isolate* isolate,
GCNotifyUpdatedSlotCallback gc_notify_updated_slot);
inline void RemoveFromFinalizationRegistryCells(Isolate* isolate);
TQ_OBJECT_CONSTRUCTORS(WeakCell)
};
class JSWeakRef : public TorqueGeneratedJSWeakRef<JSWeakRef, JSObject> {
public:
DECL_PRINTER(JSWeakRef)
EXPORT_DECL_VERIFIER(JSWeakRef)
class BodyDescriptor;
TQ_OBJECT_CONSTRUCTORS(JSWeakRef)
};
} // namespace internal
} // namespace v8
#include "src/objects/object-macros-undef.h"
#endif // V8_OBJECTS_JS_WEAK_REFS_H_
```
|
Toby Swift is a radio drama director and producer for BBC Radio. His numerous credits, from 1999 to 2011, include the crime dramas The Recall Man and Trueman and Riley. He also directs contemporary and periodic radio dramas.
He won the Prix Italia for Adapted Drama in 2004 for M, and again in 2005 for My Arm and for a third time in 2007 for Metropolis. The Loop won a Bronze Sony Radio Academy Award for Best Drama Production in 2010.
Radio plays
Notes:
Sources:
Toby Swift's radio play listing at Diversity website
Toby Swift's radio play listing at RadioListings website
References
BBC Radio drama directors
BBC radio producers
Living people
Prix Italia winners
Year of birth missing (living people)
|
Clipping is a penalty in the sport of ice hockey. It is generally recognized as hitting an opposing player at or below the other player's knees. Clipping should not be confused with hip checking, where one player hits an opponent with his hips, although occasionally a hip check will result in a clipping call. A player is generally assessed a minor penalty for clipping, unless an injury is caused, in which case a major penalty and a misconduct or game misconduct will result. It is one of the most rarely called penalties in the sport.
Historically, players penalized for clipping are labeled as "dirty" players, as clipping is nearly always viewed as attempt to injure an opponent.
Additionally, Rule 639(a) of the USA Hockey Rulebook states:
“Any player who deliberately leaves his feet and contacts an opponent with any part of his body thereby causing the opponent to trip or fall shall be assessed a minor penalty (Clipping).(Note 3) This rule does not apply to a player who has dropped to his knee(s) to block a shot.”
History
Clipping was instituted as a rule in the National Hockey League in 2002, following a low hit on 26 April by Toronto Maple Leafs forward Darcy Tucker on New York Islanders captain Michael Peca. The hit occurred during a Stanley Cup playoff matchup between the two teams, and Peca was unable to play for the remainder of the season. When the NHL added the new rule, the videotape distributed by the league showed the hit as an example of a clipping penalty that would result in an automatic game misconduct.
External links
NHL Rulebook entry on clipping
Ice hockey penalties
Ice hockey terminology
|
Cássio Motta (born 22 February 1960) is a former professional tennis player from Brazil. He played in the mixed doubles final of the French Open with Cláudia Monteiro in 1982.
Grand Slam mixed doubles finals
Runners-up (1)
Career finals
Doubles (10 wins, 13 losses)
Singles (1 loss)
References
External links
Brazilian male tennis players
Tennis players from São Paulo
Brazilian people of Italian descent
1960 births
Living people
|
```xml
// See LICENSE.txt for license information.
import Clipboard from '@react-native-clipboard/clipboard';
import React, {useCallback} from 'react';
import {useIntl} from 'react-intl';
import OptionItem from '@components/option_item';
import SlideUpPanelItem from '@components/slide_up_panel_item';
import {CHANNEL_INFO} from '@constants/screens';
import {SNACK_BAR_TYPE} from '@constants/snack_bar';
import {useServerUrl} from '@context/server';
import {dismissBottomSheet} from '@screens/navigation';
import {showSnackBar} from '@utils/snack_bar';
type Props = {
channelName?: string;
teamName?: string;
showAsLabel?: boolean;
testID?: string;
}
const CopyChannelLinkOption = ({channelName, teamName, showAsLabel, testID}: Props) => {
const intl = useIntl();
const serverUrl = useServerUrl();
const onCopyLink = useCallback(async () => {
Clipboard.setString(`${serverUrl}/${teamName}/channels/${channelName}`);
await dismissBottomSheet();
showSnackBar({barType: SNACK_BAR_TYPE.LINK_COPIED, sourceScreen: CHANNEL_INFO});
}, [channelName, teamName, serverUrl]);
if (showAsLabel) {
return (
<SlideUpPanelItem
onPress={onCopyLink}
text={intl.formatMessage({id: 'channel_info.copy_link', defaultMessage: 'Copy Link'})}
leftIcon='link-variant'
testID={testID}
/>
);
}
return (
<OptionItem
action={onCopyLink}
label={intl.formatMessage({id: 'channel_info.copy_link', defaultMessage: 'Copy Link'})}
icon='link-variant'
type='default'
testID={testID}
/>
);
};
export default CopyChannelLinkOption;
```
|
```ruby
# frozen_string_literal: true
require "utils"
RSpec.describe Utils do
describe ".deconstantize" do
it "removes the rightmost segment from the constant expression in the string" do
expect(described_class.deconstantize("Net::HTTP")).to eq("Net")
expect(described_class.deconstantize("::Net::HTTP")).to eq("::Net")
expect(described_class.deconstantize("String")).to eq("")
expect(described_class.deconstantize("::String")).to eq("")
end
it "returns an empty string if the namespace is empty" do
expect(described_class.deconstantize("")).to eq("")
expect(described_class.deconstantize("::")).to eq("")
end
end
describe ".demodulize" do
it "removes the module part from the expression in the string" do
expect(described_class.demodulize("Foo::Bar")).to eq("Bar")
end
it "returns the string if it does not contain a module expression" do
expect(described_class.demodulize("FooBar")).to eq("FooBar")
end
it "returns an empty string if the namespace is empty" do
expect(described_class.demodulize("")).to eq("")
expect(described_class.demodulize("::")).to eq("")
end
end
specify ".parse_author!" do
parse_error_msg = /Unable to parse name and email/
expect(described_class.parse_author!("John Doe <john.doe@example.com>"))
.to eq({ name: "John Doe", email: "john.doe@example.com" })
expect { described_class.parse_author!("") }
.to raise_error(parse_error_msg)
expect { described_class.parse_author!("John Doe") }
.to raise_error(parse_error_msg)
expect { described_class.parse_author!("<john.doe@example.com>") }
.to raise_error(parse_error_msg)
end
describe ".pluralize" do
it "combines the stem with the default suffix based on the count" do
expect(described_class.pluralize("foo", 0)).to eq("foos")
expect(described_class.pluralize("foo", 1)).to eq("foo")
expect(described_class.pluralize("foo", 2)).to eq("foos")
end
it "combines the stem with the singular suffix based on the count" do
expect(described_class.pluralize("foo", 0, singular: "o")).to eq("foos")
expect(described_class.pluralize("foo", 1, singular: "o")).to eq("fooo")
expect(described_class.pluralize("foo", 2, singular: "o")).to eq("foos")
end
it "combines the stem with the plural suffix based on the count" do
expect(described_class.pluralize("foo", 0, plural: "es")).to eq("fooes")
expect(described_class.pluralize("foo", 1, plural: "es")).to eq("foo")
expect(described_class.pluralize("foo", 2, plural: "es")).to eq("fooes")
end
it "combines the stem with the singular and plural suffix based on the count" do
expect(described_class.pluralize("foo", 0, singular: "o", plural: "es")).to eq("fooes")
expect(described_class.pluralize("foo", 1, singular: "o", plural: "es")).to eq("fooo")
expect(described_class.pluralize("foo", 2, singular: "o", plural: "es")).to eq("fooes")
end
it "includes the count when requested" do
expect(described_class.pluralize("foo", 0, include_count: true)).to eq("0 foos")
expect(described_class.pluralize("foo", 1, include_count: true)).to eq("1 foo")
expect(described_class.pluralize("foo", 2, include_count: true)).to eq("2 foos")
end
end
describe ".underscore" do
# commented out entries require acronyms inflections
let(:words) do
[
["API", "api"],
["APIController", "api_controller"],
["Nokogiri::HTML", "nokogiri/html"],
# ["HTTPAPI", "http_api"],
["HTTP::Get", "http/get"],
["SSLError", "ssl_error"],
# ["RESTful", "restful"],
# ["RESTfulController", "restful_controller"],
# ["Nested::RESTful", "nested/restful"],
# ["IHeartW3C", "i_heart_w3c"],
# ["PhDRequired", "phd_required"],
# ["IRoRU", "i_ror_u"],
# ["RESTfulHTTPAPI", "restful_http_api"],
# ["HTTP::RESTful", "http/restful"],
# ["HTTP::RESTfulAPI", "http/restful_api"],
# ["APIRESTful", "api_restful"],
["Capistrano", "capistrano"],
["CapiController", "capi_controller"],
["HttpsApis", "https_apis"],
["Html5", "html5"],
["Restfully", "restfully"],
["RoRails", "ro_rails"],
]
end
it "converts strings to underscore case" do
words.each do |camel, under|
expect(described_class.underscore(camel)).to eq(under)
expect(described_class.underscore(under)).to eq(under)
end
end
end
end
```
|
```smalltalk
using FrameWork.SDKManager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
/// <summary>
///
/// </summary>
public class PaymentVerificationManager
{
public static CallBack<PayResult> onVerificationResultCallBack;
private static PaymentVerificationInterface verificationInterface;
public static void Init(PaymentVerificationInterface verificationInterface)
{
PaymentVerificationManager.verificationInterface = verificationInterface;
verificationInterface.Init();
SDKManager.PayCallBack += PayCallBack;
}
private static void PayCallBack(OnPayInfo info)
{
if (info.isSuccess)
{
//if(string.IsNullOrEmpty(info.receipt))
//{
// info.receipt = Guid.NewGuid().ToString();
//}
verificationInterface.CheckRecipe(info);
}
else
{
Debug.Log("PaymentVerificationManager info.goodsId " + info.goodsId);
int code = info.isSuccess ? 0 : -1;
OnVerificationResult(code, info.goodsId,false,info.receipt,info.error,info.storeName);
}
}
/// <summary>
///
/// </summary>
/// <param name="code"></param>
/// <param name="goodsID">ID</param>
/// <param name="repeatReceipt"></param>
/// <param name="receipt"></param>
public static void OnVerificationResult(int code,string goodsID, bool repeatReceipt,string receipt,string error,StoreName storeName)
{
try
{
if (onVerificationResultCallBack != null)
{
PayResult result = new PayResult(code,goodsID,error,storeName);
Debug.Log(" code " + code + " goodsID " + goodsID);
onVerificationResultCallBack(result);
}
}
catch (Exception e)
{
Debug.LogError(e);
}
if (code == 0 || code == ErrorCodeDefine.StorePay_RepeatReceipt || repeatReceipt)
{
Debug.Log(""+ goodsID);
SDKManager.ConfirmPay(storeName.ToString(), goodsID, receipt );
}
//
if (code!=0)
{
Debug.LogError(" goodID:" + goodsID);
}
}
}
```
|
```css
Horizontal centering fluid blocks
Vertical centering with `margin-top`
Clearfix for layouts
Equal width table cells
Avoid margin hacks with flexbox
```
|
Balaenula is an extinct genus of cetacean.
Taxonomy
Cladistic analyses of fossils and extant balaenids place Balaenula as the sister taxon of right whales in a clade separate from the bowhead whale.
Fossil records
This genus is known in the fossil records from the Neogene to the Quaternary (age range: from 11.608 to 1.806 million years ago). Fossils are found in the marine strata of Italy, United Kingdom, United States, the Netherlands, France and Japan.
The most complete specimen known from the U.S. (as well as the only one on display in North America) was found at Lake Waccamaw, North Carolina in 2008. The whale's skull was excavated from the limestone outcropping by the state's Underwater Archaeology Branch, prepared, and permanently displayed at the Lake Waccamaw Depot Museum starting 2012.
Species
There are two currently recognized species of Balaenula:
†Balaenula balaenopsis Van Beneden, 1872 (Type)
†Balaenula astensis Trevisan, 1942 (from Italy)
B. astensis was quite similar to the living right whale (Eubalaena glacialis) but much smaller, reaching a length of about . This species lived around four million years ago. Fossils have been found near Asti (Northern Italy), in a Zanclean/Piacenzian marine sandstone.
The only known specimen of B. balaenopsis was discovered in Belgium in the late 1800s.
An unnamed species from Japan (represented by a partial skeleton) is also known.
References
Prehistoric cetacean genera
Fossil taxa described in 1872
Pliocene cetaceans
Balaenidae
|
```go
package rfc
/*
*
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
*/
import (
"github.com/zmap/zcrypto/x509"
"github.com/zmap/zlint/v3/lint"
"github.com/zmap/zlint/v3/util"
)
type utcNoSecond struct{}
/************************************************************************
4.1.2.5.1. UTCTime
The universal time type, UTCTime, is a standard ASN.1 type intended
for representation of dates and time. UTCTime specifies the year
through the two low-order digits and time is specified to the
precision of one minute or one second. UTCTime includes either Z
(for Zulu, or Greenwich Mean Time) or a time differential.
For the purposes of this profile, UTCTime values MUST be expressed in
Greenwich Mean Time (Zulu) and MUST include seconds (i.e., times are
YYMMDDHHMMSSZ), even where the number of seconds is zero. Conforming
systems MUST interpret the year field (YY) as follows:
Where YY is greater than or equal to 50, the year SHALL be
interpreted as 19YY; and
Where YY is less than 50, the year SHALL be interpreted as 20YY.
************************************************************************/
func init() {
lint.RegisterLint(&lint.Lint{
Name: "e_utc_time_does_not_include_seconds",
Description: "UTCTime values MUST include seconds",
Citation: "RFC 5280: 4.1.2.5.1",
Source: lint.RFC5280,
EffectiveDate: util.RFC2459Date,
Lint: &utcNoSecond{},
})
}
func (l *utcNoSecond) Initialize() error {
return nil
}
func (l *utcNoSecond) CheckApplies(c *x509.Certificate) bool {
firstDate, secondDate := util.GetTimes(c)
beforeTag, afterTag := util.FindTimeType(firstDate, secondDate)
date1Utc := beforeTag == 23
date2Utc := afterTag == 23
return date1Utc || date2Utc
}
func (l *utcNoSecond) Execute(c *x509.Certificate) *lint.LintResult {
date1, date2 := util.GetTimes(c)
beforeTag, afterTag := util.FindTimeType(date1, date2)
date1Utc := beforeTag == 23
date2Utc := afterTag == 23
if date1Utc {
if len(date1.Bytes) != 13 && len(date1.Bytes) != 17 {
return &lint.LintResult{Status: lint.Error}
}
}
if date2Utc {
if len(date2.Bytes) != 13 && len(date2.Bytes) != 17 {
return &lint.LintResult{Status: lint.Error}
}
}
return &lint.LintResult{Status: lint.Pass}
}
```
|
Point Pleasant may refer to:
Places
In Canada
Point Pleasant Park, Halifax, Nova Scotia
In England
Point Pleasant (Wallsend), Tyne and Wear
In the United States
Point Pleasant Township, Warren County, Illinois
Point Pleasant, Indiana
Point Pleasant, New Jersey
Point Pleasant Beach, New Jersey
Point Pleasant, Maryland, a neighborhood of Glen Burnie, Maryland
Point Pleasant, Missouri, in New Madrid County, Missouri
Point Pleasant, Ohio
Point Pleasant, Pennsylvania
Point Pleasant, West Virginia
Other
Point Pleasant (TV series), a 2005 Fox television show set in a fictionalized version of the New Jersey town
Point Pleasant Battleground, near Point Pleasant, West Virginia, and site of a 1774 battle between Virginia militia and Native Americans
"Point Pleasant", a song by God Is an Astronaut from the 2002 album The End of the Beginning
See also
Point Pleasant Historic District (disambiguation)
Pleasant Point (disambiguation)
Point Pleasant High School (disambiguation)
|
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="shortcut icon" type="image/png" href="../assets/img/favicon.ico">
<link rel="stylesheet" href="../assets/lib/cssgrids.css">
<link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
<script src="../assets/lib/yui-min.js"></script>
<script src="../assets/js/api-prettify.js"></script>
<script src="../assets/js/api-filter.js"></script>
<script src="../assets/js/api-list.js"></script>
<script src="../assets/js/api-search.js"></script>
<script src="../assets/js/api-docs.js"></script>
<title>nunuStudio Postprocessing</title>
</head>
<body class="yui3-skin-sam">
<div id="doc">
<div id="hd" class="yui3-g header">
<div class="yui3-u-3-4">
<h1><a href="../index.html"><img src="../assets/img/logo.png" title=""></a></h1>
</div>
</div>
<div id="bd" class="yui3-g">
<div class="yui3-u-1-4">
<div id="docs-sidebar" class="sidebar">
<div id="api-list">
<h2 class="off-left">APIs</h2>
<div id="api-tabview" class="tabview">
<div id="api-tabview-filter">
<input type="search" id="api-filter" placeholder="Type to filter APIs">
</div>
<ul class="tabs">
<li><a href="#api-classes">Classes</a></li>
<li><a href="#api-modules">Modules</a></li>
</ul>
<div id="api-tabview-panel">
<ul id="api-classes" class="apis classes">
<li><a href="../classes/AfterimagePass.html">AfterimagePass</a></li>
<li><a href="../classes/AmbientLight.html">AmbientLight</a></li>
<li><a href="../classes/AnimationMixer.html">AnimationMixer</a></li>
<li><a href="../classes/AnimationTimer.html">AnimationTimer</a></li>
<li><a href="../classes/App.html">App</a></li>
<li><a href="../classes/ARHandler.html">ARHandler</a></li>
<li><a href="../classes/ArraybufferUtils.html">ArraybufferUtils</a></li>
<li><a href="../classes/Audio.html">Audio</a></li>
<li><a href="../classes/AudioEmitter.html">AudioEmitter</a></li>
<li><a href="../classes/AudioLoader.html">AudioLoader</a></li>
<li><a href="../classes/Base64Utils.html">Base64Utils</a></li>
<li><a href="../classes/BaseNode.html">BaseNode</a></li>
<li><a href="../classes/BillboardGroup.html">BillboardGroup</a></li>
<li><a href="../classes/BloomPass.html">BloomPass</a></li>
<li><a href="../classes/BokehPass.html">BokehPass</a></li>
<li><a href="../classes/BufferUtils.html">BufferUtils</a></li>
<li><a href="../classes/ByteArrayUtils.html">ByteArrayUtils</a></li>
<li><a href="../classes/CanvasSprite.html">CanvasSprite</a></li>
<li><a href="../classes/CanvasTexture.html">CanvasTexture</a></li>
<li><a href="../classes/CapsuleBufferGeometry.html">CapsuleBufferGeometry</a></li>
<li><a href="../classes/ColorifyPass.html">ColorifyPass</a></li>
<li><a href="../classes/CompressedTexture.html">CompressedTexture</a></li>
<li><a href="../classes/CopyPass.html">CopyPass</a></li>
<li><a href="../classes/CSS3DObject.html">CSS3DObject</a></li>
<li><a href="../classes/CSS3DRenderer.html">CSS3DRenderer</a></li>
<li><a href="../classes/CSS3DSprite.html">CSS3DSprite</a></li>
<li><a href="../classes/CubeCamera.html">CubeCamera</a></li>
<li><a href="../classes/CubeTexture.html">CubeTexture</a></li>
<li><a href="../classes/DataTexture.html">DataTexture</a></li>
<li><a href="../classes/DirectionalLight.html">DirectionalLight</a></li>
<li><a href="../classes/DirectionalLightCSM.html">DirectionalLightCSM</a></li>
<li><a href="../classes/DotScreenPass.html">DotScreenPass</a></li>
<li><a href="../classes/EffectComposer.html">EffectComposer</a></li>
<li><a href="../classes/EventManager.html">EventManager</a></li>
<li><a href="../classes/FileSystem.html">FileSystem</a></li>
<li><a href="../classes/FilmPass.html">FilmPass</a></li>
<li><a href="../classes/FirstPersonControls.html">FirstPersonControls</a></li>
<li><a href="../classes/Fog.html">Fog</a></li>
<li><a href="../classes/Font.html">Font</a></li>
<li><a href="../classes/FontLoader.html">FontLoader</a></li>
<li><a href="../classes/FXAAPass.html">FXAAPass</a></li>
<li><a href="../classes/Gamepad.html">Gamepad</a></li>
<li><a href="../classes/GeometryLoader.html">GeometryLoader</a></li>
<li><a href="../classes/Group.html">Group</a></li>
<li><a href="../classes/Gyroscope.html">Gyroscope</a></li>
<li><a href="../classes/HemisphereLight.html">HemisphereLight</a></li>
<li><a href="../classes/HTMLView.html">HTMLView</a></li>
<li><a href="../classes/HueSaturationPass.html">HueSaturationPass</a></li>
<li><a href="../classes/Image.html">Image</a></li>
<li><a href="../classes/ImageLoader.html">ImageLoader</a></li>
<li><a href="../classes/InstancedMesh.html">InstancedMesh</a></li>
<li><a href="../classes/Key.html">Key</a></li>
<li><a href="../classes/Keyboard.html">Keyboard</a></li>
<li><a href="../classes/LegacyGeometryLoader.html">LegacyGeometryLoader</a></li>
<li><a href="../classes/LensFlare.html">LensFlare</a></li>
<li><a href="../classes/LightProbe.html">LightProbe</a></li>
<li><a href="../classes/LocalStorage.html">LocalStorage</a></li>
<li><a href="../classes/Material.html">Material</a></li>
<li><a href="../classes/MaterialLoader.html">MaterialLoader</a></li>
<li><a href="../classes/MathUtils.html">MathUtils</a></li>
<li><a href="../classes/Mesh.html">Mesh</a></li>
<li><a href="../classes/Model.html">Model</a></li>
<li><a href="../classes/Mouse.html">Mouse</a></li>
<li><a href="../classes/NodeScript.html">NodeScript</a></li>
<li><a href="../classes/Nunu.html">Nunu</a></li>
<li><a href="../classes/Object3D.html">Object3D</a></li>
<li><a href="../classes/ObjectLoader.html">ObjectLoader</a></li>
<li><a href="../classes/ObjectUtils.html">ObjectUtils</a></li>
<li><a href="../classes/OperationNode.html">OperationNode</a></li>
<li><a href="../classes/OrbitControls.html">OrbitControls</a></li>
<li><a href="../classes/OrthographicCamera.html">OrthographicCamera</a></li>
<li><a href="../classes/ParametricBufferGeometry.html">ParametricBufferGeometry</a></li>
<li><a href="../classes/ParticleDistributions.html">ParticleDistributions</a></li>
<li><a href="../classes/ParticleEmitter.html">ParticleEmitter</a></li>
<li><a href="../classes/ParticleEmitterControl.html">ParticleEmitterControl</a></li>
<li><a href="../classes/ParticleEmitterControlOptions.html">ParticleEmitterControlOptions</a></li>
<li><a href="../classes/ParticleGroup.html">ParticleGroup</a></li>
<li><a href="../classes/Pass.html">Pass</a></li>
<li><a href="../classes/PerspectiveCamera.html">PerspectiveCamera</a></li>
<li><a href="../classes/PhysicsGenerator.html">PhysicsGenerator</a></li>
<li><a href="../classes/PhysicsObject.html">PhysicsObject</a></li>
<li><a href="../classes/PointLight.html">PointLight</a></li>
<li><a href="../classes/PositionalAudio.html">PositionalAudio</a></li>
<li><a href="../classes/Program.html">Program</a></li>
<li><a href="../classes/PythonScript.html">PythonScript</a></li>
<li><a href="../classes/RectAreaLight.html">RectAreaLight</a></li>
<li><a href="../classes/RendererConfiguration.html">RendererConfiguration</a></li>
<li><a href="../classes/RendererState.html">RendererState</a></li>
<li><a href="../classes/RenderPass.html">RenderPass</a></li>
<li><a href="../classes/Resource.html">Resource</a></li>
<li><a href="../classes/ResourceManager.html">ResourceManager</a></li>
<li><a href="../classes/RoundedBoxBufferGeometry.html">RoundedBoxBufferGeometry</a></li>
<li><a href="../classes/Scene.html">Scene</a></li>
<li><a href="../classes/Script.html">Script</a></li>
<li><a href="../classes/ShaderAttribute.html">ShaderAttribute</a></li>
<li><a href="../classes/ShaderPass.html">ShaderPass</a></li>
<li><a href="../classes/ShaderUtils.html">ShaderUtils</a></li>
<li><a href="../classes/SimplexNoise.html">SimplexNoise</a></li>
<li><a href="../classes/Skeleton.html">Skeleton</a></li>
<li><a href="../classes/SkinnedMesh.html">SkinnedMesh</a></li>
<li><a href="../classes/Sky.html">Sky</a></li>
<li><a href="../classes/SobelPass.html">SobelPass</a></li>
<li><a href="../classes/SpineAnimation.html">SpineAnimation</a></li>
<li><a href="../classes/SpineTexture.html">SpineTexture</a></li>
<li><a href="../classes/SpotLight.html">SpotLight</a></li>
<li><a href="../classes/Sprite.html">Sprite</a></li>
<li><a href="../classes/SpriteSheetTexture.html">SpriteSheetTexture</a></li>
<li><a href="../classes/SSAONOHPass.html">SSAONOHPass</a></li>
<li><a href="../classes/SSAOPass.html">SSAOPass</a></li>
<li><a href="../classes/SSAOShader.html">SSAOShader</a></li>
<li><a href="../classes/TargetConfig.html">TargetConfig</a></li>
<li><a href="../classes/TechnicolorPass.html">TechnicolorPass</a></li>
<li><a href="../classes/TerrainBufferGeometry.html">TerrainBufferGeometry</a></li>
<li><a href="../classes/TextBitmap.html">TextBitmap</a></li>
<li><a href="../classes/TextFile.html">TextFile</a></li>
<li><a href="../classes/TextMesh.html">TextMesh</a></li>
<li><a href="../classes/TextSprite.html">TextSprite</a></li>
<li><a href="../classes/Texture.html">Texture</a></li>
<li><a href="../classes/TextureLoader.html">TextureLoader</a></li>
<li><a href="../classes/Timer.html">Timer</a></li>
<li><a href="../classes/TizenKeyboard.html">TizenKeyboard</a></li>
<li><a href="../classes/Tree.html">Tree</a></li>
<li><a href="../classes/TreeUtils.html">TreeUtils</a></li>
<li><a href="../classes/TwistModifier.html">TwistModifier</a></li>
<li><a href="../classes/TypedArrayHelper.html">TypedArrayHelper</a></li>
<li><a href="../classes/UnitConverter.html">UnitConverter</a></li>
<li><a href="../classes/UnrealBloomPass.html">UnrealBloomPass</a></li>
<li><a href="../classes/Video.html">Video</a></li>
<li><a href="../classes/VideoLoader.html">VideoLoader</a></li>
<li><a href="../classes/VideoStream.html">VideoStream</a></li>
<li><a href="../classes/VideoTexture.html">VideoTexture</a></li>
<li><a href="../classes/Viewport.html">Viewport</a></li>
<li><a href="../classes/VRHandler.html">VRHandler</a></li>
<li><a href="../classes/WebcamTexture.html">WebcamTexture</a></li>
<li><a href="../classes/WorkerPool.html">WorkerPool</a></li>
<li><a href="../classes/WorkerTask.html">WorkerTask</a></li>
<li><a href="../classes/{Object} ParticleGroupOptions.html">{Object} ParticleGroupOptions</a></li>
</ul>
<ul id="api-modules" class="apis modules">
<li><a href="../modules/Animation.html">Animation</a></li>
<li><a href="../modules/Animations.html">Animations</a></li>
<li><a href="../modules/Audio.html">Audio</a></li>
<li><a href="../modules/BinaryUtils.html">BinaryUtils</a></li>
<li><a href="../modules/Cameras.html">Cameras</a></li>
<li><a href="../modules/Controls.html">Controls</a></li>
<li><a href="../modules/Core.html">Core</a></li>
<li><a href="../modules/Files.html">Files</a></li>
<li><a href="../modules/Input.html">Input</a></li>
<li><a href="../modules/Lights.html">Lights</a></li>
<li><a href="../modules/Loaders.html">Loaders</a></li>
<li><a href="../modules/Meshes.html">Meshes</a></li>
<li><a href="../modules/Misc.html">Misc</a></li>
<li><a href="../modules/Particles.html">Particles</a></li>
<li><a href="../modules/Physics.html">Physics</a></li>
<li><a href="../modules/Postprocessing.html">Postprocessing</a></li>
<li><a href="../modules/Resources.html">Resources</a></li>
<li><a href="../modules/Runtime.html">Runtime</a></li>
<li><a href="../modules/Script.html">Script</a></li>
<li><a href="../modules/Sprite.html">Sprite</a></li>
<li><a href="../modules/Textures.html">Textures</a></li>
<li><a href="../modules/THREE.html">THREE</a></li>
<li><a href="../modules/Utils.html">Utils</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="yui3-u-3-4">
<!--<div id="api-options">
Show:
<label for="api-show-inherited">
<input type="checkbox" id="api-show-inherited" checked>
Inherited
</label>
<label for="api-show-protected">
<input type="checkbox" id="api-show-protected">
Protected
</label>
<label for="api-show-private">
<input type="checkbox" id="api-show-private">
Private
</label>
<label for="api-show-deprecated">
<input type="checkbox" id="api-show-deprecated">
Deprecated
</label>
</div>--> <div class="apidocs">
<div id="docs-main">
<div class="content">
<h1>Postprocessing Module</h1>
<div class="box clearfix meta">
</div>
<div class="box intro">
<p>Fast approximate anti-aliasing (FXAA) is an anti-aliasing algorithm to smooth jagged edges on post procesing effects.</p>
<p>More information about FXAA available here:</p>
<ul>
<li>https:// <a href="path_to_url">developer.download.nvidia.com/assets/gamedev/files/sdk/11/FXAA_WhitePaper.pdf</a></li>
</ul>
</div>
<div class="yui3-g">
<div class="yui3-u-1-2">
<p>This namespace provides the following classes:</p>
<ul class="module-classes">
<li class="module-class">
<a href="../classes/AfterimagePass.html">
AfterimagePass
</a>
</li>
<li class="module-class">
<a href="../classes/BloomPass.html">
BloomPass
</a>
</li>
<li class="module-class">
<a href="../classes/BokehPass.html">
BokehPass
</a>
</li>
<li class="module-class">
<a href="../classes/ColorifyPass.html">
ColorifyPass
</a>
</li>
<li class="module-class">
<a href="../classes/CopyPass.html">
CopyPass
</a>
</li>
<li class="module-class">
<a href="../classes/CSS3DObject.html">
CSS3DObject
</a>
</li>
<li class="module-class">
<a href="../classes/CSS3DRenderer.html">
CSS3DRenderer
</a>
</li>
<li class="module-class">
<a href="../classes/CSS3DSprite.html">
CSS3DSprite
</a>
</li>
<li class="module-class">
<a href="../classes/DotScreenPass.html">
DotScreenPass
</a>
</li>
<li class="module-class">
<a href="../classes/EffectComposer.html">
EffectComposer
</a>
</li>
<li class="module-class">
<a href="../classes/FilmPass.html">
FilmPass
</a>
</li>
<li class="module-class">
<a href="../classes/FXAAPass.html">
FXAAPass
</a>
</li>
<li class="module-class">
<a href="../classes/HueSaturationPass.html">
HueSaturationPass
</a>
</li>
<li class="module-class">
<a href="../classes/Pass.html">
Pass
</a>
</li>
<li class="module-class">
<a href="../classes/RendererConfiguration.html">
RendererConfiguration
</a>
</li>
<li class="module-class">
<a href="../classes/RendererState.html">
RendererState
</a>
</li>
<li class="module-class">
<a href="../classes/RenderPass.html">
RenderPass
</a>
</li>
<li class="module-class">
<a href="../classes/ShaderPass.html">
ShaderPass
</a>
</li>
<li class="module-class">
<a href="../classes/SobelPass.html">
SobelPass
</a>
</li>
<li class="module-class">
<a href="../classes/SSAONOHPass.html">
SSAONOHPass
</a>
</li>
<li class="module-class">
<a href="../classes/SSAOPass.html">
SSAOPass
</a>
</li>
<li class="module-class">
<a href="../classes/SSAOShader.html">
SSAOShader
</a>
</li>
<li class="module-class">
<a href="../classes/TechnicolorPass.html">
TechnicolorPass
</a>
</li>
<li class="module-class">
<a href="../classes/UnrealBloomPass.html">
UnrealBloomPass
</a>
</li>
</ul>
</div>
<div class="yui3-u-1-2">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
```
|
```java
/*
*
*
* 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 com.netflix.hollow.ui;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class HollowUIWebServer {
private HttpServer server;
private final HttpHandlerWithServletSupport handler;
private final int port;
private JoinableExecutorService executor;
/**
* Extends {@code ThreadPoolExecutor} to allow waiting indefinitely for termination of underlying threadpool
*/
private static class JoinableExecutorService extends ThreadPoolExecutor {
private CountDownLatch countDownLatch;
JoinableExecutorService() {
super(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
countDownLatch = new CountDownLatch(1);
}
@Override
protected void terminated() {
super.terminated();
countDownLatch.countDown();
}
void join() throws InterruptedException {
countDownLatch.await();
}
}
public HollowUIWebServer(HttpHandlerWithServletSupport handler, int port) {
this.port = port;
this.handler = handler;
this.executor = new JoinableExecutorService();
}
public void start() throws Exception {
server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext("/", this.handler);
server.setExecutor(executor);
server.start();
}
public void join() throws InterruptedException {
executor.join();
}
public void stop() throws Exception {
executor.shutdown();
try {
if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
executor.shutdownNow();
if (!executor.awaitTermination(10, TimeUnit.SECONDS))
System.err.println("Http Server ThreadPool did not terminate");
}
} catch (InterruptedException ie) {
executor.shutdownNow();
}
server.stop(0);
}
}
```
|
Kadıncık 2 hydroelectric plant is a privately owned hydroelectric power station located in Mersin Province, Turkey.
History
The plant was put into service in 1974. In 2016, within the privatization program, Kadıncık 2 plant, together with Kadıncık 1 plant, was purchased by İbrahim Çeçen holding for 864.1 million (where $1 = 2.887 ).
Technical characteristics
The installed power is 56 MW. The annual energy capacity is 307 GWh, which is equivalent to the energy requirement of 56,742 households. Kadıncık 2 power station is the fourth highest energy producer in Mersin Province.
See also
Kadıncık 1 hydroelectric power plant
References
Buildings and structures in Mersin Province
Tarsus District
Hydroelectric power stations in Turkey
Dams in Mersin Province
|
```java
/*
*
*
* 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 net.cachapa.expandablelayout.util;
import android.view.animation.Interpolator;
/**
* An {@link Interpolator} that uses a lookup table to compute an interpolation based on a
* given input.
*/
abstract class LookupTableInterpolator implements Interpolator {
private final float[] mValues;
private final float mStepSize;
public LookupTableInterpolator(float[] values) {
mValues = values;
mStepSize = 1f / (mValues.length - 1);
}
@Override
public float getInterpolation(float input) {
if (input >= 1.0f) {
return 1.0f;
}
if (input <= 0f) {
return 0f;
}
// Calculate index - We use min with length - 2 to avoid IndexOutOfBoundsException when
// we lerp (linearly interpolate) in the return statement
int position = Math.min((int) (input * (mValues.length - 1)), mValues.length - 2);
// Calculate values to account for small offsets as the lookup table has discrete values
float quantized = position * mStepSize;
float diff = input - quantized;
float weight = diff / mStepSize;
// Linearly interpolate between the table values
return mValues[position] + weight * (mValues[position + 1] - mValues[position]);
}
}
```
|
```xml
import { HasOneOptions } from 'sequelize';
import { HasAssociation } from './has-association';
import { ModelClassGetter } from '../../model/shared/model-class-getter';
import { addAssociation, getPreparedAssociationOptions } from '../shared/association-service';
import { Association } from '../shared/association';
export function HasOne<TCreationAttributes extends {}, TModelAttributes extends {}>(
associatedClassGetter: ModelClassGetter<TCreationAttributes, TModelAttributes>,
foreignKey?: string
): Function;
export function HasOne<TCreationAttributes extends {}, TModelAttributes extends {}>(
associatedClassGetter: ModelClassGetter<TCreationAttributes, TModelAttributes>,
options?: HasOneOptions
): Function;
export function HasOne<TCreationAttributes extends {}, TModelAttributes extends {}>(
associatedClassGetter: ModelClassGetter<TCreationAttributes, TModelAttributes>,
optionsOrForeignKey?: string | HasOneOptions
): Function {
return (target: any, propertyName: string) => {
const options: HasOneOptions = getPreparedAssociationOptions(optionsOrForeignKey);
if (!options.as) options.as = propertyName;
addAssociation(target, new HasAssociation(associatedClassGetter, options, Association.HasOne));
};
}
```
|
Samuel Booth may refer to:
Samuel B. Booth, bishop of the Episcopal Diocese of Vermont
Samuel Booth (politician), mayor of Brooklyn
Sam Booth, Scottish footballer
Samuel Booth, father of William Booth, founder of the Salvation Army
|
```java
Ternary operator
Updating interfaces by using `default` methods
Using bounded type parameters in generic methods
Metadata: creating a user-defined file attribute
How range operations work
```
|
```java
*
* 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.flowable.cmmn.engine.impl.behavior.impl;
import org.flowable.cmmn.api.delegate.DelegatePlanItemInstance;
import org.flowable.cmmn.api.runtime.PlanItemInstanceState;
import org.flowable.cmmn.engine.impl.agenda.CmmnEngineAgenda;
import org.flowable.cmmn.engine.impl.behavior.CmmnActivityBehavior;
import org.flowable.cmmn.engine.impl.behavior.CoreCmmnTriggerableActivityBehavior;
import org.flowable.cmmn.engine.impl.behavior.PlanItemActivityBehavior;
import org.flowable.cmmn.engine.impl.persistence.entity.PlanItemInstanceEntity;
import org.flowable.cmmn.engine.impl.util.CommandContextUtil;
import org.flowable.cmmn.engine.impl.util.ExpressionUtil;
import org.flowable.cmmn.engine.impl.util.PlanItemInstanceUtil;
import org.flowable.cmmn.model.RepetitionRule;
import org.flowable.common.engine.impl.interceptor.CommandContext;
/**
* {@link CmmnActivityBehavior} implementation for the CMMN Event Listener.
*
* @author Tijs Rademakers
*/
public class GenericEventListenerActivityBehaviour extends CoreCmmnTriggerableActivityBehavior implements PlanItemActivityBehavior {
@Override
public void onStateTransition(CommandContext commandContext, DelegatePlanItemInstance planItemInstance, String transition) {
}
@Override
public void execute(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
RepetitionRule repetitionRule = ExpressionUtil.getRepetitionRule(planItemInstanceEntity);
if (repetitionRule != null && ExpressionUtil.evaluateRepetitionRule(commandContext, planItemInstanceEntity, planItemInstanceEntity.getStagePlanItemInstanceEntity())) {
PlanItemInstanceEntity eventPlanItemInstanceEntity = PlanItemInstanceUtil.copyAndInsertPlanItemInstance(commandContext, planItemInstanceEntity, false, false);
CmmnEngineAgenda agenda = CommandContextUtil.getAgenda(commandContext);
agenda.planCreatePlanItemInstanceWithoutEvaluationOperation(eventPlanItemInstanceEntity);
agenda.planOccurPlanItemInstanceOperation(eventPlanItemInstanceEntity);
CommandContextUtil.getCmmnEngineConfiguration(commandContext).getListenerNotificationHelper().executeLifecycleListeners(
commandContext, planItemInstanceEntity, PlanItemInstanceState.ACTIVE, PlanItemInstanceState.AVAILABLE);
} else {
CommandContextUtil.getAgenda(commandContext).planOccurPlanItemInstanceOperation(planItemInstanceEntity);
}
}
@Override
public void trigger(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
execute(commandContext, planItemInstanceEntity);
}
}
```
|
```java
/*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
*
*/
package com.owncloud.android.ui.adapter;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.nextcloud.android.common.ui.theme.utils.ColorRole;
import com.nextcloud.client.preferences.AppPreferences;
import com.owncloud.android.R;
import com.owncloud.android.datamodel.ThumbnailsCacheManager;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.ui.interfaces.LocalFileListFragmentInterface;
import com.owncloud.android.utils.DisplayUtils;
import com.owncloud.android.utils.FileSortOrder;
import com.owncloud.android.utils.MimeTypeUtil;
import com.owncloud.android.utils.theme.ViewThemeUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.Executors;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
/**
* This Adapter populates a {@link RecyclerView} with all files and directories contained in a local directory
*/
public class LocalFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements FilterableListAdapter {
private static final String TAG = LocalFileListAdapter.class.getSimpleName();
private static final int showFilenameColumnThreshold = 4;
private AppPreferences preferences;
private Context mContext;
private List<File> mFiles = new ArrayList<>();
private List<File> mFilesAll = new ArrayList<>();
private boolean mLocalFolderPicker;
private boolean gridView = false;
private LocalFileListFragmentInterface localFileListFragmentInterface;
private Set<File> checkedFiles;
private ViewThemeUtils viewThemeUtils;
private boolean isWithinEncryptedFolder;
private static final int VIEWTYPE_ITEM = 0;
private static final int VIEWTYPE_FOOTER = 1;
private static final int VIEWTYPE_IMAGE = 2;
public LocalFileListAdapter(boolean localFolderPickerMode,
File directory,
LocalFileListFragmentInterface localFileListFragmentInterface,
AppPreferences preferences,
Context context,
final ViewThemeUtils viewThemeUtils,
boolean isWithinEncryptedFolder) {
this.preferences = preferences;
mContext = context;
mLocalFolderPicker = localFolderPickerMode;
this.localFileListFragmentInterface = localFileListFragmentInterface;
checkedFiles = new HashSet<>();
this.viewThemeUtils = viewThemeUtils;
this.isWithinEncryptedFolder = isWithinEncryptedFolder;
swapDirectory(directory);
}
@Override
public int getItemCount() {
return mFiles.size() + 1;
}
public int getFilesCount() {
return mFiles.size();
}
public boolean isCheckedFile(File file) {
return checkedFiles.contains(file);
}
public void removeCheckedFile(File file) {
checkedFiles.remove(file);
}
public void addCheckedFile(File file) {
checkedFiles.add(file);
}
public void addAllFilesToCheckedFiles() {
if (isWithinEncryptedFolder) {
for (File file : mFilesAll) {
if (file.isFile()) {
checkedFiles.add(file);
}
}
} else {
checkedFiles.addAll(mFiles);
}
}
public void removeAllFilesFromCheckedFiles() {
checkedFiles.clear();
}
public int getItemPosition(File file) {
return mFiles.indexOf(file);
}
public String[] getCheckedFilesPath() {
List<String> result = listFilesRecursive(checkedFiles);
Log_OC.d(TAG, "Returning " + result.size() + " selected files");
return result.toArray(new String[0]);
}
public List<String> listFilesRecursive(Collection<File> files) {
List<String> result = new ArrayList<>();
for (File file : files) {
if (file.isDirectory()) {
result.addAll(listFilesRecursive(getFiles(file)));
} else {
result.add(file.getAbsolutePath());
}
}
return result;
}
@Override
public long getItemId(int position) {
return mFiles.size() <= position ? position : -1;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if (holder instanceof LocalFileListFooterViewHolder) {
((LocalFileListFooterViewHolder) holder).footerText.setText(getFooterText());
} else {
File file = null;
if (mFiles.size() > position && mFiles.get(position) != null) {
file = mFiles.get(position);
}
if (file != null) {
File finalFile = file;
LocalFileListGridImageViewHolder gridViewHolder = (LocalFileListGridImageViewHolder) holder;
if (mLocalFolderPicker) {
gridViewHolder.itemLayout.setBackgroundColor(mContext.getResources().getColor(R.color.bg_default));
gridViewHolder.checkbox.setVisibility(View.GONE);
} else {
gridViewHolder.checkbox.setVisibility(View.VISIBLE);
if (isCheckedFile(file)) {
gridViewHolder.itemLayout.setBackgroundColor(ContextCompat.getColor(mContext, R.color.selected_item_background));
gridViewHolder.checkbox.setImageDrawable(
viewThemeUtils.platform.tintDrawable(mContext, R.drawable.ic_checkbox_marked, ColorRole.PRIMARY));
} else {
gridViewHolder.itemLayout.setBackgroundColor(mContext.getResources().getColor(R.color.bg_default));
gridViewHolder.checkbox.setImageResource(R.drawable.ic_checkbox_blank_outline);
}
gridViewHolder.checkbox.setOnClickListener(v -> localFileListFragmentInterface
.onItemCheckboxClicked(finalFile));
}
gridViewHolder.thumbnail.setTag(file.hashCode());
setThumbnail(file, gridViewHolder.thumbnail, mContext, viewThemeUtils);
gridViewHolder.itemLayout.setOnClickListener(v -> localFileListFragmentInterface
.onItemClicked(finalFile));
if (holder instanceof LocalFileListItemViewHolder) {
LocalFileListItemViewHolder itemViewHolder = (LocalFileListItemViewHolder) holder;
if (file.isDirectory()) {
itemViewHolder.fileSize.setVisibility(View.GONE);
itemViewHolder.fileSeparator.setVisibility(View.GONE);
if (isWithinEncryptedFolder) {
itemViewHolder.checkbox.setVisibility(View.GONE);
}
} else {
itemViewHolder.fileSize.setVisibility(View.VISIBLE);
itemViewHolder.fileSeparator.setVisibility(View.VISIBLE);
itemViewHolder.fileSize.setText(DisplayUtils.bytesToHumanReadable(file.length()));
}
itemViewHolder.lastModification.setText(DisplayUtils.getRelativeTimestamp(mContext,
file.lastModified()));
}
if (gridViewHolder instanceof LocalFileListGridItemViewHolder) {
LocalFileListGridItemViewHolder itemVH = (LocalFileListGridItemViewHolder) gridViewHolder;
itemVH.fileName.setText(file.getName());
if (gridView && (MimeTypeUtil.isImage(file) || MimeTypeUtil.isVideo(file) ||
localFileListFragmentInterface.getColumnsCount() > showFilenameColumnThreshold)) {
itemVH.fileName.setVisibility(View.GONE);
} else {
itemVH.fileName.setVisibility(View.VISIBLE);
}
}
}
}
}
public static void setThumbnail(File file,
ImageView thumbnailView,
Context context,
ViewThemeUtils viewThemeUtils) {
if (file.isDirectory()) {
thumbnailView.setImageDrawable(MimeTypeUtil.getDefaultFolderIcon(context, viewThemeUtils));
} else {
thumbnailView.setImageResource(R.drawable.file);
/* Cancellation needs do be checked and done before changing the drawable in fileIcon, or
* {@link ThumbnailsCacheManager#cancelPotentialThumbnailWork} will NEVER cancel any task.
*/
boolean allowedToCreateNewThumbnail = ThumbnailsCacheManager.cancelPotentialThumbnailWork(file,
thumbnailView);
// get Thumbnail if file is image
if (MimeTypeUtil.isImage(file)) {
// Thumbnail in Cache?
Bitmap thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(
ThumbnailsCacheManager.PREFIX_THUMBNAIL + file.hashCode()
);
if (thumbnail != null) {
thumbnailView.setImageBitmap(thumbnail);
} else {
// generate new Thumbnail
if (allowedToCreateNewThumbnail) {
final ThumbnailsCacheManager.ThumbnailGenerationTask task =
new ThumbnailsCacheManager.ThumbnailGenerationTask(thumbnailView);
if (MimeTypeUtil.isVideo(file)) {
thumbnail = ThumbnailsCacheManager.mDefaultVideo;
} else {
thumbnail = ThumbnailsCacheManager.mDefaultImg;
}
final ThumbnailsCacheManager.AsyncThumbnailDrawable asyncDrawable =
new ThumbnailsCacheManager.AsyncThumbnailDrawable(
context.getResources(),
thumbnail,
task
);
thumbnailView.setImageDrawable(asyncDrawable);
task.execute(new ThumbnailsCacheManager.ThumbnailGenerationTaskObject(file, null));
Log_OC.v(TAG, "Executing task to generate a new thumbnail");
} // else, already being generated, don't restart it
}
} else {
thumbnailView.setImageDrawable(MimeTypeUtil.getFileTypeIcon(null,
file.getName(),
context,
viewThemeUtils));
}
}
}
@Override
public int getItemViewType(int position) {
if (position == mFiles.size()) {
return VIEWTYPE_FOOTER;
} else {
if (MimeTypeUtil.isImageOrVideo(getItem(position))) {
return VIEWTYPE_IMAGE;
} else {
return VIEWTYPE_ITEM;
}
}
}
private File getItem(int position) {
return mFiles.get(position);
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
switch (viewType) {
default:
case VIEWTYPE_ITEM:
if (gridView) {
View itemView = LayoutInflater.from(mContext).inflate(R.layout.grid_item, parent, false);
return new LocalFileListGridItemViewHolder(itemView);
} else {
View itemView = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
return new LocalFileListItemViewHolder(itemView);
}
case VIEWTYPE_IMAGE:
if (gridView) {
View itemView = LayoutInflater.from(mContext).inflate(R.layout.grid_image, parent, false);
return new LocalFileListGridImageViewHolder(itemView);
} else {
View itemView = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
return new LocalFileListItemViewHolder(itemView);
}
case VIEWTYPE_FOOTER:
View itemView = LayoutInflater.from(mContext).inflate(R.layout.list_footer, parent, false);
return new LocalFileListFooterViewHolder(itemView);
}
}
/**
* Change the adapted directory for a new one
*
* @param directory New file to adapt. Can be NULL, meaning "no content to adapt".
*/
public void swapDirectory(final File directory) {
localFileListFragmentInterface.setLoading(true);
final Handler uiHandler = new Handler(Looper.getMainLooper());
Executors.newSingleThreadExecutor().execute(() -> {
List<File> fileList;
if (directory == null) {
fileList = new ArrayList<>();
} else {
if (mLocalFolderPicker) {
fileList = getFolders(directory);
} else {
fileList = getFiles(directory);
}
}
if (!fileList.isEmpty()) {
FileSortOrder sortOrder = preferences.getSortOrderByType(FileSortOrder.Type.localFileListView);
fileList = sortOrder.sortLocalFiles(fileList);
// Fetch preferences for showing hidden files
boolean showHiddenFiles = preferences.isShowHiddenFilesEnabled();
if (!showHiddenFiles) {
fileList = filterHiddenFiles(fileList);
}
}
final List<File> newFiles = fileList;
uiHandler.post(() -> {
mFiles = newFiles;
mFilesAll = new ArrayList<>();
mFilesAll.addAll(mFiles);
notifyDataSetChanged();
localFileListFragmentInterface.setLoading(false);
});
});
}
public void setSortOrder(FileSortOrder sortOrder) {
localFileListFragmentInterface.setLoading(true);
final Handler uiHandler = new Handler(Looper.getMainLooper());
Executors.newSingleThreadExecutor().execute(() -> {
preferences.setSortOrder(FileSortOrder.Type.localFileListView, sortOrder);
mFiles = sortOrder.sortLocalFiles(mFiles);
uiHandler.post(() -> {
notifyDataSetChanged();
localFileListFragmentInterface.setLoading(false);
});
});
}
private List<File> getFolders(final File directory) {
File[] folders = directory.listFiles(File::isDirectory);
if (folders != null && folders.length > 0) {
return new ArrayList<>(Arrays.asList(folders));
} else {
return new ArrayList<>();
}
}
private List<File> getFiles(File directory) {
File[] files = directory.listFiles();
if (files != null && files.length > 0) {
return new ArrayList<>(Arrays.asList(files));
} else {
return new ArrayList<>();
}
}
public void filter(String text) {
if (text.isEmpty()) {
mFiles = mFilesAll;
} else {
List<File> result = new ArrayList<>();
String filterText = text.toLowerCase(Locale.getDefault());
for (File file : mFilesAll) {
if (file.getName().toLowerCase(Locale.getDefault()).contains(filterText)) {
result.add(file);
}
}
mFiles = result;
}
notifyDataSetChanged();
}
/**
* Filter for hidden files
*
* @param files ArrayList of files to filter
* @return Non-hidden files
*/
private List<File> filterHiddenFiles(List<File> files) {
List<File> ret = new ArrayList<>();
for (File file : files) {
if (!file.isHidden()) {
ret.add(file);
}
}
return ret;
}
private String getFooterText() {
int filesCount = 0;
int foldersCount = 0;
for (File file : mFiles) {
if (file.isDirectory()) {
foldersCount++;
} else {
if (!file.isHidden()) {
filesCount++;
}
}
}
return generateFooterText(filesCount, foldersCount);
}
private String generateFooterText(int filesCount, int foldersCount) {
String output;
Resources resources = mContext.getResources();
if (filesCount + foldersCount <= 0) {
output = "";
} else if (foldersCount <= 0) {
output = resources.getQuantityString(R.plurals.file_list__footer__file, filesCount, filesCount);
} else if (filesCount <= 0) {
output = resources.getQuantityString(R.plurals.file_list__footer__folder, foldersCount, foldersCount);
} else {
output = resources.getQuantityString(R.plurals.file_list__footer__file, filesCount, filesCount) + ", " +
resources.getQuantityString(R.plurals.file_list__footer__folder, foldersCount, foldersCount);
}
return output;
}
public void setGridView(boolean gridView) {
this.gridView = gridView;
}
public int checkedFilesCount() {
return checkedFiles.size();
}
private static class LocalFileListItemViewHolder extends LocalFileListGridItemViewHolder {
private final TextView fileSize;
private final TextView lastModification;
private final TextView fileSeparator;
private LocalFileListItemViewHolder(View itemView) {
super(itemView);
fileSize = itemView.findViewById(R.id.file_size);
fileSeparator = itemView.findViewById(R.id.file_separator);
lastModification = itemView.findViewById(R.id.last_mod);
itemView.findViewById(R.id.sharedAvatars).setVisibility(View.GONE);
itemView.findViewById(R.id.overflow_menu).setVisibility(View.GONE);
itemView.findViewById(R.id.tagsGroup).setVisibility(View.GONE);
}
}
static class LocalFileListGridImageViewHolder extends RecyclerView.ViewHolder {
protected final ImageView thumbnail;
protected final ImageView checkbox;
protected final LinearLayout itemLayout;
private LocalFileListGridImageViewHolder(View itemView) {
super(itemView);
thumbnail = itemView.findViewById(R.id.thumbnail);
checkbox = itemView.findViewById(R.id.custom_checkbox);
itemLayout = itemView.findViewById(R.id.ListItemLayout);
itemView.findViewById(R.id.sharedIcon).setVisibility(View.GONE);
itemView.findViewById(R.id.favorite_action).setVisibility(View.GONE);
itemView.findViewById(R.id.localFileIndicator).setVisibility(View.GONE);
}
}
static class LocalFileListGridItemViewHolder extends LocalFileListGridImageViewHolder {
private final TextView fileName;
private LocalFileListGridItemViewHolder(View itemView) {
super(itemView);
fileName = itemView.findViewById(R.id.Filename);
}
}
private static class LocalFileListFooterViewHolder extends RecyclerView.ViewHolder {
private final TextView footerText;
private LocalFileListFooterViewHolder(View itemView) {
super(itemView);
footerText = itemView.findViewById(R.id.footerText);
}
}
@VisibleForTesting
public void setFiles(List<File> newFiles) {
mFiles = newFiles;
mFilesAll = new ArrayList<>();
mFilesAll.addAll(mFiles);
notifyDataSetChanged();
localFileListFragmentInterface.setLoading(false);
}
}
```
|
Northam was an electoral district of the Legislative Assembly in the Australian state of Western Australia from 1890 to 1974.
The district was based on the town of Northam lying to the east of Perth. It was one of the original 30 seats contested at the 1890 election. The district was abolished at the 1974 election. Its last member, Ken McIver of the Labor Party, went on to become the member for Avon.
Northam was represented by five members over the course of its 84-year history. Three of those members served as Premier of Western Australia: George Throssell (Premier 1901), James Mitchell (Premier 1919–1924 & 1930–1933) and Albert Hawke (Premier 1953–1959).
Members
Election results
Northam
|
```javascript
/**
* @license
*
*
* 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.
*/
var Controller = skit.platform.Controller;
var Marketing = library.controllers.Marketing;
module.exports = Controller.create(Marketing, {});
```
|
```c
struct ListNode *detectCycle(struct ListNode *head)
{
if (head == NULL || head->next == NULL)
return NULL;
struct ListNode *slow, *fast;
slow = fast = head;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
struct ListNode *entry = head;
while (slow != entry)
{
slow = slow->next;
entry = entry->next;
}
return entry;
}
}
return NULL;
}
```
|
The Rockland County Times is a weekly newspaper published in Rockland County, New York.
The Rockland County Times began publication in October 1889. In 1998 the paper declared bankruptcy and was purchased by Peter Sluys, a former editor of other weekly newspapers. The following year, the Rockland County Times was designated one of the official newspapers of Rockland County, for purposes of publication of legal notices and announcements.
In 2014 The paper was purchased by Dylan Skriloff, its editor. In 2020 it was purchased by John and Walter Sanchez, owners of The Queens Ledger / Greenpoint Star Weekly Newspaper Group in New York City. They also publish The Wave of Rockaway. The broadsheet paid weekly newspaper is published on Thursdays. Along with its mail subscriptions it is distributed at 115 locations throughout the county. The paper is published from its offices at 119 Main Street Nanuet and in 2022 is the only countywide paid weekly newspaper in Rockland County.
Robert J. Connor was a former columnist for the Rockland County Times. Since 2013, the paper's reporting has been sourced by People, CBS News, and Politico, among others.
References
Weekly newspapers published in the United States
1889 establishments in New York (state)
|
The 2012–13 season was East Stirlingshire's nineteenth consecutive season in the Scottish Third Division, having been relegated from the Scottish Second Division at the end of the 1993–94 season, following league reconstruction. East Stirlingshire also competed in the Challenge Cup, League Cup and the Scottish Cup.
Summary
Season
East Stirlingshire finished tenth in the Scottish Third Division. They reached the Quarter-final of the Challenge Cup, the first round of the League Cup and the third round of the Scottish Cup.
Results & fixtures
Pre-season
Scottish Third Division
Scottish Challenge Cup
Scottish League Cup
Scottish Cup
Player statistics
Squad
Last updated 13 May 2013
|}
Disciplinary record
Includes all competitive matches.
Last updated 13 May 2013
Team statistics
League table
Division summary
Transfers
Players in
Players out
References
East Stirlingshire F.C. seasons
East Stirlingshire
|
Spectrunculus crassus is a species of cusk-eel native to the Atlantic and eastern Pacific.
References
Ophidiidae
Fish described in 1888
|
```php
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Finder\Iterator;
use Symfony\Component\Finder\Comparator\NumberComparator;
/**
* SizeRangeFilterIterator filters out files that are not in the given size range.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SizeRangeFilterIterator extends FilterIterator
{
private $comparators = array();
/**
* Constructor.
*
* @param \Iterator $iterator The Iterator to filter
* @param NumberComparator[] $comparators An array of NumberComparator instances
*/
public function __construct(\Iterator $iterator, array $comparators)
{
$this->comparators = $comparators;
parent::__construct($iterator);
}
/**
* Filters the iterator values.
*
* @return bool true if the value should be kept, false otherwise
*/
public function accept()
{
$fileinfo = $this->current();
if (!$fileinfo->isFile()) {
return true;
}
$filesize = $fileinfo->getSize();
foreach ($this->comparators as $compare) {
if (!$compare->test($filesize)) {
return false;
}
}
return true;
}
}
```
|
Daniel Boimah Kenney Knero Lapaé Edwards II (born May 19, 1985), better known as Knero Lapaé or simply Knero (stylized as kNERO; pronounced knee ro la pay), is a Liberian rapper, singer, songwriter, record producer, model, and author. His music is a mixture of Hip hop and Afrobeats.
Personal life and family members
kNERO was born in Monrovia, Liberia and raised in Brooklyn, New York. His father is Gola and his mother is from the Kpelle tribe. He is one of four children of Sara Léla and Rev. D. Boimah Lapaé Edwards, who was the youngest Liberian to managed an American corporation in Liberia. His father is currently the President of the non-profit organization, The Bomi County Association. kNERO was brought up in a predominant political background. He is the nephew of Liberia's 24th president Ellen Johnson Sirleaf. He has an uncle who was a judge of the Magistrate Court, a District Commissioner, and County Development Coordinator for the Ministry of Internal Affairs. He is also the first cousin of Richard B. Devine, a former Senator of Liberia. His family was fortunate enough to escape the Liberian Civil War as a result of his father's achievements, but still suffers the loss of family and friends.
Music career and performances
kNERO released "Not Drunk Enuff" featuring Norwegian singer Adele Erichsen, a former contestant on The Voice – Norges beste stemme. The single was released under CCAP records. Due to his political ties, he celebrated the Liberian Declaration of Independence by performing his single "A.F.R.I.C.A" at the Liberian Embassy in Washington, D.C. He performed at the Hip Hop of Pioneers event held at the Newark Symphony Hall; the event featured additional performances from MC Lyte, Kool and the Gang, Dana Dane and Slick Rick.
Between 2006 and 2007, he performed at The Fox Theatre in Atlanta for Dr. Malachi Z. York's 11th Annual Nuwaupu Ball; his name was announced alongside Erykah Badu, Jimmy Cliff and Musiq Soulchild. kNERO released his single "My Thang" featuring Jamal "Gravy" Woolard and former Roc-A-Fella artist Amil, which appeared on several urban blog sites.
In 2014, kNERO closed a deal to release his next single "King" under Universal Music Group.
Music Influences
While growing up, kNERO listened to artists such as Buck Shot, Smif N Wessun, Jay Z, The Notorious B.I.G., Nas, Phil Collins, Sade Adu, Fela Kuti, Prodigy, Big Daddy Kane, Biz Markie, Rakim, Raekwon, Ghostface Killah, KRS-One, 50 Cent, Kool G Rap, Tracy Chapman and Bob Marley.
Other works
Barber career
In 1995, kNERO fell in love with the art of barbering. To avoid street violence and other criminal activities, he learned to master his craft over the years. He then travels from state to state gaining connections in the hair industry, which helped his music career. His limitless experiences, becoming rapper Raekwon from the Wu-Tang Clan personal barber. Gaining clients as Comedian Kyle Grooms, Fashion Designer Toure Designs, Humanitarian/Motivational speaker George Green, Celebrity Hairstylist Keith Campbell, Middleweight Boxer Peter Quillin, and more.
Modeling and clothing
In 2012, kNERO was a model for photos of The Toure Designs' fall season collection. Later that year, the model in The Toure Designs' Target First Saturdays "Carnival Inspired Fashion" themed at the Brooklyn Museum. He continued to walk the runway alongside actress/singer Demetria Mckinney, modeling for Toure Designs' for the 2015 Mercedes Benz Fashion week presented by ICU Network hosted by SB Stunts.
Acting
kNERO Lapaé has made an appearance in the 2013 film Living With No Regrets, with Clifton Powell, Marc John Jefferies, rapper AZ, Charlie Baltimore, Treach and more.
In 2014, kNERO landed a role on Red Dot a series about a group of trained killers, which expands into stories of many other individuals that they come into contact with. He first appeared in the Red Dot episode "The Walking Dead", as Fritzoy, a goon of a hit-man leader named Cassius who's out for revenge after finding out his friend Eddie was murdered.
Memoir
Homeless With A Record Deal: The Moments Of Luxury (January 2016)
Discography
Singles
Awards and nominations
Liberia Music Awards
|-
| rowspan="2"|2014
| rowspan="3"|Himself
| Artist of the Year - USA
|
|-
| Hip Hop Artist of the Year
|
|-
|2016
| Hip Hop Artist of the Year
|
References
External links
1981 births
Living people
Musicians from Monrovia
Gola people
Liberian songwriters
Liberian people of Gola descent
Rappers from Brooklyn
African-American record producers
Liberian people of Kpelle descent
Songwriters from New York (state)
American memoirists
Liberian emigrants to the United States
American hip hop record producers
East Coast hip hop musicians
Liberian singers
21st-century American rappers
Record producers from New York (state)
21st-century African-American musicians
20th-century African-American people
Liberian male musicians
|
```c++
#define MINIMAL_STDERR_OUTPUT
#include "llvm/Analysis/Passes.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Transforms/Scalar.h"
#include <cctype>
#include <cstdio>
#include <map>
#include <string>
#include <vector>
using namespace llvm;
//===your_sha256_hash------===//
// Lexer
//===your_sha256_hash------===//
// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
// of these for known things.
enum Token {
tok_eof = -1,
// commands
tok_def = -2, tok_extern = -3,
// primary
tok_identifier = -4, tok_number = -5,
// control
tok_if = -6, tok_then = -7, tok_else = -8,
tok_for = -9, tok_in = -10,
// operators
tok_binary = -11, tok_unary = -12,
// var definition
tok_var = -13
};
static std::string IdentifierStr; // Filled in if tok_identifier
static double NumVal; // Filled in if tok_number
/// gettok - Return the next token from standard input.
static int gettok() {
static int LastChar = ' ';
// Skip any whitespace.
while (isspace(LastChar))
LastChar = getchar();
if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
IdentifierStr = LastChar;
while (isalnum((LastChar = getchar())))
IdentifierStr += LastChar;
if (IdentifierStr == "def") return tok_def;
if (IdentifierStr == "extern") return tok_extern;
if (IdentifierStr == "if") return tok_if;
if (IdentifierStr == "then") return tok_then;
if (IdentifierStr == "else") return tok_else;
if (IdentifierStr == "for") return tok_for;
if (IdentifierStr == "in") return tok_in;
if (IdentifierStr == "binary") return tok_binary;
if (IdentifierStr == "unary") return tok_unary;
if (IdentifierStr == "var") return tok_var;
return tok_identifier;
}
if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
std::string NumStr;
do {
NumStr += LastChar;
LastChar = getchar();
} while (isdigit(LastChar) || LastChar == '.');
NumVal = strtod(NumStr.c_str(), 0);
return tok_number;
}
if (LastChar == '#') {
// Comment until end of line.
do LastChar = getchar();
while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
if (LastChar != EOF)
return gettok();
}
// Check for end of file. Don't eat the EOF.
if (LastChar == EOF)
return tok_eof;
// Otherwise, just return the character as its ascii value.
int ThisChar = LastChar;
LastChar = getchar();
return ThisChar;
}
//===your_sha256_hash------===//
// Abstract Syntax Tree (aka Parse Tree)
//===your_sha256_hash------===//
/// ExprAST - Base class for all expression nodes.
class ExprAST {
public:
virtual ~ExprAST() {}
virtual Value *Codegen() = 0;
};
/// NumberExprAST - Expression class for numeric literals like "1.0".
class NumberExprAST : public ExprAST {
double Val;
public:
NumberExprAST(double val) : Val(val) {}
virtual Value *Codegen();
};
/// VariableExprAST - Expression class for referencing a variable, like "a".
class VariableExprAST : public ExprAST {
std::string Name;
public:
VariableExprAST(const std::string &name) : Name(name) {}
const std::string &getName() const { return Name; }
virtual Value *Codegen();
};
/// UnaryExprAST - Expression class for a unary operator.
class UnaryExprAST : public ExprAST {
char Opcode;
ExprAST *Operand;
public:
UnaryExprAST(char opcode, ExprAST *operand)
: Opcode(opcode), Operand(operand) {}
virtual Value *Codegen();
};
/// BinaryExprAST - Expression class for a binary operator.
class BinaryExprAST : public ExprAST {
char Op;
ExprAST *LHS, *RHS;
public:
BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
: Op(op), LHS(lhs), RHS(rhs) {}
virtual Value *Codegen();
};
/// CallExprAST - Expression class for function calls.
class CallExprAST : public ExprAST {
std::string Callee;
std::vector<ExprAST*> Args;
public:
CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
: Callee(callee), Args(args) {}
virtual Value *Codegen();
};
/// IfExprAST - Expression class for if/then/else.
class IfExprAST : public ExprAST {
ExprAST *Cond, *Then, *Else;
public:
IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
: Cond(cond), Then(then), Else(_else) {}
virtual Value *Codegen();
};
/// ForExprAST - Expression class for for/in.
class ForExprAST : public ExprAST {
std::string VarName;
ExprAST *Start, *End, *Step, *Body;
public:
ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
ExprAST *step, ExprAST *body)
: VarName(varname), Start(start), End(end), Step(step), Body(body) {}
virtual Value *Codegen();
};
/// VarExprAST - Expression class for var/in
class VarExprAST : public ExprAST {
std::vector<std::pair<std::string, ExprAST*> > VarNames;
ExprAST *Body;
public:
VarExprAST(const std::vector<std::pair<std::string, ExprAST*> > &varnames,
ExprAST *body)
: VarNames(varnames), Body(body) {}
virtual Value *Codegen();
};
/// PrototypeAST - This class represents the "prototype" for a function,
/// which captures its argument names as well as if it is an operator.
class PrototypeAST {
std::string Name;
std::vector<std::string> Args;
bool isOperator;
unsigned Precedence; // Precedence if a binary op.
public:
PrototypeAST(const std::string &name, const std::vector<std::string> &args,
bool isoperator = false, unsigned prec = 0)
: Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
bool isUnaryOp() const { return isOperator && Args.size() == 1; }
bool isBinaryOp() const { return isOperator && Args.size() == 2; }
char getOperatorName() const {
assert(isUnaryOp() || isBinaryOp());
return Name[Name.size()-1];
}
unsigned getBinaryPrecedence() const { return Precedence; }
Function *Codegen();
void CreateArgumentAllocas(Function *F);
};
/// FunctionAST - This class represents a function definition itself.
class FunctionAST {
PrototypeAST *Proto;
ExprAST *Body;
public:
FunctionAST(PrototypeAST *proto, ExprAST *body)
: Proto(proto), Body(body) {}
Function *Codegen();
};
//===your_sha256_hash------===//
// Parser
//===your_sha256_hash------===//
/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
/// token the parser is looking at. getNextToken reads another token from the
/// lexer and updates CurTok with its results.
static int CurTok;
static int getNextToken() {
return CurTok = gettok();
}
/// BinopPrecedence - This holds the precedence for each binary operator that is
/// defined.
static std::map<char, int> BinopPrecedence;
/// GetTokPrecedence - Get the precedence of the pending binary operator token.
static int GetTokPrecedence() {
if (!isascii(CurTok))
return -1;
// Make sure it's a declared binop.
int TokPrec = BinopPrecedence[CurTok];
if (TokPrec <= 0) return -1;
return TokPrec;
}
/// Error* - These are little helper functions for error handling.
ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
static ExprAST *ParseExpression();
/// identifierexpr
/// ::= identifier
/// ::= identifier '(' expression* ')'
static ExprAST *ParseIdentifierExpr() {
std::string IdName = IdentifierStr;
getNextToken(); // eat identifier.
if (CurTok != '(') // Simple variable ref.
return new VariableExprAST(IdName);
// Call.
getNextToken(); // eat (
std::vector<ExprAST*> Args;
if (CurTok != ')') {
while (1) {
ExprAST *Arg = ParseExpression();
if (!Arg) return 0;
Args.push_back(Arg);
if (CurTok == ')') break;
if (CurTok != ',')
return Error("Expected ')' or ',' in argument list");
getNextToken();
}
}
// Eat the ')'.
getNextToken();
return new CallExprAST(IdName, Args);
}
/// numberexpr ::= number
static ExprAST *ParseNumberExpr() {
ExprAST *Result = new NumberExprAST(NumVal);
getNextToken(); // consume the number
return Result;
}
/// parenexpr ::= '(' expression ')'
static ExprAST *ParseParenExpr() {
getNextToken(); // eat (.
ExprAST *V = ParseExpression();
if (!V) return 0;
if (CurTok != ')')
return Error("expected ')'");
getNextToken(); // eat ).
return V;
}
/// ifexpr ::= 'if' expression 'then' expression 'else' expression
static ExprAST *ParseIfExpr() {
getNextToken(); // eat the if.
// condition.
ExprAST *Cond = ParseExpression();
if (!Cond) return 0;
if (CurTok != tok_then)
return Error("expected then");
getNextToken(); // eat the then
ExprAST *Then = ParseExpression();
if (Then == 0) return 0;
if (CurTok != tok_else)
return Error("expected else");
getNextToken();
ExprAST *Else = ParseExpression();
if (!Else) return 0;
return new IfExprAST(Cond, Then, Else);
}
/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
static ExprAST *ParseForExpr() {
getNextToken(); // eat the for.
if (CurTok != tok_identifier)
return Error("expected identifier after for");
std::string IdName = IdentifierStr;
getNextToken(); // eat identifier.
if (CurTok != '=')
return Error("expected '=' after for");
getNextToken(); // eat '='.
ExprAST *Start = ParseExpression();
if (Start == 0) return 0;
if (CurTok != ',')
return Error("expected ',' after for start value");
getNextToken();
ExprAST *End = ParseExpression();
if (End == 0) return 0;
// The step value is optional.
ExprAST *Step = 0;
if (CurTok == ',') {
getNextToken();
Step = ParseExpression();
if (Step == 0) return 0;
}
if (CurTok != tok_in)
return Error("expected 'in' after for");
getNextToken(); // eat 'in'.
ExprAST *Body = ParseExpression();
if (Body == 0) return 0;
return new ForExprAST(IdName, Start, End, Step, Body);
}
/// varexpr ::= 'var' identifier ('=' expression)?
// (',' identifier ('=' expression)?)* 'in' expression
static ExprAST *ParseVarExpr() {
getNextToken(); // eat the var.
std::vector<std::pair<std::string, ExprAST*> > VarNames;
// At least one variable name is required.
if (CurTok != tok_identifier)
return Error("expected identifier after var");
while (1) {
std::string Name = IdentifierStr;
getNextToken(); // eat identifier.
// Read the optional initializer.
ExprAST *Init = 0;
if (CurTok == '=') {
getNextToken(); // eat the '='.
Init = ParseExpression();
if (Init == 0) return 0;
}
VarNames.push_back(std::make_pair(Name, Init));
// End of var list, exit loop.
if (CurTok != ',') break;
getNextToken(); // eat the ','.
if (CurTok != tok_identifier)
return Error("expected identifier list after var");
}
// At this point, we have to have 'in'.
if (CurTok != tok_in)
return Error("expected 'in' keyword after 'var'");
getNextToken(); // eat 'in'.
ExprAST *Body = ParseExpression();
if (Body == 0) return 0;
return new VarExprAST(VarNames, Body);
}
/// primary
/// ::= identifierexpr
/// ::= numberexpr
/// ::= parenexpr
/// ::= ifexpr
/// ::= forexpr
/// ::= varexpr
static ExprAST *ParsePrimary() {
switch (CurTok) {
default: return Error("unknown token when expecting an expression");
case tok_identifier: return ParseIdentifierExpr();
case tok_number: return ParseNumberExpr();
case '(': return ParseParenExpr();
case tok_if: return ParseIfExpr();
case tok_for: return ParseForExpr();
case tok_var: return ParseVarExpr();
}
}
/// unary
/// ::= primary
/// ::= '!' unary
static ExprAST *ParseUnary() {
// If the current token is not an operator, it must be a primary expr.
if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
return ParsePrimary();
// If this is a unary operator, read it.
int Opc = CurTok;
getNextToken();
if (ExprAST *Operand = ParseUnary())
return new UnaryExprAST(Opc, Operand);
return 0;
}
/// binoprhs
/// ::= ('+' unary)*
static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
// If this is a binop, find its precedence.
while (1) {
int TokPrec = GetTokPrecedence();
// If this is a binop that binds at least as tightly as the current binop,
// consume it, otherwise we are done.
if (TokPrec < ExprPrec)
return LHS;
// Okay, we know this is a binop.
int BinOp = CurTok;
getNextToken(); // eat binop
// Parse the unary expression after the binary operator.
ExprAST *RHS = ParseUnary();
if (!RHS) return 0;
// If BinOp binds less tightly with RHS than the operator after RHS, let
// the pending operator take RHS as its LHS.
int NextPrec = GetTokPrecedence();
if (TokPrec < NextPrec) {
RHS = ParseBinOpRHS(TokPrec+1, RHS);
if (RHS == 0) return 0;
}
// Merge LHS/RHS.
LHS = new BinaryExprAST(BinOp, LHS, RHS);
}
}
/// expression
/// ::= unary binoprhs
///
static ExprAST *ParseExpression() {
ExprAST *LHS = ParseUnary();
if (!LHS) return 0;
return ParseBinOpRHS(0, LHS);
}
/// prototype
/// ::= id '(' id* ')'
/// ::= binary LETTER number? (id, id)
/// ::= unary LETTER (id)
static PrototypeAST *ParsePrototype() {
std::string FnName;
unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
unsigned BinaryPrecedence = 30;
switch (CurTok) {
default:
return ErrorP("Expected function name in prototype");
case tok_identifier:
FnName = IdentifierStr;
Kind = 0;
getNextToken();
break;
case tok_unary:
getNextToken();
if (!isascii(CurTok))
return ErrorP("Expected unary operator");
FnName = "unary";
FnName += (char)CurTok;
Kind = 1;
getNextToken();
break;
case tok_binary:
getNextToken();
if (!isascii(CurTok))
return ErrorP("Expected binary operator");
FnName = "binary";
FnName += (char)CurTok;
Kind = 2;
getNextToken();
// Read the precedence if present.
if (CurTok == tok_number) {
if (NumVal < 1 || NumVal > 100)
return ErrorP("Invalid precedecnce: must be 1..100");
BinaryPrecedence = (unsigned)NumVal;
getNextToken();
}
break;
}
if (CurTok != '(')
return ErrorP("Expected '(' in prototype");
std::vector<std::string> ArgNames;
while (getNextToken() == tok_identifier)
ArgNames.push_back(IdentifierStr);
if (CurTok != ')')
return ErrorP("Expected ')' in prototype");
// success.
getNextToken(); // eat ')'.
// Verify right number of names for operator.
if (Kind && ArgNames.size() != Kind)
return ErrorP("Invalid number of operands for operator");
return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
}
/// definition ::= 'def' prototype expression
static FunctionAST *ParseDefinition() {
getNextToken(); // eat def.
PrototypeAST *Proto = ParsePrototype();
if (Proto == 0) return 0;
if (ExprAST *E = ParseExpression())
return new FunctionAST(Proto, E);
return 0;
}
/// toplevelexpr ::= expression
static FunctionAST *ParseTopLevelExpr() {
if (ExprAST *E = ParseExpression()) {
// Make an anonymous proto.
PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
return new FunctionAST(Proto, E);
}
return 0;
}
/// external ::= 'extern' prototype
static PrototypeAST *ParseExtern() {
getNextToken(); // eat extern.
return ParsePrototype();
}
//===your_sha256_hash------===//
// Code Generation
//===your_sha256_hash------===//
static Module *TheModule;
static FunctionPassManager *TheFPM;
static LLVMContext TheContext;
static IRBuilder<> Builder(TheContext);
static std::map<std::string, AllocaInst*> NamedValues;
Value *ErrorV(const char *Str) { Error(Str); return 0; }
/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
/// the function. This is used for mutable variables etc.
static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
const std::string &VarName) {
IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
TheFunction->getEntryBlock().begin());
return TmpB.CreateAlloca(Type::getDoubleTy(TheContext), 0, VarName.c_str());
}
Value *NumberExprAST::Codegen() {
return ConstantFP::get(TheContext, APFloat(Val));
}
Value *VariableExprAST::Codegen() {
// Look this variable up in the function.
Value *V = NamedValues[Name];
if (V == 0) return ErrorV("Unknown variable name");
// Load the value.
return Builder.CreateLoad(V, Name.c_str());
}
Value *UnaryExprAST::Codegen() {
Value *OperandV = Operand->Codegen();
if (OperandV == 0) return 0;
#ifdef USE_MCJIT
Function *F = TheHelper->getFunction(MakeLegalFunctionName(std::string("unary")+Opcode));
#else
Function *F = TheModule->getFunction(std::string("unary")+Opcode);
#endif
if (F == 0)
return ErrorV("Unknown unary operator");
return Builder.CreateCall(F, OperandV, "unop");
}
Value *BinaryExprAST::Codegen() {
// Special case '=' because we don't want to emit the LHS as an expression.
if (Op == '=') {
// Assignment requires the LHS to be an identifier.
VariableExprAST *LHSE = dynamic_cast<VariableExprAST*>(LHS);
if (!LHSE)
return ErrorV("destination of '=' must be a variable");
// Codegen the RHS.
Value *Val = RHS->Codegen();
if (Val == 0) return 0;
// Look up the name.
Value *Variable = NamedValues[LHSE->getName()];
if (Variable == 0) return ErrorV("Unknown variable name");
Builder.CreateStore(Val, Variable);
return Val;
}
Value *L = LHS->Codegen();
Value *R = RHS->Codegen();
if (L == 0 || R == 0) return 0;
switch (Op) {
case '+': return Builder.CreateFAdd(L, R, "addtmp");
case '-': return Builder.CreateFSub(L, R, "subtmp");
case '*': return Builder.CreateFMul(L, R, "multmp");
case '/': return Builder.CreateFDiv(L, R, "divtmp");
case '<':
L = Builder.CreateFCmpULT(L, R, "cmptmp");
// Convert bool 0/1 to double 0.0 or 1.0
return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext), "booltmp");
default: break;
}
// If it wasn't a builtin binary operator, it must be a user defined one. Emit
// a call to it.
Function *F = TheModule->getFunction(std::string("binary")+Op);
assert(F && "binary operator not found!");
Value *Ops[] = { L, R };
return Builder.CreateCall(F, Ops, "binop");
}
Value *CallExprAST::Codegen() {
// Look up the name in the global module table.
Function *CalleeF = TheModule->getFunction(Callee);
if (CalleeF == 0) {
char error_str[64];
sprintf(error_str, "Unknown function referenced %s", Callee.c_str());
return ErrorV(error_str);
}
// If argument mismatch error.
if (CalleeF->arg_size() != Args.size())
return ErrorV("Incorrect # arguments passed");
std::vector<Value*> ArgsV;
for (unsigned i = 0, e = Args.size(); i != e; ++i) {
ArgsV.push_back(Args[i]->Codegen());
if (ArgsV.back() == 0) return 0;
}
return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
}
Value *IfExprAST::Codegen() {
Value *CondV = Cond->Codegen();
if (CondV == 0) return 0;
// Convert condition to a bool by comparing equal to 0.0.
CondV = Builder.CreateFCmpONE(
CondV, ConstantFP::get(TheContext, APFloat(0.0)), "ifcond");
Function *TheFunction = Builder.GetInsertBlock()->getParent();
// Create blocks for the then and else cases. Insert the 'then' block at the
// end of the function.
BasicBlock *ThenBB = BasicBlock::Create(TheContext, "then", TheFunction);
BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
Builder.CreateCondBr(CondV, ThenBB, ElseBB);
// Emit then value.
Builder.SetInsertPoint(ThenBB);
Value *ThenV = Then->Codegen();
if (ThenV == 0) return 0;
Builder.CreateBr(MergeBB);
// Codegen of 'Then' can change the current block, update ThenBB for the PHI.
ThenBB = Builder.GetInsertBlock();
// Emit else block.
TheFunction->insert(TheFunction->end(), ElseBB);
Builder.SetInsertPoint(ElseBB);
Value *ElseV = Else->Codegen();
if (ElseV == 0) return 0;
Builder.CreateBr(MergeBB);
// Codegen of 'Else' can change the current block, update ElseBB for the PHI.
ElseBB = Builder.GetInsertBlock();
// Emit merge block.
TheFunction->insert(TheFunction->end(), MergeBB);
Builder.SetInsertPoint(MergeBB);
PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(TheContext), 2, "iftmp");
PN->addIncoming(ThenV, ThenBB);
PN->addIncoming(ElseV, ElseBB);
return PN;
}
Value *ForExprAST::Codegen() {
// Output this as:
// var = alloca double
// ...
// start = startexpr
// store start -> var
// goto loop
// loop:
// ...
// bodyexpr
// ...
// loopend:
// step = stepexpr
// endcond = endexpr
//
// curvar = load var
// nextvar = curvar + step
// store nextvar -> var
// br endcond, loop, endloop
// outloop:
Function *TheFunction = Builder.GetInsertBlock()->getParent();
// Create an alloca for the variable in the entry block.
AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
// Emit the start code first, without 'variable' in scope.
Value *StartVal = Start->Codegen();
if (StartVal == 0) return 0;
// Store the value into the alloca.
Builder.CreateStore(StartVal, Alloca);
// Make the new basic block for the loop header, inserting after current
// block.
BasicBlock *LoopBB = BasicBlock::Create(TheContext, "loop", TheFunction);
// Insert an explicit fall through from the current block to the LoopBB.
Builder.CreateBr(LoopBB);
// Start insertion in LoopBB.
Builder.SetInsertPoint(LoopBB);
// Within the loop, the variable is defined equal to the PHI node. If it
// shadows an existing variable, we have to restore it, so save it now.
AllocaInst *OldVal = NamedValues[VarName];
NamedValues[VarName] = Alloca;
// Emit the body of the loop. This, like any other expr, can change the
// current BB. Note that we ignore the value computed by the body, but don't
// allow an error.
if (Body->Codegen() == 0)
return 0;
// Emit the step value.
Value *StepVal;
if (Step) {
StepVal = Step->Codegen();
if (StepVal == 0) return 0;
} else {
// If not specified, use 1.0.
StepVal = ConstantFP::get(TheContext, APFloat(1.0));
}
// Compute the end condition.
Value *EndCond = End->Codegen();
if (EndCond == 0) return EndCond;
// Reload, increment, and restore the alloca. This handles the case where
// the body of the loop mutates the variable.
Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
Builder.CreateStore(NextVar, Alloca);
// Convert condition to a bool by comparing equal to 0.0.
EndCond = Builder.CreateFCmpONE(
EndCond, ConstantFP::get(TheContext, APFloat(0.0)), "loopcond");
// Create the "after loop" block and insert it.
BasicBlock *AfterBB =
BasicBlock::Create(TheContext, "afterloop", TheFunction);
// Insert the conditional branch into the end of LoopEndBB.
Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
// Any new code will be inserted in AfterBB.
Builder.SetInsertPoint(AfterBB);
// Restore the unshadowed variable.
if (OldVal)
NamedValues[VarName] = OldVal;
else
NamedValues.erase(VarName);
// for expr always returns 0.0.
return Constant::getNullValue(Type::getDoubleTy(TheContext));
}
Value *VarExprAST::Codegen() {
std::vector<AllocaInst *> OldBindings;
Function *TheFunction = Builder.GetInsertBlock()->getParent();
// Register all variables and emit their initializer.
for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
const std::string &VarName = VarNames[i].first;
ExprAST *Init = VarNames[i].second;
// Emit the initializer before adding the variable to scope, this prevents
// the initializer from referencing the variable itself, and permits stuff
// like this:
// var a = 1 in
// var a = a in ... # refers to outer 'a'.
Value *InitVal;
if (Init) {
InitVal = Init->Codegen();
if (InitVal == 0) return 0;
} else { // If not specified, use 0.0.
InitVal = ConstantFP::get(TheContext, APFloat(0.0));
}
AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
Builder.CreateStore(InitVal, Alloca);
// Remember the old variable binding so that we can restore the binding when
// we unrecurse.
OldBindings.push_back(NamedValues[VarName]);
// Remember this binding.
NamedValues[VarName] = Alloca;
}
// Codegen the body, now that all vars are in scope.
Value *BodyVal = Body->Codegen();
if (BodyVal == 0) return 0;
// Pop all our variables from scope.
for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
NamedValues[VarNames[i].first] = OldBindings[i];
// Return the body computation.
return BodyVal;
}
Function *PrototypeAST::Codegen() {
// Make the function type: double(double,double) etc.
std::vector<Type *> Doubles(Args.size(), Type::getDoubleTy(TheContext));
FunctionType *FT =
FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
// If F conflicted, there was already something named 'Name'. If it has a
// body, don't allow redefinition or reextern.
if (F->getName() != Name) {
// Delete the one we just made and get the existing one.
F->eraseFromParent();
F = TheModule->getFunction(Name);
// If F already has a body, reject this.
if (!F->empty()) {
ErrorF("redefinition of function");
return 0;
}
// If F took a different number of args, reject.
if (F->arg_size() != Args.size()) {
ErrorF("redefinition of function with different # args");
return 0;
}
}
// Set names for all arguments.
unsigned Idx = 0;
for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
++AI, ++Idx)
AI->setName(Args[Idx]);
return F;
}
/// CreateArgumentAllocas - Create an alloca for each argument and register the
/// argument in the symbol table so that references to it will succeed.
void PrototypeAST::CreateArgumentAllocas(Function *F) {
Function::arg_iterator AI = F->arg_begin();
for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
// Create an alloca for this variable.
AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
// Store the initial value into the alloca.
Builder.CreateStore(AI, Alloca);
// Add arguments to variable symbol table.
NamedValues[Args[Idx]] = Alloca;
}
}
Function *FunctionAST::Codegen() {
NamedValues.clear();
Function *TheFunction = Proto->Codegen();
if (TheFunction == 0)
return 0;
// If this is an operator, install it.
if (Proto->isBinaryOp())
BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
// Create a new basic block to start insertion into.
BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
Builder.SetInsertPoint(BB);
// Add all arguments to the symbol table and create their allocas.
Proto->CreateArgumentAllocas(TheFunction);
if (Value *RetVal = Body->Codegen()) {
// Finish off the function.
Builder.CreateRet(RetVal);
// Validate the generated code, checking for consistency.
verifyFunction(*TheFunction);
// Optimize the function.
TheFPM->run(*TheFunction);
return TheFunction;
}
// Error reading body, remove function.
TheFunction->eraseFromParent();
if (Proto->isBinaryOp())
BinopPrecedence.erase(Proto->getOperatorName());
return 0;
}
//===your_sha256_hash------===//
// Top-Level parsing and JIT Driver
//===your_sha256_hash------===//
static ExecutionEngine *TheExecutionEngine;
static void HandleDefinition() {
if (FunctionAST *F = ParseDefinition()) {
if (Function *LF = F->Codegen()) {
#ifndef MINIMAL_STDERR_OUTPUT
fprintf(stderr, "Read function definition:");
LF->print(errs());
fprintf(stderr, "\n");
#endif
}
} else {
// Skip token for error recovery.
getNextToken();
}
}
static void HandleExtern() {
if (PrototypeAST *P = ParseExtern()) {
if (Function *F = P->Codegen()) {
#ifndef MINIMAL_STDERR_OUTPUT
fprintf(stderr, "Read extern: ");
F->print(errs());
fprintf(stderr, "\n");
#endif
}
} else {
// Skip token for error recovery.
getNextToken();
}
}
static void HandleTopLevelExpression() {
// Evaluate a top-level expression into an anonymous function.
if (FunctionAST *F = ParseTopLevelExpr()) {
if (Function *LF = F->Codegen()) {
// JIT the function, returning a function pointer.
void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
// Cast it to the right type (takes no arguments, returns a double) so we
// can call it as a native function.
double (*FP)() = (double (*)())(intptr_t)FPtr;
#ifdef MINIMAL_STDERR_OUTPUT
FP();
#else
fprintf(stderr, "Evaluated to %f\n", FP());
#endif
}
} else {
// Skip token for error recovery.
getNextToken();
}
}
/// top ::= definition | external | expression | ';'
static void MainLoop() {
while (1) {
#ifndef MINIMAL_STDERR_OUTPUT
fprintf(stderr, "ready> ");
#endif
switch (CurTok) {
case tok_eof: return;
case ';': getNextToken(); break; // ignore top-level semicolons.
case tok_def: HandleDefinition(); break;
case tok_extern: HandleExtern(); break;
default: HandleTopLevelExpression(); break;
}
}
}
//===your_sha256_hash------===//
// "Library" functions that can be "extern'd" from user code.
//===your_sha256_hash------===//
/// putchard - putchar that takes a double and returns 0.
extern "C"
double putchard(double X) {
putchar((char)X);
return 0;
}
/// printd - printf that takes a double prints it as "%f\n", returning 0.
extern "C"
double printd(double X) {
printf("%f", X);
return 0;
}
extern "C"
double printlf() {
printf("\n");
return 0;
}
//===your_sha256_hash------===//
// Main driver code.
//===your_sha256_hash------===//
int main(int argc, char **argv) {
InitializeNativeTarget();
LLVMContext &Context = TheContext;
// Install standard binary operators.
// 1 is lowest precedence.
BinopPrecedence['='] = 2;
BinopPrecedence['<'] = 10;
BinopPrecedence['+'] = 20;
BinopPrecedence['-'] = 20;
BinopPrecedence['/'] = 40;
BinopPrecedence['*'] = 40; // highest.
// Make the module, which holds all the code.
TheModule = new Module("my cool jit", Context);
// Create the JIT. This takes ownership of the module.
std::string ErrStr;
TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
if (!TheExecutionEngine) {
fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
exit(1);
}
FunctionPassManager OurFPM(TheModule);
// Set up the optimizer pipeline. Start with registering info about how the
// target lays out data structures.
OurFPM.add(new DataLayout(*TheExecutionEngine->getDataLayout()));
// Provide basic AliasAnalysis support for GVN.
OurFPM.add(createBasicAliasAnalysisPass());
// Promote allocas to registers.
OurFPM.add(createPromoteMemoryToRegisterPass());
// Do simple "peephole" optimizations and bit-twiddling optzns.
OurFPM.add(createInstructionCombiningPass());
// Reassociate expressions.
OurFPM.add(createReassociatePass());
// Eliminate Common SubExpressions.
OurFPM.add(createGVNPass());
// Simplify the control flow graph (deleting unreachable blocks, etc).
OurFPM.add(createCFGSimplificationPass());
OurFPM.doInitialization();
// Set the global so the code gen can use this.
TheFPM = &OurFPM;
// Prime the first token.
#ifndef MINIMAL_STDERR_OUTPUT
fprintf(stderr, "ready> ");
#endif
getNextToken();
// Run the main "interpreter loop" now.
MainLoop();
// Print out all of the generated code.
TheFPM = 0;
#ifndef MINIMAL_STDERR_OUTPUT
TheModule->print(errs(), nullptr);
#endif
return 0;
}
```
|
Moree Baths and Swimming Pool is a heritage-listed swimming pool at Anne Street, Moree, New South Wales, Australia. It was the site of one of the successful protests by Aboriginal Australians for their rights during the Freedom Ride in February 1965. The site was added to the Australian National Heritage List on 6 September 2013.
History
By-laws prohibited Aboriginal people from going to pubs or clubs or the swimming baths in Moree, and they were not allowed to walk on the sidewalk or play football in the local team. The local cinema was segregated - Blacks had to sit in the front rows. Lyall Munro Snr and the Moree Aboriginal Advancement Committee worked hard to change these segregationist policies.
In early 1965 a group of students from the University of Sydney led by Aboriginal student activist Charles Perkins embarked upon a bus trip known as the Freedom Ride through outback NSW and Queensland to highlight racial inequalities in Australia at the time. The trip was based on the "Freedom Rides" that occurred as part of the civil rights movement in the United States in the early 1960s. The bus travelled to number of towns where racial discrimination had been identified with the aim of highlighting the inequalities and raising the profile of this issue amongst the broader Australian community. A number of towns were visited including Walgett and Kempsey but in Moree, where a ban on Aboriginal use of the local pool was in force, the trip gained a national profile in the media and raised the profile of Charles Perkins as an iconic figure for the Indigenous community.
The events at the Moree Swimming Baths in February 1965 constitute a defining moment in the history of race relations in Australia. The activities of the Student Action for Aborigines group at Moree drew the attention of the public to the informal and institutional racial segregation practised at that time in outback towns in New South Wales. The events at Moree also highlighted the failures at both state and federal levels; while both spoke rhetoric of inclusion into the wider Australian society, Aboriginal people in country towns were still being excluded from sharing basic facilities. The publicity that the events at the Moree baths attracted contributed to shaping a climate of opinion resulting in a resounding Yes vote in the 1967 referendum, leading to a change in the Australian Constitution to allow the Australian Government to make laws specifically for Aboriginal people. The constitutional amendment provided the legal basis for subsequent Australian Government involvement in Aboriginal and Torres Strait Islander affairs, and also led to increased recognition of the importance of Indigenous rights in Australia.
The Freedom Ride and the events at Moree have their origins in a heightened concern about racial discrimination in Australia after the Second World War. In 1945 the international community, in its attempts to provide peace and security in a world traumatised by the social and economic disruption of total war, agreed to recognise the political aspirations of, and to promote self-government in, colonised countries.
In 1960 the British Prime Minister, Harold MacMillan responded to the Sharpeville massacre in Cape Town by delivering his "Winds of Change" speech to the South African Parliament. The speech recognised the inevitable growth of African national consciousness. The Australian Prime Minister, Robert Menzies, and MacMillan tried to develop a form of words that would keep the Commonwealth intact. However, the final statement released at the end of the 1961 meeting of Commonwealth Prime Ministers expressed concern at the effect that South Africa's racial policies could have on relations between Commonwealth countries that were members of a multi-racial association of people.
Menzies declined to become involved in overt criticism of apartheid, arguing that it was an internal matter for South Africa in which Australia should not interfere. Despite the government's silence, an anti-apartheid movement began to form which included the National Union of Australian University Students.
South Africa was not the only country where there were laws institutionalising segregation and racial discrimination. In the early 1960s, protests by the civil rights movement against racial segregation laws in the United States of America led to brutal response by police in southern states. The police response and subsequent mass jailing received widespread coverage in Australia. In response to the mass protests and arrests in Birmingham, Alabama, the American President, John Kennedy, introduced a Civil Rights Bill to Congress in 1963. His successor, Lyndon Johnson, sought to push the bill through Congress in the early months of 1964. Sydney University students decided to protest outside the United States consulate on 6 May 1964 in support of the Bill, and against the senators from southern states who were attempting through filibuster to prevent its passage. When police began arresting protestors, fellow students tried to free them. The initial scuffle turned into what one newspaper described as "an all-in brawl", leading to extensive media publicity.
International and some local reports of the demonstration included suggestions that demonstrators were hypocritical because they focused on fashionable American civil rights issues but did not consider the treatment of Australia's Indigenous minority, which was also racially discriminatory. In 1965, assimilation rather than segregation had been Australian Government policy for at least a decade, but the Australian Government powers were limited to persuasion since Aboriginal policy was firmly a matter for the state governments at this time. In his statement after the 1961 Native Welfare Conference, the Hon Paul Hasluck, the Australian Government Minister for Territories, described this policy as one that would enable Aboriginal people to:
"... live as members of a single Australian community, enjoying the same responsibilities, observing the same customs and influenced by the same beliefs, hopes and loyalties as other Australians."
Discriminatory legislation was removed by the Australian Government and state governments in the early 1960s. The last two states to grant Aboriginal people voting rights were Western Australia in 1962, and Queensland in 1962 (for Australian elections) and 1965 (for state elections). In New South Wales, Aboriginal policy was managed by the Aborigines Welfare Board (AWB), which sought either to keep people on its managed stations or to exert control over the rest through a network of district welfare officers. Typically, Aboriginal people lived on the fringes of towns, either in unhealthy shanty settlements or in highly regulated stations. They continued to suffer the effects of racial discrimination at a local level, socially, economically, and culturally.
There was, however, a growing movement for Aboriginal rights in the late 1950s and early 1960s, represented most clearly by the organisations brought together by the Federal Council for the Advancement of Aborigines (in 1964 Torres Strait Islanders were added so that the acronym became FCAATSI). Students had not been a significant part of this movement, but after the criticisms of their actions outside the US Embassy in May 1964, and influenced by the arrival the year before of Charles Perkins and Gary Williams as the first two Aboriginal students at the University of Sydney, they began to organise a very successful student-organised demonstration and concert. This took place on National Aborigines Day in Hyde Park in Sydney and was followed by the formation in July 1964 of a more permanent organisation, Student Action for Aborigines (SAFA). This organisation drew people from many of the political, religious and recreational clubs in the University and it had an Aboriginal student, Charles Perkins, as Chairman.
The proposed Freedom Ride with its focus on racial discrimination and segregation resonated with Charles Perkins' life. He was born at The Bungalow in Alice Springs. His Eastern Arrernte mother, recognising there were limited educational opportunities in Alice Springs, took up an offer for him to go to St Francis House, an Anglican home for boys of mixed Aboriginal and other descent in Semaphore South, Adelaide. He had encountered discrimination against Aboriginal people in Alice Springs and this continued when he moved to Adelaide.ref name=AHD-106098-8>The Times 19 October 2000</ref>
One of the suggested activities for the SAFA group, which was inspired by the Freedom Rides in America, was a bus tour of Aboriginal settlements. Unlike the American Freedom Rides, which aimed to challenge segregation on interstate buses and at interstate bus terminals in the south, SAFA planned their bus tour to highlight the plight of Aboriginal people in rural Australia on a range of issues. Their aim was to undertake a social survey into the extent of racial discrimination in country towns, and then to draw discrimination to the attention of the wider Australian public through the press, radio and television. They wanted to point out the discriminatory barriers and inadequacies in health and housing as well as supporting Aboriginal people in challenging the status quo. The group decided to adopt Martin Luther King's approach of non-violent resistance when dealing with opponents.
Preparations for the trip included a number of fundraisers including folk concerts, dances and sales of Christmas cards. SAFA also received donations from the Student Union, and each student participant contributed ten pounds. They heard talks and produced a reading list about the barriers facing Aboriginal people in outback New South Wales to help them prepare themselves for the trip. The group also had several people as sources of information on discrimination and segregation in the towns in northern New South Wales. One was Jack Horner of the Aboriginal Australian Fellowship. He provided information on issues in a number of towns in outback New South Wales including Walgett, Moree and Kempsey. He also advised the SAFA about recent reports and conferences dealing with Aboriginal health and education. Charles Perkins, the President of the group was another source of information for the bus trip. During the summer, he worked for the Foundation for Aboriginal Affairs, where his interaction with job seekers, evicted families and those requiring access to social services enabled him to gain an understanding of the issues faced by Aboriginal people in New South Wales. He gained further insight into racial prejudice and segregation in some of the towns when he was invited to join a light plane tour through New South Wales with a journalist, Craig Williams, and the Reverend Ted Noffs, who had agreed to help the students design their survey.
With all the preparations completed, the Freedom Ride bus left Sydney on 13 February 1965. Its first stop was Wellington where the students conducted surveys and investigations, highlighting social injustices and uncovering evidence of racial discrimination. However, without local Aboriginal contacts and with insufficient firm information to justify a demonstration they moved onto to the next town, Gulargambone. While the conditions under which Aboriginal people lived there were quite shocking, there was not a clear case of racial discrimination on which to demonstrate. The next stop was Walgett, and here the Freedom-riders took action. Walgett had both an existing group of Aboriginal activists and some clear cases of racial discrimination. It proved to be the first real showdown for the Freedom Riders. They spent their first day conducting interviews to obtain information about segregation and racial discrimination and found that the cinema, the Returned Servicemen's League (RSL) club, the town's two hotels and a frock shop were all segregated. The Freedom Riders picketed the Walgett RSL club from noon until sunset holding placards stating "Walgett: Australian's disgrace", "Bar the Colour Bar", "Good enough for Tobruk - why not Walgett RSL?".
Walgett was the first big test for the students. While their protest did little to change the attitudes of the townsfolk, they encouraged the Aboriginal community to push for change. Aboriginal people who participated in pickets were bitter at the ongoing discrimination they experienced in their town and they continued to protest and agitate for desegregation in the establishments that still upheld a colour ban after the protestors left. Initially, there was little media interest in the events in Walgett. However, a report by Bruce Maxwell, a cadet reporter for The Herald, brought the SAFA Freedom Ride into the national spotlight. The Sydney Morning Herald and The Daily Mirror newspapers as well as TV and radio now began to report on the next stage of the Freedom Ride in Moree.
The pattern of racial discrimination and segregation in Moree was similar to that found in Walgett with some firms refusing to employ Aboriginal people, and most hotels refusing to serve them. The students' attention, however, focused on the swimming pool, where a council by-law prevented Aboriginal people's entry. This was an example of discrimination enforceable under local ordinance so it was seen to be similar to officially sanctioned apartheid in South Africa and segregation in the United States. In addition, a local councillor, alderman Bob Brown, had repeatedly tried to get the council to allow Aborigines to use the baths, but to no avail - he could not even get a seconder for his motion.
Initially, the Freedom Riders held a picket at the Moree council chambers to protest against the exclusion of Aboriginal people (except for school children during school hours) from the Moree baths. The next day Bob Brown and the Freedom Riders tried to take Aboriginal children into the pool. The pool manager argued heatedly with the student leaders. The impasse ended when the mayor agreed to allow the children in. That evening, the students held a public meeting to explain why they were in Moree and to present their survey results. Initially the largely white audience reacted angrily and some left, but after discussion the atmosphere changed. The meeting concluded by passing a motion that the by-law segregating the pool should be removed, which the mayor said he would take to the council.
The Freedom Riders left Moree the next day, jubilant that the colour ban had been lifted. While the students travelled to Boggabilla and then to Warwick in southern Queensland, Bob Brown tried to take another group of Aboriginal children to the pool but the pool manager refused them entry and decided to close the pool. Following an emergency council meeting, the mayor arrived and ordered the manager to re-open the pool and enforce the by-law providing for segregation of the baths. The following day Bob Brown called the Freedom Riders to let them know what had happened. Charles Perkins had flown to Sydney to be interviewed for a television programme. The students phoned the Methodist Minister in Moree who confirmed Bob Brown's story and told them that they would not be welcome in Moree. The students decided to turn the bus around and return to Moree.
The Freedom Riders stopped at Inverell that night and picked up Charles Perkins in the morning. Charles felt that the opportunity to achieve a "break through" was at stake and saw Moree as the place to do this. On returning to Moree, the Freedom Riders again collected a number of Aboriginal children from the mission to gain admittance into the swimming pool. They attempted to enter the pool with the children for three hours. By this time, a large crowd of locals had gathered outside the pool. It was hostile and tempers were inflamed. Some locals threw eggs and tomatoes. They knocked some students down and at least one was punched. Fights broke out and police arrested several crowd members. The media reported the attacks on the students as "little different from the American South".
A breakthrough came when the mayor of Moree, Bill Lloyd, came down to the baths and informed the students and the crowd that he was prepared to sign a motion to rescind the 1955 by-law. After some negotiation, the Freedom Riders accepted these assurances and agreed to leave. They boarded the bus under a hail of eggs and tomatoes and the police provided a protective escort as the bus left town.
The Freedom Riders continued their journey, visiting the coastal towns in northern New South Wales to undertake their surveys and highlight instances of racial discrimination. While the students demonstrated against particular instances of discrimination and segregation in towns like Kempsey and Bowraville, the local reactions were more muted than those in Moree.
The reports and photos in the major newspapers of the events at Moree shocked many white Australians, making them aware of the plight of Aboriginal people. By drawing attention to both informal and officially sanctioned segregation and racial discrimination, the Freedom Ride helped to show that governmental rhetoric, that Aboriginal people should share in the benefits and opportunities of Australians generally, was not being applied in practice.
The Freedom Riders highlighted the fact that, contrary to government policy, segregation and discrimination were endemic in many of the rural towns of New South Wales. The council ordinance prohibiting Aboriginal people from using the Moree baths demonstrated that discrimination was officially sanctioned in some cases. Whether the Australian Government was unable or unwilling to tackle such contradictory policies is unclear. Section 51 of the constitution, prohibited the Government from passing laws specifically for Aboriginal Australians. There was also a lack of will to use the external affairs powers to address racial discrimination.
By highlighting endemic racism in Australia, the Freedom Ride contributed to the passage of the 1967 referendum, which altered the constitution to allow the Commonwealth to make laws for Aboriginal people. It also contributed to the passage in 1975 of legislation prohibiting racial discrimination and encouraged some Aboriginal people to become active in challenging the status quo of segregation and discrimination. The Freedom Ride has been described as one of those transitional moments in Australian history when one era fades and another takes its place.
Description
Moree Baths and Swimming Pool is at about 0.5ha, Lot 20 bounded by Anne Street, Gosport Street and Warialda Street in Moree.
The Moree Hot Artesian Pool Complex (Moree baths) is owned and managed by the Moree Plains Shire Council. The original hot pool opened in 1895 when the first bore that tapped into the Great Artesian Basin was completed. The bore delivered mineral waters, heated naturally to about 41 degrees Celsius. A small basin was originally excavated and gravelled. This was later upgraded with a small wooden lined basin for bathing. The original bore ceased to flow in 1957, and the hot mineral waters are now pumped to the baths. Currently the large municipal complex comprises three tiled pools.
Condition
The building is still in use and is in good condition. Since 1965 the exterior has been modified and there have been minor refurbishments to the interior of the baths and swimming pool. These modifications have not affected its heritage value relating to the 1965 Freedom Ride.
Heritage listing
In 1965 student protest actions at the Moree baths highlighted the racial discrimination and segregation experienced by Aboriginal people in Australian rural towns and the outback and forced the broader Australia community to look at the way it treated its Indigenous population. The protest was an important contributor to the climate of opinion which resulted in a yes vote in the 1967 referendum to change the Australian Constitution regarding the status of Aboriginal Australians. That change provided a legal basis for subsequent Australian Government involvement in Aboriginal and Torres Strait Islander affairs and an increased recognition at local, state, and national levels of the importance of Indigenous rights in Australia.
The events that occurred at the Moree baths in 1965 also have a special association with the life and works of the Aboriginal activist Dr Charles Nelson Perrurle Perkins AO. Moree was the place where the public first saw him confront people with awkward truths about the treatment of Aborigines. This combined with other events that occurred in the wider Freedom ride, brought Charles Perkins to public prominence as a leading Aboriginal activist and established him as an iconic figure for both young and older Aborigines alike. In addition it clearly demonstrated his commitment to achieving equity for Aboriginal people in Australia, which became a lifelong cause.
Moree Baths and Swimming Pool was listed on the Australian National Heritage List on 6 September 2013 having satisfied the following criteria.
Criterion A: Events, Processes
The Moree baths has outstanding national heritage value under criterion (a) as the place where student protests in 1965 highlighted the legalised segregation and racism experienced by Aboriginal people in outback Australia. It brought the racial discrimination and segregation experienced by the Aboriginal population in Australian country and rural towns to the attention and consciousness of the white Australian population. It forced Australia to look at the way it treated its Indigenous population and showed that racial segregation continued in many towns. The protest was an important contributor to the climate of opinion which produced a yes vote in the 1967 referendum to change the Australian Constitution. From that change came a legal basis for subsequent Commonwealth involvement in Aboriginal and Torres Strait Islander affairs and an increased recognition at local, state, and national levels of the importance of Indigenous rights in Australia.
Criterion H: Significant people
The Moree baths has outstanding heritage value to the nation under criterion (h) as the place that has a special association with the life and works of the Aboriginal activist Dr Charles Nelson Perrurle Perkins AO. The events at the Moree baths in 1965 brought him into public prominence as a leading Aboriginal activist and it was here that his tactic of confronting people with awkward truths about their treatment of Aboriginal people first emerged in a public context. This pattern was repeated throughout his life even when it resulted in costs to him personally. The events that occurred in Moree, and the wider Freedom ride, established Charles Perkins as an iconic figure for both young and older Aboriginal people alike. In addition it clearly demonstrated his commitment to achieving equity for Aboriginal people in Australia, something that became a lifelong cause.
References
Bibliography
Clark, J. 2008, Aborigines and Activism - Race, Aborigines and the Coming of the Sixties to Australia, University of Western Australia Press: Crawley, WA.
Behrendt L. 2007. On Leadership - Inspiration from the life and Legacy of Dr Charles Perkins. The Journal of Indigenous Policy, Issue 7, August 2007.
Briscoe G. 2000. Kwementyaye Perrurle Perkins: a personal memoir. Aboriginal History 24: 251- 255.
Cameron K. 2000. Discovering democracy: Aboriginal people struggle for citizenship Rights. Discussion Paper 6, New South Wales discovering democracy professional development committee.
Curthoys A. 2000. Charles Perkins: no longer around to provoke, irritate, and inspire us all. Aboriginal History 24: 256- 258.
Curthoys A. 2002, Freedom ride: a freedom rider remembers, Allen & Unwin, Crows Nest, NSW.
Curthoys, Ann. 2004, The Freedom Ride - Its Significance Today, Public lecture National Museum of Australia. Public Lecture 4 September 2004.
Ford G.W. 1965. The Student Bus: SAFA interviewed. Outlook 2: 4-10.
Goodall, Heather. 1996. Invasion to Embassy: Land in Aboriginal Politics in New South Wales, 1770-1972, Allen and Unwin, Crows Nest, NSW.
Gunson N. 2000. The imprimatur of Charles Perkin on Aboriginal History. Aboriginal History 24: 258-259.
Hasluck P. 1961. Native Welfare Conference. Statement by leave by Minister for Territories (the Hon. Paul Hasluck M.P.) in the House of Representatives on Thursday 20 April 1961.
Henty-Roberts C. 2000. Kwementyaye Perkins (Dr Charles Nelson Perrule Perkins, AO) 1936 - 2000. Indigenous Law Bulletin, October 2000, Volume 5, Issue 3.
Hughes R. 1998. Interview with Charles Perkins for Australian Biography project. Screen Australia. Retrieved 20 February 2022 from https://www.nfsa.gov.au/collection/curated/australian-biography-charles-perkins-1
Parliament of NSW Government: 2000. Hansard, Legislative Assembly, Death of Charles Nelson Perkins, 1 November 2000 p 9494
Perkins C. 1975. A Bastard Like Me. Sydney: Ure Smith.
Spalding. I. 1965. No Genteel Silence. Crux: The Journal of the Australian Student Christian Movement 68: 2-3.
Marks K. 2000. Obituary Dr Charles Nelson Perrurle Perkins, AO. The Independent, Friday Review 20 October.
Martin A. 2000. Sir Robert Gordon Menzies. In M. Grattan (ed.) Australian Prime Ministers. Sydney: New Holland Publishers. pp. 174-205
Maynard, John. 2011.The Aboriginal Soccer Tribe: A History of Aboriginal Involvement with the World Game (Broome: Magabala Books).
Messenger R. 2002. A ride that began to close Australia's Black and White divide. Canberra Times, September 7.
National Archives of Australia nd. Robert Menzies in office. Downloaded on 25 May 2012 from https://web.archive.org/web/20131113103332/http://primeministers.naa.gov.au/primeministers/menzies/in-office.aspx.
Read P. 1988. 'Darce Cassidy's Freedom Ride. -University of Sydney. Student Action for Aborigines tour of NSW country towns in February 1965 and ABC reporter Darce Cassidy's tapes-' Australian Aboriginal Studies (Canberra), no. 1, pp. 45-53.
Spigelman J. 1965a. Student Action for Aborigines. Vestes 8: 116-118.
Spigelman J. 1965b. Reactions to the SAFA Tour. Dissent 14: 44-48.
Spigelman J. 2001. A moral force for all Australians Walking Together, Council for Aboriginal Reconciliation 30: 12.
Spigelman, J. 2005. 'Charles Perkins Memorial Oration 2005 by Chief Justice of New South Wales at the University of Sydney.
United Nations 1945. Charter of the United Nations and Statute of the International Court of Justice. Downloaded on 25 May 2012 from http://www.un.org/en/documents/charter/index.shtml
Attribution
External links
Australian National Heritage List
Moree, New South Wales
Swimming venues in Australia
Articles incorporating text from the Australian Heritage Database
|
```swift
import Foundation
import KsApi
import Library
import UIKit
final class HelpDataSource: ValueCellDataSource {
func configureRows() {
_ = HelpSectionType.allCases.map { section in
let values = section.cellRowsForSection.map { SettingsCellValue(cellType: $0) }
self.set(
values: values,
cellClass: SettingsTableViewCell.self,
inSection: section.rawValue
)
}
}
func cellTypeForIndexPath(indexPath: IndexPath) -> HelpType? {
let value = self[indexPath] as? SettingsCellValue
return value?.cellType as? HelpType
}
override func configureCell(tableCell cell: UITableViewCell, withValue value: Any) {
switch (cell, value) {
case let (cell as SettingsTableViewCell, value as SettingsCellValue):
cell.configureWith(value: value)
default:
assertionFailure("Unrecognized (cell, viewModel) combo.")
}
}
}
```
|
```objective-c
//===- Thumb1FrameLowering.h - Thumb1-specific frame info stuff ---*- C++ -*-=//
//
// See path_to_url for license information.
//
//===your_sha256_hash------===//
#ifndef LLVM_LIB_TARGET_ARM_THUMB1FRAMELOWERING_H
#define LLVM_LIB_TARGET_ARM_THUMB1FRAMELOWERING_H
#include "ARMFrameLowering.h"
namespace llvm {
class ARMSubtarget;
class MachineFunction;
class Thumb1FrameLowering : public ARMFrameLowering {
public:
explicit Thumb1FrameLowering(const ARMSubtarget &sti);
/// emitProlog/emitEpilog - These methods insert prolog and epilog code into
/// the function.
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override;
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override;
bool spillCalleeSavedRegisters(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
const std::vector<CalleeSavedInfo> &CSI,
const TargetRegisterInfo *TRI) const override;
bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
std::vector<CalleeSavedInfo> &CSI,
const TargetRegisterInfo *TRI) const override;
bool hasReservedCallFrame(const MachineFunction &MF) const override;
MachineBasicBlock::iterator
eliminateCallFramePseudoInstr(MachineFunction &MF,
MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI) const override;
/// Check whether or not the given \p MBB can be used as a epilogue
/// for the target.
/// The epilogue will be inserted before the first terminator of that block.
/// This method is used by the shrink-wrapping pass to decide if
/// \p MBB will be correctly handled by the target.
bool canUseAsEpilogue(const MachineBasicBlock &MBB) const override;
/// Disable shrink wrap as tBfar/BL will be used to adjust for long jumps.
bool enableShrinkWrapping(const MachineFunction &MF) const override {
return false;
}
private:
/// Check if the frame lowering of \p MF needs a special fixup
/// code sequence for the epilogue.
/// Unlike T2 and ARM mode, the T1 pop instruction cannot restore
/// to LR, and we can't pop the value directly to the PC when
/// we need to update the SP after popping the value. So instead
/// we have to emit:
/// POP {r3}
/// ADD sp, #offset
/// BX r3
/// If this would clobber a return value, then generate this sequence instead:
/// MOV ip, r3
/// POP {r3}
/// ADD sp, #offset
/// MOV lr, r3
/// MOV r3, ip
/// BX lr
bool needPopSpecialFixUp(const MachineFunction &MF) const;
/// Emit the special fixup code sequence for the epilogue.
/// \see needPopSpecialFixUp for more details.
/// \p DoIt, tells this method whether or not to actually insert
/// the code sequence in \p MBB. I.e., when \p DoIt is false,
/// \p MBB is left untouched.
/// \returns For \p DoIt == true: True when the emission succeeded
/// false otherwise. For \p DoIt == false: True when the emission
/// would have been possible, false otherwise.
bool emitPopSpecialFixUp(MachineBasicBlock &MBB, bool DoIt) const;
};
} // end namespace llvm
#endif // LLVM_LIB_TARGET_ARM_THUMB1FRAMELOWERING_H
```
|
Brahim Déby Itno ( , 6 June 1980 – 2 July 2007) was the son of Idriss Déby, the former president of Chad.
Personal life
Brahim attended the University of Ottawa in Canada as a foreign exchange student and graduated in 2004 with a degree in business administration. It is claimed that, in 2005, President Déby held a secret meeting in which he expressed his desire to have Brahim succeed him at some point; this reportedly caused a rift in the family.
On 24 May 2006, Brahim Déby was arrested outside a Paris nightclub after getting involved in a brawl. During the fight, an unlicensed semi-automatic pistol fell from his pocket. Police later searched his house and found 375 grams of marijuana. On 3 June 2006, Brahim Déby was given a six-month suspended sentence for drugs and arms possession. He was subsequently sacked as an advisor to his father.
Déby was found dead by a security guard in his apartment building's parking garage in Courbevoie, a suburb of Paris, on 2 July 2007. Due to the apparently violent nature of his death, French authorities began investigating it as murder. An autopsy indicated that Déby, who was covered in white powder, died due to asphyxiation, probably from the powder, which was thought to have been sprayed from a fire extinguisher found near his body. Déby had a wound on his head, but this was thought to be unrelated to his death.
According to a lawyer for Déby's family on 17 July, Déby was attacked ten days after arriving in France from Chad; his father had advised him not to return to France due to his past legal issues there. Shortly prior to the attack, Déby was said to be very worried and had received a telephone call. He was attacked by four or five men disguised as policemen who waited for him to arrive at the parking garage. The attackers tasered Déby before killing him by spraying him with the fire extinguisher powder. They then searched his apartment for an unknown reason; it was speculated that the attackers might have been looking for money kept there by Déby.
Déby's body was returned to Chad aboard a specially chartered flight on the morning of 4 July. He was buried at midday on the same day in the Muslim cemetery in Lamadji, to the north of N'Djamena. The funeral was held privately but was nevertheless widely attended, with Déby's extended family, as well as government ministers and various political figures, present.
Five arrests (four in Paris, one in Romania) made in connection with Déby's death were reported on 28 November 2008. In 2011 four men were convicted of "robbery leading to death without intention to kill" and sentenced to prison sentences of between five and thirteen years; one man was acquitted. A further trial was held in 2013, after prosecutors protested the initial sentences as unduly lenient.
References
1980 births
2007 deaths
Chadian people murdered abroad
Deaths from asphyxiation
People murdered in Paris
University of Ottawa alumni
2007 murders in France
2000s murders in Paris
July 2007 events in France
|
```c++
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/ostreams.h"
#include "testing/gtest-support.h"
namespace v8 {
namespace internal {
TEST(Ostream, AsHex) {
auto testAsHex = [](const char* expected, const AsHex& value) {
std::ostringstream out;
out << value;
std::string result = out.str();
EXPECT_EQ(expected, result);
EXPECT_TRUE(result == expected)
<< "\nexpected: " << expected << "\ngot: " << result << "\n";
};
testAsHex("0", AsHex(0));
testAsHex("", AsHex(0, 0));
testAsHex("0x", AsHex(0, 0, true));
testAsHex("0x0", AsHex(0, 1, true));
testAsHex("0x00", AsHex(0, 2, true));
testAsHex("123", AsHex(0x123, 0));
testAsHex("0123", AsHex(0x123, 4));
testAsHex("0x123", AsHex(0x123, 0, true));
testAsHex("0x123", AsHex(0x123, 3, true));
testAsHex("0x0123", AsHex(0x123, 4, true));
testAsHex("0x00000123", AsHex(0x123, 8, true));
}
TEST(Ostream, AsHexBytes) {
auto testAsHexBytes = [](const char* expected, const AsHexBytes& value) {
std::ostringstream out;
out << value;
std::string result = out.str();
EXPECT_EQ(expected, result);
};
// Little endian (default):
testAsHexBytes("00", AsHexBytes(0));
testAsHexBytes("", AsHexBytes(0, 0));
testAsHexBytes("23 01", AsHexBytes(0x123));
testAsHexBytes("23 01", AsHexBytes(0x123, 1));
testAsHexBytes("23 01", AsHexBytes(0x123, 2));
testAsHexBytes("23 01 00", AsHexBytes(0x123, 3));
testAsHexBytes("ff ff ff ff", AsHexBytes(0xFFFFFFFF));
testAsHexBytes("00 00 00 00", AsHexBytes(0, 4));
testAsHexBytes("56 34 12", AsHexBytes(0x123456));
// Big endian:
testAsHexBytes("00", AsHexBytes(0, 1, AsHexBytes::kBigEndian));
testAsHexBytes("", AsHexBytes(0, 0, AsHexBytes::kBigEndian));
testAsHexBytes("01 23", AsHexBytes(0x123, 1, AsHexBytes::kBigEndian));
testAsHexBytes("01 23", AsHexBytes(0x123, 1, AsHexBytes::kBigEndian));
testAsHexBytes("01 23", AsHexBytes(0x123, 2, AsHexBytes::kBigEndian));
testAsHexBytes("00 01 23", AsHexBytes(0x123, 3, AsHexBytes::kBigEndian));
testAsHexBytes("ff ff ff ff", AsHexBytes(0xFFFFFFFF, AsHexBytes::kBigEndian));
testAsHexBytes("00 00 00 00", AsHexBytes(0, 4, AsHexBytes::kBigEndian));
testAsHexBytes("12 34 56", AsHexBytes(0x123456, 1, AsHexBytes::kBigEndian));
}
} // namespace internal
} // namespace v8
```
|
Sean Paul Farrell (born 28 February 1969 in Watford) is an English former professional footballer.
Early life and youth career
Farrell was born and raised in Watford, Hertfordshire, and grew up supporting his local team, Watford. He was invited to try out for Luton Town – Watford's traditional rivals – in 1985, when he was 15 years old. After impressing during his initial trial, he was invited back to play for the club's youth team in a match against Reading, during which he scored two goals in a 4–2 Luton victory. The team offered him an apprenticeship soon after, and he signed before his 16th birthday; he turned professional two years later.
Senior career
Farrell caused a stir among sections of the Luton support with his open support of the club's rivals. He went out on loan to Colchester United in 1988, and broke into the Luton side during the 1990–91 season, when he made twenty appearances. However, the return of David Pleat to Luton heralded a loan move to Northampton Town in 1991 before a permanent £100,000 move to Fulham. At Fulham he scored 31 goals in 94 games before moving to Peterborough United in 1994. In 1997, he joined Notts County, and played there for four years before joining Burton Albion, where he ended his career due to injury in 2003.
After football
Farrell now lives in Nottingham and works in the area.
Honours
Club
Notts County
Football League Division Three Winner (1): 1997–98
References
External links
1969 births
Living people
English Football League players
English men's footballers
Luton Town F.C. players
Colchester United F.C. players
Northampton Town F.C. players
Fulham F.C. players
Peterborough United F.C. players
Notts County F.C. players
Burton Albion F.C. players
Men's association football forwards
Footballers from Watford
|
```javascript
/**
* @license Apache-2.0
*
*
*
* 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.
*/
'use strict';
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var sdsapxsumpw = require( './sdsapxsumpw.js' );
var ndarray = require( './ndarray.js' );
// MAIN //
setReadOnly( sdsapxsumpw, 'ndarray', ndarray );
// EXPORTS //
module.exports = sdsapxsumpw;
```
|
The Herero Wars were a series of colonial wars between the German Empire and the Herero people of German South West Africa (present-day Namibia). They took place between 1904 and 1908.
Background
Pre-colonial South-West Africa
The Hereros were cattle grazers, occupying most of central and northern South West Africa. Under the leadership of Jonker Afrikaner, who died in 1861, and then later under the leadership of Samuel Maharero, they had achieved supremacy over the Nama and Orlam peoples in a series of conflicts that had in their later stages, seen the extensive use of fire-arms obtained from European traders.
German colonization
In the early 1880s, the German statesman Otto von Bismarck, reversing his previous rejection of colonial acquisitions, decided on a policy of imperial expansion. In 1882 Bismarck gave permission to Adolf Lüderitz to obtain lands which Germany would bring within its "protection", under the conditions that a port was established within the territories taken and that there was "clear title" to the land. Lüderitz bought the title to Angra Pequena (later renamed Lüderitz Bay) from Joseph Fredericks, a chief of the Oorlam people, in exchange for 200 rifles, 2,500 German marks, and some lead toy soldiers, and established a port there. Clarification of Germany's title among the European powers took some time, as the British demurred in response to a German request to clarify the boundaries of their title, however in April 1884 Bismarck instructed the German consul in declare "Lüderitzland" (as Lüderitz's holding in South-West Africa had become known) as under the "protection" of the German Reich. Lüderitz steadily spread Germany's influence throughout the South-West African territory until by 1885 only one tribe within it – the Witboois – had not concluded some kind of arrangement with Germany.
Whilst Rhenish missionaries, traders, and other Europeans had been present in the territory since the 1830s, it was only with the advent of Germany's claim to South-West Africa that German settlement of the territory began in earnest. By 1903 there were roughly 4,682 European settlers in the protectorate of whom nearly 3,000 were Germans, most of them in the towns of Lüderitz, Swakopmund, and Windhoek. The advent of large-scale German settlement also brought about changes in the treatment of the native Herero and Nama peoples by Europeans, with native people facing increased legal discrimination and expropriation of land for the use of European settlers.
Rebellion
In 1903, some of the Khoi and Herero tribes rose in revolt and about 120-150 German settlers were killed, with many victims of the uprising tortured and mutilated before death. Troops were sent from Germany to re-establish order but only dispersed the rebels, led by Chief Samuel Maharero. In a famous letter to Hendrik Witbooi, the Namaqua chief, Maharero sought to organize his rebellion against the Germans while building alliances with the other tribes, exclaiming Let us die fighting!
The Herero led a guerrilla campaign, conducting fast hit and run operations then melting back into the terrain they knew well, preventing the Germans from gaining an advantage with their modern artillery and machine-guns. However a conclusive battle was fought on 11 August 1904, at the Battle of Waterberg in the Waterberg Mountains. Chief Maharero believed his six to one advantage over the Germans would allow him to win in a final showdown. The Germans had time to bring forward their artillery and heavy weapons. Both sides took heavy losses, but the Herero were scattered and defeated.
In October 1904, General Lothar von Trotha issued orders to kill every male Herero and drive women and children into the desert. As soon as the news of this order reached Germany, it was repealed, but Trotha initially ignored Berlin. When the extermination order was finally suspended at the end of 1904, surviving tribesmen were herded into concentration camps, while others were transferred as slave labor to German businesses; many Herero died of overwork and malnutrition.
It took the Germans until 1908 to re-establish authority over the territory. By that time tens of thousands of Africans (estimates range from 34,000 to 110,000) had been either killed or died of thirst while fleeing. 65,000 of 80,000 Hereros and at least 10,000 of 20,000 Nama died as a result of the conflict.
At the height of the campaign, some 19,000 German troops were involved.
At about the same time, diamonds were discovered in the territory, which briefly greatly boosted its prosperity.
Aftermath
In 1915, during World War I, South African forces occupied it in the so-called South West Africa Campaign, and SW Africa officially became a mandate of South Africa in 1920.
On 16 August 2004, 100 years after the war, the German government officially apologised for the atrocities. "We Germans accept our historic and moral responsibility and the guilt incurred by Germans at that time," said Heidemarie Wieczorek-Zeul, Germany's development aid minister. In addition, she admitted that the massacres were equivalent to genocide.
Not until 2015 did the German government admit that the massacres were equivalent to genocide and again apologised in 2016. The Herero are suing the German government in a class action lawsuit. In 2021, Germany announced that they would repay Namibia €1.1 billion.
In literature
The Herero Wars and the massacres are both depicted in a chapter of the 1963 novel V. by Thomas Pynchon. The tragic story of the Herero and Namaqua Genocide also appears in Pynchon's 1973 novel Gravity's Rainbow.
The heavy toll of the Herero and Namaqua Genocide on individual lives and the fabric of Herero culture is seen in the 2013 historical novel Mama Namibia by Mari Serebrov.
The war and the massacres are both significantly featured in The Glamour of Prospecting, a contemporary account by Frederick Cornell of his attempts to prospect for diamonds in the region. In the book, he describes his first-hand accounts of witnessing the concentration camp on Shark Island amongst other aspects of the conflict.
See also
Herero and Namaqua genocide
References
Further reading
German colonisation in Africa
Guerrilla wars
Historical events in Namibia
Conflicts involving the German Empire
Imperialism
Conflicts in 1904
Conflicts in 1905
Conflicts in 1906
Conflicts in 1907
Conflicts in 1908
1900s in German South West Africa
African resistance to colonialism
|
Kevo Strict Nature Reserve () is a strict nature reserve located in Utsjoki, northern Lapland, Finland. It was established in 1956 and covers .
The reserve is a popular backpacking destination due to its canyon-like gorge valley. A central part of the reserve is the long and, at places, deep Kevojoki canyon, on the bottom of which flows the Kevojoki river. It is surrounded by more level fell upland.
Walking in the reserve is only permitted along two marked routes. The Kevo backpacking route is long and follows the gorge valley. The Kuivi route is and goes along the fell area. Both routes are difficult and include e.g. many paddle crossings.
Gallery
External links
Strict nature reserves of Finland
Protected areas of the Arctic
Utsjoki
Geography of Lapland (Finland)
Tourist attractions in Lapland (Finland)
|
```javascript
/**
* @license Apache-2.0
*
*
*
* 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.
*/
'use strict';
// MAIN //
/**
* Returns a stacktrace.
*
* @private
* @returns {(string|void)} stacktrace
*/
function stacktrace() {
var err = new Error();
return err.stack;
}
// EXPORTS //
module.exports = stacktrace;
```
|
Constructive fraud is a legal fiction describing a situation where a person or entity gained an unfair advantage over another by deceitful or unfair methods. Intent does not need to be shown as in the case of actual fraud. Some unfair methods may include not telling customers about defects in a product.
The elements are:
a duty owing by the party to be charged to the complaining party due to their relationship;
violation of that duty by the making of deceptive material misrepresentations of past or existing facts or remaining silent when a duty to speak exists;
reliance thereon by the complaining party;
injury to the complaining party as a proximate result thereof; and
the gaining of an advantage by the party to be charged at the expense of the complaining party.
References
Legal terminology
Legal fictions
|
```javascript
const _ = require('underscore');
function isObj(object) {
return (
object &&
typeof object == 'object' &&
Object.prototype.toString.call(object).toLowerCase() == '[object object]'
);
}
function isArray(object) {
return object && typeof object == 'object' && object.constructor == Array;
}
function getLength(object) {
return Object.keys(object).length;
}
function Compare(objA, objB) {
if (!isObj(objA) && !isObj(objB)) {
if (isArray(objA) && isArray(objB)) {
return CompareArray(objA, objB, true);
}
return objA == objB;
}
if (!isObj(objA) || !isObj(objB)) return false;
if (getLength(objA) != getLength(objB)) return false;
return CompareObj(objA, objB, true);
}
function CompareArray(objA, objB, flag) {
if (objA.length != objB.length) return false;
for (let i in objB) {
if (!Compare(objA[i], objB[i])) {
flag = false;
break;
}
}
return flag;
}
function CompareObj(objA, objB, flag) {
for (var key in objA) {
if (!flag) break;
if (!objB.hasOwnProperty(key)) {
flag = false;
break;
}
if (!isArray(objA[key])) {
if (objB[key] != objA[key]) {
flag = false;
break;
}
} else {
if (!isArray(objB[key])) {
flag = false;
break;
}
var oA = objA[key],
oB = objB[key];
if (oA.length != oB.length) {
flag = false;
break;
}
for (var k in oA) {
if (!flag) break;
flag = CompareObj(oA[k], oB[k], flag);
}
}
}
return flag;
}
exports.jsonEqual = Compare;
exports.isDeepMatch = function(obj, properties) {
if (!properties || typeof properties !== 'object' || Object.keys(properties).length === 0) {
return true;
}
if (!obj || typeof obj !== 'object' || Object.keys(obj).length === 0) {
return false;
}
let match = true;
let keys = Object.keys(properties)
for (let index=0; index< keys.length; index++) {
let i = keys[index];
if (!Compare(obj[i], properties[i])) {
match = false;
break;
}
}
return match;
};
```
|
The following is a list of banana cultivars and the groups into which they are classified. Almost all modern cultivated varieties (cultivars) of edible bananas and plantains are hybrids and polyploids of two wild, seeded banana species, Musa acuminata and Musa balbisiana. Cultivated bananas are almost always seedless (parthenocarpic) and hence sterile, so they are propagated vegetatively (cloned). They are classified into groups according to a genome-based system introduced by Ernest Cheesman, Norman Simmonds, and Ken Shepherd, which indicates the degree of genetic inheritance from the two wild parents and the number of chromosomes (ploidy). Cultivars derived from Musa acuminata are more likely to be used as dessert bananas, while those derived from Musa balbisiana and hybrids of the two are usually plantains or cooking bananas.
Classification of cultivars
Banana plants were originally classified by Linnaeus into two species, which he called Musa paradisiaca – those used as cooking bananas (plantains), and M. sapientum – those used as dessert bananas. The primary center of diversity of cultivated bananas is Southeast Asia. Botanical exploration of this area led to many more species being named, along with subspecies and varieties. However, this approach proved inadequate to deal with the large number of cultivated varieties (cultivars) which were discovered, and many of the names later proved to be synonyms. Furthermore, it was discovered that most cultivated bananas are actually hybrids between two wild species, M. acuminata and M. balbisiana, both first described in 1820 by the Italian botanist Luigi Aloysius Colla, and that Linnaeus' two "species" were both this hybrid, which is now called M. × paradisiaca. Unlike the wild species, which have seeds, cultivated bananas are almost always seedless (parthenocarpic) and hence sterile, so they have to be propagated vegetatively.
In 1955, researchers Norman Simmonds and Ken Shepherd proposed abandoning traditional Latin-based botanical names for cultivated bananas. This approach foreshadowed the International Code of Nomenclature for Cultivated Plants which, in addition to using Latin names based on the International Code of Nomenclature for algae, fungi, and plants, gives cultivars names in a currently spoken language, enclosed in single quotes, and organizes them into "cultivar groups", also not given Latin names.
Banana cultivars derived from M. acuminata and M. balbisiana can be classified into cultivar groups using two criteria. The first is the number of chromosomes: whether the plant is diploid, triploid or tetraploid. The second is relationship to the two ancestral species, which may be determined by genetic analysis or by a scoring system devised by Simmonds and Shepherd. A cultivar is scored on 15 characters, chosen because they differ between the two species. Each character is given a score between one and five according to whether it is typical of M. acuminata or of M. babisiana or is in between. Thus the total score for a cultivar will range from 15 if all characters agree with M. acuminata to 75 if all characters agree with M. balbisiana. Intermediate scores suggest mixed ancestry: for example, 45 would be expected for diploids with equal genetic contributions from both species.
Groups are then named using a combination of the letters "A" and "B". The number of letters shows the ploidy; the proportion of As and Bs the contributions of the ancestral species. The AAB Group, for example, comprises triploid cultivars with more genetic inheritance from M. acuminata than M. balbisiana. A character score of around 35 is expected for members of this group. Within groups, cultivars may be divided into subgroups and then given a cultivar name, e.g. Musa AAA Group (Cavendish Subgroup) 'Robusta'.
In practice, the scoring system and the associated grouping is not as straightforward as the Simmonds and Shepherd naming system implies. For example, a member of the AAB Group should have a score about one third of the way between M. acuminata and M. balbisiana (i.e. about 35) if one third of its chromosomes come from M. balbisiana. However, the cultivars 'Silk' and 'Pome', both classified in the AAB Group, scored 26 and 46 respectively. The cultivar 'Pelipita' is placed in the ABB group, so should have 11 of its 33 chromosomes derived from M. acuminata. However, a technique called "genomic in situ hybridization" (GISH) showed that actually only 8 chromosomes were of this origin. Other lines of evidence suggest a more complex genome structure is present in other banana cultivars, so the group names should not be taken at face value.
Cultivars
The total number of cultivars of bananas and plantains has been estimated to be anything from around 300 to more than 1000. Names are highly confused, even within a single country. Many common names do not refer to a single cultivar or clone; for example 'Lady's Finger' or 'Lady Finger' has been used as the name for members of different genome groups, including AA and AAB. Many other names are synonyms of cultivars grown in the same or different countries. Attempts have been made to create lists of synonyms. In 2000, Valmayor et al. listed equivalent local names for 68 cultivars across five Southeast Asian countries (the Philippines, Malaysia, Indonesia, Thailand and Vietnam), together with their internationally used names. They considered a further 81 cultivars to be unique to one country. In 2007, Ploetz et al. listed more cultivar names and synonyms, with an emphasis on those grown in the islands of the Pacific, but including some grown in areas such as India, Africa and South America. As an example, for the widely grown cultivar 'Dwarf Cavendish', they gave 58 synonyms from 29 countries or geographical areas. ProMusa has created a checklist of banana cultivar names based on available literature.
A recent development is the use of "somaclones" in banana cultivation. Micropropagation involves growing plants from very small amounts of source tissue, sometimes even a single cell, under sterile conditions using artificial techniques to induce growth from mitochondrial relief systems. The purpose of micropropagation is often to produce a large number of genetically identical offspring in the manner of Shannon et al. However, by inducing mutations through various means, it is possible to produce plants which differ slightly from the "parent" plant and from each other ("somaclonal variations"). By growing on these somaclones and selecting those with desirable features, new cultivars can be produced which are very similar to an existing cultivar, but differ in one or two features, such as disease resistance. Somaclones may only be distinguishable by genetic analysis.
Musa section
Musa × paradisiaca is the name for hybrids between Musa acuminata (A) and Musa balbisiana (B), both in Musa section Musa.
AA Group
Diploid Musa acuminata, both wild banana plants and cultivars
Chingan banana
Lacatan banana
Lady Finger banana (Sugar banana)
Pisang jari buaya (Crocodile fingers banana)
Señorita banana (Monkoy, Arnibal banana, Cuarenta dias, Cariñosa, Pisang Empat Puluh Hari, Pisang Lampung)
Sinwobogi banana
Pisang Lilin
Pisang Muli
Pisang Kapas
AAA Group
Triploid Musa acuminata, both wild banana plants and cultivars
Cavendish Subgroup
'Dwarf Cavendish'
'Giant Cavendish' ('Williams')
Formosana (GCTCV-218), a variant with some resistance to Fusarium wilt TR4
'Grand Nain' ('Chiquita')
'Masak Hijau'
'Robusta'
Azman (grown in Turkey)
'Red Dacca'
Dwarf Red banana
Flhorban 920
Gros Michel banana
East African Highland bananas (AAA-EA subgroup)
Pisang Susu ('Kluai Nam Nom')
Pisang Ampyang
Pisang Palembang
AAAA Group
Tetraploid Musa acuminata, both wild bananas and cultivars
Bodles Altafort banana
Golden Beauty banana
AAAB Group
Tetraploid cultivars of Musa × paradisiaca
Atan banana
Goldfinger banana
AAB Group
Triploid cultivars of Musa × paradisiaca. This group contains the Plantain subgroup, composed of "true" plantains or African Plantains. The AAB Group's centre of diversity is Central and West Africa, where a large number of cultivars were domesticated following the introduction of ancestral Plantains from Asia, possibly 2000–3000 years ago.
The Iholena and Maoli-Popo'ulu subgroups are referred to as Pacific plantains.
Iholena subgroup - subgroup of cooking bananas domesticated in the Pacific region
Maoli-Popo'ulu subgroup - subgroup of cooking bananas domesticated in the Pacific region
Maqueño banana
Popoulu banana
Mysore subgroup - cooking and dessert bananas
Mysore banana
Pisang Raja subgroup
Pisang Raja banana
Plantain subgroup
French plantain
Cooking banana
Green French banana
Horn plantain & Rhino Horn banana
Nendran banana
Pink French banana
Tiger banana
Pome subgroup
Pome banana
Prata-anã banana (Dwarf Brazilian banana, Dwarf Prata)
Silk subgroup
Latundan banana (Silk banana, Apple banana, Pisang Raja Sereh)
Others
Pisang Seribu banana
Plu banana
AABB Group
Tetraploid cultivars of Musa × paradisiaca
Kalamagol banana
Pisang Awak (Ducasse banana)
AB Group
Diploid cultivars of Musa × paradisiaca
Ney Poovan banana
ABB Group
Triploid cultivars of Musa × paradisiaca
Blue Java banana (Ice Cream banana, Ney mannan, Ash plantain, Pata hina, Dukuru, Vata)
Bluggoe Subgroup
Bluggoe banana (also known as orinoco and "burro")
Silver Bluggoe banana
Pelipita banana (Pelipia, Pilipia)
Saba Subgroup
Saba banana (Cardaba, Dippig)
Cardaba banana
Benedetta banana
ABBB Group
Tetraploid cultivars of Musa × paradisiaca
Tiparot banana
BB Group
Diploid Musa balbisiana, wild bananas
Callimusa section
Cultivars of Musa lolodensis, Musa maclayi and Musa peekelii belong in Musa section Callimusa.
Fe'i banana
See also
Lists of cultivars
Musa (genus)
True plantains
References
Further reading
External links
Information portal on banana cultivars
Lists of cultivars
|
The Devon and Exeter Institution is a subscription library in the City of Exeter, Devon, founded in 1813 for "The general diffusion of science, literature and the arts". It is situated at 7, Cathedral Close, Exeter, in a building facing the north side of Exeter Cathedral which was formerly the Exeter townhouse of the Courtenay family of Powderham Castle.
Membership
Membership is by annual subscription, although current students and staff of Exeter University may use it free of charge.
Library
The library houses two marble busts by the sculptor Edward Bowring Stephens (1815–1882) of Exeter, of Sir William Webb Follett (1796–1845), MP for Exeter and Sir John Bowring (1792–1872), of Exeter, Governor of Hong Kong and President of the Devon and Exeter Institution 1860–61.
The library's collection consists of approximately 40,000 printed books in addition to prints, documents, drawings, art and a small number of artefacts.
List of presidents
Richard Ford, 1855
Sir John Bowring, 1860–61
History of building
The idea for an institution combining a library, reading room, county museum and venue for public lectures was conceived by William Elford Leach, a young naturalist from Plymouth. Leach approached the Mayor of Exeter with his proposal in June 1812, and fundraising began shortly after. The Institution's aims were agreed in a meeting on 12 August 1813. Membership required the purchase of a £25 share and an annual subscription of £1, limiting its initial membership to affluent, educated gentlemen.
The building in which the Institution is housed at 7, Cathedral Close, was purchased from the Dean and Chapter of Exeter Cathedral and was formerly the Exeter townhouse of the Civil War Roundhead General Sir William Waller (c.1597-1668) of Forde, Wolborough, Devon. Following the death of his son, his eventual heiress was his daughter Margaret Waller (d.1694), who married Sir William Courtenay, 1st Baronet (1628–1702), of Powderham, Devon, to which family she brought the Waller estates including the Exeter townhouse. Her descendants became Viscounts Courtenay and Earls of Devon.
Overmantel in Exeter townhouse
An heraldic overmantel circa 1750, survives in a back room of 7 Cathedral Close, Exeter, the former town house of the Courtenay family of Powderham, now home of the Devon and Exeter Institution. The left hand painted panel shows the arms of William Courtenay, 1st Viscount Courtenay (1711-1762): Quarterly 1st & 4th: Or, three torteaux (Courtenay); 2 & 3: Or, a lion rampant azure (de Redvers, Earl of Devon) impaling Argent, a chevron between three griffins passant sable, the arms of Finch, Earl of Aylesford, the family of his wife. The sinister supporter is one of the Finch heraldic griffins, the dexter one is the Courtenay boar. The Courtenay Latin motto is shown underneath: Ubi lapsus quid feci ("Where did I slip what have I done"). The panel on the right shows the arms of Bishop Peter Courtenay (1432–1492), Bishop of Exeter and Winchester, of the Powderham family. His arms (Courtenay, with a label of three points azure each point of the label charged with three plates for difference) are impaled by the arms of the See of Winchester, which are very similar to the arms of the See of Exeter. The whole is circumscribed by the Garter. The supporters are: dexter, the Courtenay dolphin, sinister, the Courtenay boar. The motto beneath is: Quod verum tutum ("What is true is safe").
Sources
Devon and Exeter Institution website
Devon and Exeter Institution Library and Reading Rooms, leaflet available on site
Pevsner, Nikolaus & Cherry, Bridget, Buildings of England: Devon, London, 2004, p. 413
References
Libraries in Exeter
1813 establishments in England
Organisations based in Devon
Grade II* listed buildings in Devon
Subscription libraries in England
Private libraries in the United Kingdom
|
Górniak is a village in the administrative district of Gmina Lubraniec, within Włocławek County, Kuyavian-Pomeranian Voivodeship, in north-central Poland. It lies approximately east of Lubraniec, south-west of Włocławek, and south of Toruń.
References
Villages in Włocławek County
|
```c++
//
// basic_datagram_socket.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~
//
//
// file LICENSE_1_0.txt or copy at path_to_url
//
#ifndef ASIO_BASIC_DATAGRAM_SOCKET_HPP
#define ASIO_BASIC_DATAGRAM_SOCKET_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <cstddef>
#include "asio/basic_socket.hpp"
#include "asio/detail/handler_type_requirements.hpp"
#include "asio/detail/non_const_lvalue.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/detail/type_traits.hpp"
#include "asio/error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
#if !defined(ASIO_BASIC_DATAGRAM_SOCKET_FWD_DECL)
#define ASIO_BASIC_DATAGRAM_SOCKET_FWD_DECL
// Forward declaration with defaulted arguments.
template <typename Protocol, typename Executor = any_io_executor>
class basic_datagram_socket;
#endif // !defined(ASIO_BASIC_DATAGRAM_SOCKET_FWD_DECL)
/// Provides datagram-oriented socket functionality.
/**
* The basic_datagram_socket class template provides asynchronous and blocking
* datagram-oriented socket functionality.
*
* @par Thread Safety
* @e Distinct @e objects: Safe.@n
* @e Shared @e objects: Unsafe.
*
* Synchronous @c send, @c send_to, @c receive, @c receive_from, @c connect,
* and @c shutdown operations are thread safe with respect to each other, if
* the underlying operating system calls are also thread safe. This means that
* it is permitted to perform concurrent calls to these synchronous operations
* on a single socket object. Other synchronous operations, such as @c open or
* @c close, are not thread safe.
*/
template <typename Protocol, typename Executor>
class basic_datagram_socket
: public basic_socket<Protocol, Executor>
{
private:
class initiate_async_send;
class initiate_async_send_to;
class initiate_async_receive;
class initiate_async_receive_from;
public:
/// The type of the executor associated with the object.
typedef Executor executor_type;
/// Rebinds the socket type to another executor.
template <typename Executor1>
struct rebind_executor
{
/// The socket type when rebound to the specified executor.
typedef basic_datagram_socket<Protocol, Executor1> other;
};
/// The native representation of a socket.
#if defined(GENERATING_DOCUMENTATION)
typedef implementation_defined native_handle_type;
#else
typedef typename basic_socket<Protocol,
Executor>::native_handle_type native_handle_type;
#endif
/// The protocol type.
typedef Protocol protocol_type;
/// The endpoint type.
typedef typename Protocol::endpoint endpoint_type;
/// Construct a basic_datagram_socket without opening it.
/**
* This constructor creates a datagram socket without opening it. The open()
* function must be called before data can be sent or received on the socket.
*
* @param ex The I/O executor that the socket will use, by default, to
* dispatch handlers for any asynchronous operations performed on the socket.
*/
explicit basic_datagram_socket(const executor_type& ex)
: basic_socket<Protocol, Executor>(ex)
{
}
/// Construct a basic_datagram_socket without opening it.
/**
* This constructor creates a datagram socket without opening it. The open()
* function must be called before data can be sent or received on the socket.
*
* @param context An execution context which provides the I/O executor that
* the socket will use, by default, to dispatch handlers for any asynchronous
* operations performed on the socket.
*/
template <typename ExecutionContext>
explicit basic_datagram_socket(ExecutionContext& context,
constraint_t<
is_convertible<ExecutionContext&, execution_context&>::value
> = 0)
: basic_socket<Protocol, Executor>(context)
{
}
/// Construct and open a basic_datagram_socket.
/**
* This constructor creates and opens a datagram socket.
*
* @param ex The I/O executor that the socket will use, by default, to
* dispatch handlers for any asynchronous operations performed on the socket.
*
* @param protocol An object specifying protocol parameters to be used.
*
* @throws asio::system_error Thrown on failure.
*/
basic_datagram_socket(const executor_type& ex, const protocol_type& protocol)
: basic_socket<Protocol, Executor>(ex, protocol)
{
}
/// Construct and open a basic_datagram_socket.
/**
* This constructor creates and opens a datagram socket.
*
* @param context An execution context which provides the I/O executor that
* the socket will use, by default, to dispatch handlers for any asynchronous
* operations performed on the socket.
*
* @param protocol An object specifying protocol parameters to be used.
*
* @throws asio::system_error Thrown on failure.
*/
template <typename ExecutionContext>
basic_datagram_socket(ExecutionContext& context,
const protocol_type& protocol,
constraint_t<
is_convertible<ExecutionContext&, execution_context&>::value,
defaulted_constraint
> = defaulted_constraint())
: basic_socket<Protocol, Executor>(context, protocol)
{
}
/// Construct a basic_datagram_socket, opening it and binding it to the given
/// local endpoint.
/**
* This constructor creates a datagram socket and automatically opens it bound
* to the specified endpoint on the local machine. The protocol used is the
* protocol associated with the given endpoint.
*
* @param ex The I/O executor that the socket will use, by default, to
* dispatch handlers for any asynchronous operations performed on the socket.
*
* @param endpoint An endpoint on the local machine to which the datagram
* socket will be bound.
*
* @throws asio::system_error Thrown on failure.
*/
basic_datagram_socket(const executor_type& ex, const endpoint_type& endpoint)
: basic_socket<Protocol, Executor>(ex, endpoint)
{
}
/// Construct a basic_datagram_socket, opening it and binding it to the given
/// local endpoint.
/**
* This constructor creates a datagram socket and automatically opens it bound
* to the specified endpoint on the local machine. The protocol used is the
* protocol associated with the given endpoint.
*
* @param context An execution context which provides the I/O executor that
* the socket will use, by default, to dispatch handlers for any asynchronous
* operations performed on the socket.
*
* @param endpoint An endpoint on the local machine to which the datagram
* socket will be bound.
*
* @throws asio::system_error Thrown on failure.
*/
template <typename ExecutionContext>
basic_datagram_socket(ExecutionContext& context,
const endpoint_type& endpoint,
constraint_t<
is_convertible<ExecutionContext&, execution_context&>::value
> = 0)
: basic_socket<Protocol, Executor>(context, endpoint)
{
}
/// Construct a basic_datagram_socket on an existing native socket.
/**
* This constructor creates a datagram socket object to hold an existing
* native socket.
*
* @param ex The I/O executor that the socket will use, by default, to
* dispatch handlers for any asynchronous operations performed on the socket.
*
* @param protocol An object specifying protocol parameters to be used.
*
* @param native_socket The new underlying socket implementation.
*
* @throws asio::system_error Thrown on failure.
*/
basic_datagram_socket(const executor_type& ex,
const protocol_type& protocol, const native_handle_type& native_socket)
: basic_socket<Protocol, Executor>(ex, protocol, native_socket)
{
}
/// Construct a basic_datagram_socket on an existing native socket.
/**
* This constructor creates a datagram socket object to hold an existing
* native socket.
*
* @param context An execution context which provides the I/O executor that
* the socket will use, by default, to dispatch handlers for any asynchronous
* operations performed on the socket.
*
* @param protocol An object specifying protocol parameters to be used.
*
* @param native_socket The new underlying socket implementation.
*
* @throws asio::system_error Thrown on failure.
*/
template <typename ExecutionContext>
basic_datagram_socket(ExecutionContext& context,
const protocol_type& protocol, const native_handle_type& native_socket,
constraint_t<
is_convertible<ExecutionContext&, execution_context&>::value
> = 0)
: basic_socket<Protocol, Executor>(context, protocol, native_socket)
{
}
/// Move-construct a basic_datagram_socket from another.
/**
* This constructor moves a datagram socket from one object to another.
*
* @param other The other basic_datagram_socket object from which the move
* will occur.
*
* @note Following the move, the moved-from object is in the same state as if
* constructed using the @c basic_datagram_socket(const executor_type&)
* constructor.
*/
basic_datagram_socket(basic_datagram_socket&& other) noexcept
: basic_socket<Protocol, Executor>(std::move(other))
{
}
/// Move-assign a basic_datagram_socket from another.
/**
* This assignment operator moves a datagram socket from one object to
* another.
*
* @param other The other basic_datagram_socket object from which the move
* will occur.
*
* @note Following the move, the moved-from object is in the same state as if
* constructed using the @c basic_datagram_socket(const executor_type&)
* constructor.
*/
basic_datagram_socket& operator=(basic_datagram_socket&& other)
{
basic_socket<Protocol, Executor>::operator=(std::move(other));
return *this;
}
/// Move-construct a basic_datagram_socket from a socket of another protocol
/// type.
/**
* This constructor moves a datagram socket from one object to another.
*
* @param other The other basic_datagram_socket object from which the move
* will occur.
*
* @note Following the move, the moved-from object is in the same state as if
* constructed using the @c basic_datagram_socket(const executor_type&)
* constructor.
*/
template <typename Protocol1, typename Executor1>
basic_datagram_socket(basic_datagram_socket<Protocol1, Executor1>&& other,
constraint_t<
is_convertible<Protocol1, Protocol>::value
&& is_convertible<Executor1, Executor>::value
> = 0)
: basic_socket<Protocol, Executor>(std::move(other))
{
}
/// Move-assign a basic_datagram_socket from a socket of another protocol
/// type.
/**
* This assignment operator moves a datagram socket from one object to
* another.
*
* @param other The other basic_datagram_socket object from which the move
* will occur.
*
* @note Following the move, the moved-from object is in the same state as if
* constructed using the @c basic_datagram_socket(const executor_type&)
* constructor.
*/
template <typename Protocol1, typename Executor1>
constraint_t<
is_convertible<Protocol1, Protocol>::value
&& is_convertible<Executor1, Executor>::value,
basic_datagram_socket&
> operator=(basic_datagram_socket<Protocol1, Executor1>&& other)
{
basic_socket<Protocol, Executor>::operator=(std::move(other));
return *this;
}
/// Destroys the socket.
/**
* This function destroys the socket, cancelling any outstanding asynchronous
* operations associated with the socket as if by calling @c cancel.
*/
~basic_datagram_socket()
{
}
/// Send some data on a connected socket.
/**
* This function is used to send data on the datagram socket. The function
* call will block until the data has been sent successfully or an error
* occurs.
*
* @param buffers One ore more data buffers to be sent on the socket.
*
* @returns The number of bytes sent.
*
* @throws asio::system_error Thrown on failure.
*
* @note The send operation can only be used with a connected socket. Use
* the send_to function to send data on an unconnected datagram socket.
*
* @par Example
* To send a single data buffer use the @ref buffer function as follows:
* @code socket.send(asio::buffer(data, size)); @endcode
* See the @ref buffer documentation for information on sending multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*/
template <typename ConstBufferSequence>
std::size_t send(const ConstBufferSequence& buffers)
{
asio::error_code ec;
std::size_t s = this->impl_.get_service().send(
this->impl_.get_implementation(), buffers, 0, ec);
asio::detail::throw_error(ec, "send");
return s;
}
/// Send some data on a connected socket.
/**
* This function is used to send data on the datagram socket. The function
* call will block until the data has been sent successfully or an error
* occurs.
*
* @param buffers One ore more data buffers to be sent on the socket.
*
* @param flags Flags specifying how the send call is to be made.
*
* @returns The number of bytes sent.
*
* @throws asio::system_error Thrown on failure.
*
* @note The send operation can only be used with a connected socket. Use
* the send_to function to send data on an unconnected datagram socket.
*/
template <typename ConstBufferSequence>
std::size_t send(const ConstBufferSequence& buffers,
socket_base::message_flags flags)
{
asio::error_code ec;
std::size_t s = this->impl_.get_service().send(
this->impl_.get_implementation(), buffers, flags, ec);
asio::detail::throw_error(ec, "send");
return s;
}
/// Send some data on a connected socket.
/**
* This function is used to send data on the datagram socket. The function
* call will block until the data has been sent successfully or an error
* occurs.
*
* @param buffers One or more data buffers to be sent on the socket.
*
* @param flags Flags specifying how the send call is to be made.
*
* @param ec Set to indicate what error occurred, if any.
*
* @returns The number of bytes sent.
*
* @note The send operation can only be used with a connected socket. Use
* the send_to function to send data on an unconnected datagram socket.
*/
template <typename ConstBufferSequence>
std::size_t send(const ConstBufferSequence& buffers,
socket_base::message_flags flags, asio::error_code& ec)
{
return this->impl_.get_service().send(
this->impl_.get_implementation(), buffers, flags, ec);
}
/// Start an asynchronous send on a connected socket.
/**
* This function is used to asynchronously send data on the datagram socket.
* It is an initiating function for an @ref asynchronous_operation, and always
* returns immediately.
*
* @param buffers One or more data buffers to be sent on the socket. Although
* the buffers object may be copied as necessary, ownership of the underlying
* memory blocks is retained by the caller, which must guarantee that they
* remain valid until the completion handler is called.
*
* @param token The @ref completion_token that will be used to produce a
* completion handler, which will be called when the send completes. Potential
* completion tokens include @ref use_future, @ref use_awaitable, @ref
* yield_context, or a function object with the correct completion signature.
* The function signature of the completion handler must be:
* @code void handler(
* const asio::error_code& error, // Result of operation.
* std::size_t bytes_transferred // Number of bytes sent.
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the completion handler will not be invoked from within this function.
* On immediate completion, invocation of the handler will be performed in a
* manner equivalent to using asio::post().
*
* @par Completion Signature
* @code void(asio::error_code, std::size_t) @endcode
*
* @note The async_send operation can only be used with a connected socket.
* Use the async_send_to function to send data on an unconnected datagram
* socket.
*
* @par Example
* To send a single data buffer use the @ref buffer function as follows:
* @code
* socket.async_send(asio::buffer(data, size), handler);
* @endcode
* See the @ref buffer documentation for information on sending multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*
* @par Per-Operation Cancellation
* On POSIX or Windows operating systems, this asynchronous operation supports
* cancellation for the following asio::cancellation_type values:
*
* @li @c cancellation_type::terminal
*
* @li @c cancellation_type::partial
*
* @li @c cancellation_type::total
*/
template <typename ConstBufferSequence,
ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code,
std::size_t)) WriteToken = default_completion_token_t<executor_type>>
auto async_send(const ConstBufferSequence& buffers,
WriteToken&& token = default_completion_token_t<executor_type>())
-> decltype(
async_initiate<WriteToken,
void (asio::error_code, std::size_t)>(
declval<initiate_async_send>(), token,
buffers, socket_base::message_flags(0)))
{
return async_initiate<WriteToken,
void (asio::error_code, std::size_t)>(
initiate_async_send(this), token,
buffers, socket_base::message_flags(0));
}
/// Start an asynchronous send on a connected socket.
/**
* This function is used to asynchronously send data on the datagram socket.
* It is an initiating function for an @ref asynchronous_operation, and always
* returns immediately.
*
* @param buffers One or more data buffers to be sent on the socket. Although
* the buffers object may be copied as necessary, ownership of the underlying
* memory blocks is retained by the caller, which must guarantee that they
* remain valid until the completion handler is called.
*
* @param flags Flags specifying how the send call is to be made.
*
* @param token The @ref completion_token that will be used to produce a
* completion handler, which will be called when the send completes. Potential
* completion tokens include @ref use_future, @ref use_awaitable, @ref
* yield_context, or a function object with the correct completion signature.
* The function signature of the completion handler must be:
* @code void handler(
* const asio::error_code& error, // Result of operation.
* std::size_t bytes_transferred // Number of bytes sent.
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the completion handler will not be invoked from within this function.
* On immediate completion, invocation of the handler will be performed in a
* manner equivalent to using asio::post().
*
* @par Completion Signature
* @code void(asio::error_code, std::size_t) @endcode
*
* @note The async_send operation can only be used with a connected socket.
* Use the async_send_to function to send data on an unconnected datagram
* socket.
*
* @par Per-Operation Cancellation
* On POSIX or Windows operating systems, this asynchronous operation supports
* cancellation for the following asio::cancellation_type values:
*
* @li @c cancellation_type::terminal
*
* @li @c cancellation_type::partial
*
* @li @c cancellation_type::total
*/
template <typename ConstBufferSequence,
ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code,
std::size_t)) WriteToken = default_completion_token_t<executor_type>>
auto async_send(const ConstBufferSequence& buffers,
socket_base::message_flags flags,
WriteToken&& token = default_completion_token_t<executor_type>())
-> decltype(
async_initiate<WriteToken,
void (asio::error_code, std::size_t)>(
declval<initiate_async_send>(), token, buffers, flags))
{
return async_initiate<WriteToken,
void (asio::error_code, std::size_t)>(
initiate_async_send(this), token, buffers, flags);
}
/// Send a datagram to the specified endpoint.
/**
* This function is used to send a datagram to the specified remote endpoint.
* The function call will block until the data has been sent successfully or
* an error occurs.
*
* @param buffers One or more data buffers to be sent to the remote endpoint.
*
* @param destination The remote endpoint to which the data will be sent.
*
* @returns The number of bytes sent.
*
* @throws asio::system_error Thrown on failure.
*
* @par Example
* To send a single data buffer use the @ref buffer function as follows:
* @code
* asio::ip::udp::endpoint destination(
* asio::ip::address::from_string("1.2.3.4"), 12345);
* socket.send_to(asio::buffer(data, size), destination);
* @endcode
* See the @ref buffer documentation for information on sending multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*/
template <typename ConstBufferSequence>
std::size_t send_to(const ConstBufferSequence& buffers,
const endpoint_type& destination)
{
asio::error_code ec;
std::size_t s = this->impl_.get_service().send_to(
this->impl_.get_implementation(), buffers, destination, 0, ec);
asio::detail::throw_error(ec, "send_to");
return s;
}
/// Send a datagram to the specified endpoint.
/**
* This function is used to send a datagram to the specified remote endpoint.
* The function call will block until the data has been sent successfully or
* an error occurs.
*
* @param buffers One or more data buffers to be sent to the remote endpoint.
*
* @param destination The remote endpoint to which the data will be sent.
*
* @param flags Flags specifying how the send call is to be made.
*
* @returns The number of bytes sent.
*
* @throws asio::system_error Thrown on failure.
*/
template <typename ConstBufferSequence>
std::size_t send_to(const ConstBufferSequence& buffers,
const endpoint_type& destination, socket_base::message_flags flags)
{
asio::error_code ec;
std::size_t s = this->impl_.get_service().send_to(
this->impl_.get_implementation(), buffers, destination, flags, ec);
asio::detail::throw_error(ec, "send_to");
return s;
}
/// Send a datagram to the specified endpoint.
/**
* This function is used to send a datagram to the specified remote endpoint.
* The function call will block until the data has been sent successfully or
* an error occurs.
*
* @param buffers One or more data buffers to be sent to the remote endpoint.
*
* @param destination The remote endpoint to which the data will be sent.
*
* @param flags Flags specifying how the send call is to be made.
*
* @param ec Set to indicate what error occurred, if any.
*
* @returns The number of bytes sent.
*/
template <typename ConstBufferSequence>
std::size_t send_to(const ConstBufferSequence& buffers,
const endpoint_type& destination, socket_base::message_flags flags,
asio::error_code& ec)
{
return this->impl_.get_service().send_to(this->impl_.get_implementation(),
buffers, destination, flags, ec);
}
/// Start an asynchronous send.
/**
* This function is used to asynchronously send a datagram to the specified
* remote endpoint. It is an initiating function for an @ref
* asynchronous_operation, and always returns immediately.
*
* @param buffers One or more data buffers to be sent to the remote endpoint.
* Although the buffers object may be copied as necessary, ownership of the
* underlying memory blocks is retained by the caller, which must guarantee
* that they remain valid until the completion handler is called.
*
* @param destination The remote endpoint to which the data will be sent.
* Copies will be made of the endpoint as required.
*
* @param token The @ref completion_token that will be used to produce a
* completion handler, which will be called when the send completes. Potential
* completion tokens include @ref use_future, @ref use_awaitable, @ref
* yield_context, or a function object with the correct completion signature.
* The function signature of the completion handler must be:
* @code void handler(
* const asio::error_code& error, // Result of operation.
* std::size_t bytes_transferred // Number of bytes sent.
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the completion handler will not be invoked from within this function.
* On immediate completion, invocation of the handler will be performed in a
* manner equivalent to using asio::post().
*
* @par Completion Signature
* @code void(asio::error_code, std::size_t) @endcode
*
* @par Example
* To send a single data buffer use the @ref buffer function as follows:
* @code
* asio::ip::udp::endpoint destination(
* asio::ip::address::from_string("1.2.3.4"), 12345);
* socket.async_send_to(
* asio::buffer(data, size), destination, handler);
* @endcode
* See the @ref buffer documentation for information on sending multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*
* @par Per-Operation Cancellation
* On POSIX or Windows operating systems, this asynchronous operation supports
* cancellation for the following asio::cancellation_type values:
*
* @li @c cancellation_type::terminal
*
* @li @c cancellation_type::partial
*
* @li @c cancellation_type::total
*/
template <typename ConstBufferSequence,
ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code,
std::size_t)) WriteToken = default_completion_token_t<executor_type>>
auto async_send_to(const ConstBufferSequence& buffers,
const endpoint_type& destination,
WriteToken&& token = default_completion_token_t<executor_type>())
-> decltype(
async_initiate<WriteToken,
void (asio::error_code, std::size_t)>(
declval<initiate_async_send_to>(), token, buffers,
destination, socket_base::message_flags(0)))
{
return async_initiate<WriteToken,
void (asio::error_code, std::size_t)>(
initiate_async_send_to(this), token, buffers,
destination, socket_base::message_flags(0));
}
/// Start an asynchronous send.
/**
* This function is used to asynchronously send a datagram to the specified
* remote endpoint. It is an initiating function for an @ref
* asynchronous_operation, and always returns immediately.
*
* @param buffers One or more data buffers to be sent to the remote endpoint.
* Although the buffers object may be copied as necessary, ownership of the
* underlying memory blocks is retained by the caller, which must guarantee
* that they remain valid until the completion handler is called.
*
* @param flags Flags specifying how the send call is to be made.
*
* @param destination The remote endpoint to which the data will be sent.
* Copies will be made of the endpoint as required.
*
* @param token The @ref completion_token that will be used to produce a
* completion handler, which will be called when the send completes. Potential
* completion tokens include @ref use_future, @ref use_awaitable, @ref
* yield_context, or a function object with the correct completion signature.
* The function signature of the completion handler must be:
* @code void handler(
* const asio::error_code& error, // Result of operation.
* std::size_t bytes_transferred // Number of bytes sent.
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the completion handler will not be invoked from within this function.
* On immediate completion, invocation of the handler will be performed in a
* manner equivalent to using asio::post().
*
* @par Completion Signature
* @code void(asio::error_code, std::size_t) @endcode
*
* @par Per-Operation Cancellation
* On POSIX or Windows operating systems, this asynchronous operation supports
* cancellation for the following asio::cancellation_type values:
*
* @li @c cancellation_type::terminal
*
* @li @c cancellation_type::partial
*
* @li @c cancellation_type::total
*/
template <typename ConstBufferSequence,
ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code,
std::size_t)) WriteToken = default_completion_token_t<executor_type>>
auto async_send_to(const ConstBufferSequence& buffers,
const endpoint_type& destination, socket_base::message_flags flags,
WriteToken&& token = default_completion_token_t<executor_type>())
-> decltype(
async_initiate<WriteToken,
void (asio::error_code, std::size_t)>(
declval<initiate_async_send_to>(), token,
buffers, destination, flags))
{
return async_initiate<WriteToken,
void (asio::error_code, std::size_t)>(
initiate_async_send_to(this), token,
buffers, destination, flags);
}
/// Receive some data on a connected socket.
/**
* This function is used to receive data on the datagram socket. The function
* call will block until data has been received successfully or an error
* occurs.
*
* @param buffers One or more buffers into which the data will be received.
*
* @returns The number of bytes received.
*
* @throws asio::system_error Thrown on failure.
*
* @note The receive operation can only be used with a connected socket. Use
* the receive_from function to receive data on an unconnected datagram
* socket.
*
* @par Example
* To receive into a single data buffer use the @ref buffer function as
* follows:
* @code socket.receive(asio::buffer(data, size)); @endcode
* See the @ref buffer documentation for information on receiving into
* multiple buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*/
template <typename MutableBufferSequence>
std::size_t receive(const MutableBufferSequence& buffers)
{
asio::error_code ec;
std::size_t s = this->impl_.get_service().receive(
this->impl_.get_implementation(), buffers, 0, ec);
asio::detail::throw_error(ec, "receive");
return s;
}
/// Receive some data on a connected socket.
/**
* This function is used to receive data on the datagram socket. The function
* call will block until data has been received successfully or an error
* occurs.
*
* @param buffers One or more buffers into which the data will be received.
*
* @param flags Flags specifying how the receive call is to be made.
*
* @returns The number of bytes received.
*
* @throws asio::system_error Thrown on failure.
*
* @note The receive operation can only be used with a connected socket. Use
* the receive_from function to receive data on an unconnected datagram
* socket.
*/
template <typename MutableBufferSequence>
std::size_t receive(const MutableBufferSequence& buffers,
socket_base::message_flags flags)
{
asio::error_code ec;
std::size_t s = this->impl_.get_service().receive(
this->impl_.get_implementation(), buffers, flags, ec);
asio::detail::throw_error(ec, "receive");
return s;
}
/// Receive some data on a connected socket.
/**
* This function is used to receive data on the datagram socket. The function
* call will block until data has been received successfully or an error
* occurs.
*
* @param buffers One or more buffers into which the data will be received.
*
* @param flags Flags specifying how the receive call is to be made.
*
* @param ec Set to indicate what error occurred, if any.
*
* @returns The number of bytes received.
*
* @note The receive operation can only be used with a connected socket. Use
* the receive_from function to receive data on an unconnected datagram
* socket.
*/
template <typename MutableBufferSequence>
std::size_t receive(const MutableBufferSequence& buffers,
socket_base::message_flags flags, asio::error_code& ec)
{
return this->impl_.get_service().receive(
this->impl_.get_implementation(), buffers, flags, ec);
}
/// Start an asynchronous receive on a connected socket.
/**
* This function is used to asynchronously receive data from the datagram
* socket. It is an initiating function for an @ref asynchronous_operation,
* and always returns immediately.
*
* @param buffers One or more buffers into which the data will be received.
* Although the buffers object may be copied as necessary, ownership of the
* underlying memory blocks is retained by the caller, which must guarantee
* that they remain valid until the completion handler is called.
*
* @param token The @ref completion_token that will be used to produce a
* completion handler, which will be called when the receive completes.
* Potential completion tokens include @ref use_future, @ref use_awaitable,
* @ref yield_context, or a function object with the correct completion
* signature. The function signature of the completion handler must be:
* @code void handler(
* const asio::error_code& error, // Result of operation.
* std::size_t bytes_transferred // Number of bytes received.
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the completion handler will not be invoked from within this function.
* On immediate completion, invocation of the handler will be performed in a
* manner equivalent to using asio::post().
*
* @par Completion Signature
* @code void(asio::error_code, std::size_t) @endcode
*
* @note The async_receive operation can only be used with a connected socket.
* Use the async_receive_from function to receive data on an unconnected
* datagram socket.
*
* @par Example
* To receive into a single data buffer use the @ref buffer function as
* follows:
* @code
* socket.async_receive(asio::buffer(data, size), handler);
* @endcode
* See the @ref buffer documentation for information on receiving into
* multiple buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*
* @par Per-Operation Cancellation
* On POSIX or Windows operating systems, this asynchronous operation supports
* cancellation for the following asio::cancellation_type values:
*
* @li @c cancellation_type::terminal
*
* @li @c cancellation_type::partial
*
* @li @c cancellation_type::total
*/
template <typename MutableBufferSequence,
ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code,
std::size_t)) ReadToken = default_completion_token_t<executor_type>>
auto async_receive(const MutableBufferSequence& buffers,
ReadToken&& token = default_completion_token_t<executor_type>())
-> decltype(
async_initiate<ReadToken,
void (asio::error_code, std::size_t)>(
declval<initiate_async_receive>(), token,
buffers, socket_base::message_flags(0)))
{
return async_initiate<ReadToken,
void (asio::error_code, std::size_t)>(
initiate_async_receive(this), token,
buffers, socket_base::message_flags(0));
}
/// Start an asynchronous receive on a connected socket.
/**
* This function is used to asynchronously receive data from the datagram
* socket. It is an initiating function for an @ref asynchronous_operation,
* and always returns immediately.
*
* @param buffers One or more buffers into which the data will be received.
* Although the buffers object may be copied as necessary, ownership of the
* underlying memory blocks is retained by the caller, which must guarantee
* that they remain valid until the completion handler is called.
*
* @param flags Flags specifying how the receive call is to be made.
*
* @param token The @ref completion_token that will be used to produce a
* completion handler, which will be called when the receive completes.
* Potential completion tokens include @ref use_future, @ref use_awaitable,
* @ref yield_context, or a function object with the correct completion
* signature. The function signature of the completion handler must be:
* @code void handler(
* const asio::error_code& error, // Result of operation.
* std::size_t bytes_transferred // Number of bytes received.
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the completion handler will not be invoked from within this function.
* On immediate completion, invocation of the handler will be performed in a
* manner equivalent to using asio::post().
*
* @par Completion Signature
* @code void(asio::error_code, std::size_t) @endcode
*
* @note The async_receive operation can only be used with a connected socket.
* Use the async_receive_from function to receive data on an unconnected
* datagram socket.
*
* @par Per-Operation Cancellation
* On POSIX or Windows operating systems, this asynchronous operation supports
* cancellation for the following asio::cancellation_type values:
*
* @li @c cancellation_type::terminal
*
* @li @c cancellation_type::partial
*
* @li @c cancellation_type::total
*/
template <typename MutableBufferSequence,
ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code,
std::size_t)) ReadToken = default_completion_token_t<executor_type>>
auto async_receive(const MutableBufferSequence& buffers,
socket_base::message_flags flags,
ReadToken&& token = default_completion_token_t<executor_type>())
-> decltype(
async_initiate<ReadToken,
void (asio::error_code, std::size_t)>(
declval<initiate_async_receive>(), token, buffers, flags))
{
return async_initiate<ReadToken,
void (asio::error_code, std::size_t)>(
initiate_async_receive(this), token, buffers, flags);
}
/// Receive a datagram with the endpoint of the sender.
/**
* This function is used to receive a datagram. The function call will block
* until data has been received successfully or an error occurs.
*
* @param buffers One or more buffers into which the data will be received.
*
* @param sender_endpoint An endpoint object that receives the endpoint of
* the remote sender of the datagram.
*
* @returns The number of bytes received.
*
* @throws asio::system_error Thrown on failure.
*
* @par Example
* To receive into a single data buffer use the @ref buffer function as
* follows:
* @code
* asio::ip::udp::endpoint sender_endpoint;
* socket.receive_from(
* asio::buffer(data, size), sender_endpoint);
* @endcode
* See the @ref buffer documentation for information on receiving into
* multiple buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*/
template <typename MutableBufferSequence>
std::size_t receive_from(const MutableBufferSequence& buffers,
endpoint_type& sender_endpoint)
{
asio::error_code ec;
std::size_t s = this->impl_.get_service().receive_from(
this->impl_.get_implementation(), buffers, sender_endpoint, 0, ec);
asio::detail::throw_error(ec, "receive_from");
return s;
}
/// Receive a datagram with the endpoint of the sender.
/**
* This function is used to receive a datagram. The function call will block
* until data has been received successfully or an error occurs.
*
* @param buffers One or more buffers into which the data will be received.
*
* @param sender_endpoint An endpoint object that receives the endpoint of
* the remote sender of the datagram.
*
* @param flags Flags specifying how the receive call is to be made.
*
* @returns The number of bytes received.
*
* @throws asio::system_error Thrown on failure.
*/
template <typename MutableBufferSequence>
std::size_t receive_from(const MutableBufferSequence& buffers,
endpoint_type& sender_endpoint, socket_base::message_flags flags)
{
asio::error_code ec;
std::size_t s = this->impl_.get_service().receive_from(
this->impl_.get_implementation(), buffers, sender_endpoint, flags, ec);
asio::detail::throw_error(ec, "receive_from");
return s;
}
/// Receive a datagram with the endpoint of the sender.
/**
* This function is used to receive a datagram. The function call will block
* until data has been received successfully or an error occurs.
*
* @param buffers One or more buffers into which the data will be received.
*
* @param sender_endpoint An endpoint object that receives the endpoint of
* the remote sender of the datagram.
*
* @param flags Flags specifying how the receive call is to be made.
*
* @param ec Set to indicate what error occurred, if any.
*
* @returns The number of bytes received.
*/
template <typename MutableBufferSequence>
std::size_t receive_from(const MutableBufferSequence& buffers,
endpoint_type& sender_endpoint, socket_base::message_flags flags,
asio::error_code& ec)
{
return this->impl_.get_service().receive_from(
this->impl_.get_implementation(), buffers, sender_endpoint, flags, ec);
}
/// Start an asynchronous receive.
/**
* This function is used to asynchronously receive a datagram. It is an
* initiating function for an @ref asynchronous_operation, and always returns
* immediately.
*
* @param buffers One or more buffers into which the data will be received.
* Although the buffers object may be copied as necessary, ownership of the
* underlying memory blocks is retained by the caller, which must guarantee
* that they remain valid until the completion handler is called.
*
* @param sender_endpoint An endpoint object that receives the endpoint of
* the remote sender of the datagram. Ownership of the sender_endpoint object
* is retained by the caller, which must guarantee that it is valid until the
* completion handler is called.
*
* @param token The @ref completion_token that will be used to produce a
* completion handler, which will be called when the receive completes.
* Potential completion tokens include @ref use_future, @ref use_awaitable,
* @ref yield_context, or a function object with the correct completion
* signature. The function signature of the completion handler must be:
* @code void handler(
* const asio::error_code& error, // Result of operation.
* std::size_t bytes_transferred // Number of bytes received.
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the completion handler will not be invoked from within this function.
* On immediate completion, invocation of the handler will be performed in a
* manner equivalent to using asio::post().
*
* @par Completion Signature
* @code void(asio::error_code, std::size_t) @endcode
*
* @par Example
* To receive into a single data buffer use the @ref buffer function as
* follows:
* @code socket.async_receive_from(
* asio::buffer(data, size), sender_endpoint, handler); @endcode
* See the @ref buffer documentation for information on receiving into
* multiple buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*
* @par Per-Operation Cancellation
* On POSIX or Windows operating systems, this asynchronous operation supports
* cancellation for the following asio::cancellation_type values:
*
* @li @c cancellation_type::terminal
*
* @li @c cancellation_type::partial
*
* @li @c cancellation_type::total
*/
template <typename MutableBufferSequence,
ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code,
std::size_t)) ReadToken = default_completion_token_t<executor_type>>
auto async_receive_from(const MutableBufferSequence& buffers,
endpoint_type& sender_endpoint,
ReadToken&& token = default_completion_token_t<executor_type>())
-> decltype(
async_initiate<ReadToken,
void (asio::error_code, std::size_t)>(
declval<initiate_async_receive_from>(), token, buffers,
&sender_endpoint, socket_base::message_flags(0)))
{
return async_initiate<ReadToken,
void (asio::error_code, std::size_t)>(
initiate_async_receive_from(this), token, buffers,
&sender_endpoint, socket_base::message_flags(0));
}
/// Start an asynchronous receive.
/**
* This function is used to asynchronously receive a datagram. It is an
* initiating function for an @ref asynchronous_operation, and always returns
* immediately.
*
* @param buffers One or more buffers into which the data will be received.
* Although the buffers object may be copied as necessary, ownership of the
* underlying memory blocks is retained by the caller, which must guarantee
* that they remain valid until the completion handler is called.
*
* @param sender_endpoint An endpoint object that receives the endpoint of
* the remote sender of the datagram. Ownership of the sender_endpoint object
* is retained by the caller, which must guarantee that it is valid until the
* completion handler is called.
*
* @param flags Flags specifying how the receive call is to be made.
*
* @param token The @ref completion_token that will be used to produce a
* completion handler, which will be called when the receive completes.
* Potential completion tokens include @ref use_future, @ref use_awaitable,
* @ref yield_context, or a function object with the correct completion
* signature. The function signature of the completion handler must be:
* @code void handler(
* const asio::error_code& error, // Result of operation.
* std::size_t bytes_transferred // Number of bytes received.
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the completion handler will not be invoked from within this function.
* On immediate completion, invocation of the handler will be performed in a
* manner equivalent to using asio::post().
*
* @par Completion Signature
* @code void(asio::error_code, std::size_t) @endcode
*
* @par Per-Operation Cancellation
* On POSIX or Windows operating systems, this asynchronous operation supports
* cancellation for the following asio::cancellation_type values:
*
* @li @c cancellation_type::terminal
*
* @li @c cancellation_type::partial
*
* @li @c cancellation_type::total
*/
template <typename MutableBufferSequence,
ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code,
std::size_t)) ReadToken = default_completion_token_t<executor_type>>
auto async_receive_from(const MutableBufferSequence& buffers,
endpoint_type& sender_endpoint, socket_base::message_flags flags,
ReadToken&& token = default_completion_token_t<executor_type>())
-> decltype(
async_initiate<ReadToken,
void (asio::error_code, std::size_t)>(
declval<initiate_async_receive_from>(), token,
buffers, &sender_endpoint, flags))
{
return async_initiate<ReadToken,
void (asio::error_code, std::size_t)>(
initiate_async_receive_from(this), token,
buffers, &sender_endpoint, flags);
}
private:
// Disallow copying and assignment.
basic_datagram_socket(const basic_datagram_socket&) = delete;
basic_datagram_socket& operator=(
const basic_datagram_socket&) = delete;
class initiate_async_send
{
public:
typedef Executor executor_type;
explicit initiate_async_send(basic_datagram_socket* self)
: self_(self)
{
}
const executor_type& get_executor() const noexcept
{
return self_->get_executor();
}
template <typename WriteHandler, typename ConstBufferSequence>
void operator()(WriteHandler&& handler,
const ConstBufferSequence& buffers,
socket_base::message_flags flags) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a WriteHandler.
ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check;
detail::non_const_lvalue<WriteHandler> handler2(handler);
self_->impl_.get_service().async_send(
self_->impl_.get_implementation(), buffers, flags,
handler2.value, self_->impl_.get_executor());
}
private:
basic_datagram_socket* self_;
};
class initiate_async_send_to
{
public:
typedef Executor executor_type;
explicit initiate_async_send_to(basic_datagram_socket* self)
: self_(self)
{
}
const executor_type& get_executor() const noexcept
{
return self_->get_executor();
}
template <typename WriteHandler, typename ConstBufferSequence>
void operator()(WriteHandler&& handler,
const ConstBufferSequence& buffers, const endpoint_type& destination,
socket_base::message_flags flags) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a WriteHandler.
ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check;
detail::non_const_lvalue<WriteHandler> handler2(handler);
self_->impl_.get_service().async_send_to(
self_->impl_.get_implementation(), buffers, destination,
flags, handler2.value, self_->impl_.get_executor());
}
private:
basic_datagram_socket* self_;
};
class initiate_async_receive
{
public:
typedef Executor executor_type;
explicit initiate_async_receive(basic_datagram_socket* self)
: self_(self)
{
}
const executor_type& get_executor() const noexcept
{
return self_->get_executor();
}
template <typename ReadHandler, typename MutableBufferSequence>
void operator()(ReadHandler&& handler,
const MutableBufferSequence& buffers,
socket_base::message_flags flags) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
detail::non_const_lvalue<ReadHandler> handler2(handler);
self_->impl_.get_service().async_receive(
self_->impl_.get_implementation(), buffers, flags,
handler2.value, self_->impl_.get_executor());
}
private:
basic_datagram_socket* self_;
};
class initiate_async_receive_from
{
public:
typedef Executor executor_type;
explicit initiate_async_receive_from(basic_datagram_socket* self)
: self_(self)
{
}
const executor_type& get_executor() const noexcept
{
return self_->get_executor();
}
template <typename ReadHandler, typename MutableBufferSequence>
void operator()(ReadHandler&& handler,
const MutableBufferSequence& buffers, endpoint_type* sender_endpoint,
socket_base::message_flags flags) const
{
// If you get an error on the following line it means that your handler
// does not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
detail::non_const_lvalue<ReadHandler> handler2(handler);
self_->impl_.get_service().async_receive_from(
self_->impl_.get_implementation(), buffers, *sender_endpoint,
flags, handler2.value, self_->impl_.get_executor());
}
private:
basic_datagram_socket* self_;
};
};
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_BASIC_DATAGRAM_SOCKET_HPP
```
|
Life expectancy at birth in 2013 was 74 for men and 79 for women.
Obesity
In 2014 Sultan Qaboos University published research showing that 30% of the Omani population was overweight and 20% was obese.
Smoking
A ban on smoking in public places was introduced in 2010. Restaurants, malls and other public places were required to allot more than 50% of their space as non-smoking zones. 70% of residents suffer from some kind of curable disease related to smoking.
See also
Healthcare in Oman
List of hospitals in Oman
References
|
```smarty
{{- if .Table.IsJoinTable -}}
{{- else -}}
{{- range $rel := .Table.ToOneRelationships -}}
{{- $ltable := $.Aliases.Table $rel.Table -}}
{{- $ftable := $.Aliases.Table $rel.ForeignTable -}}
{{- $relAlias := $ftable.Relationship $rel.Name -}}
{{- $usesPrimitives := usesPrimitives $.Tables $rel.Table $rel.Column $rel.ForeignTable $rel.ForeignColumn -}}
{{- $colField := $ltable.Column $rel.Column -}}
{{- $fcolField := $ftable.Column $rel.ForeignColumn -}}
{{- $foreignPKeyCols := (getTable $.Tables .ForeignTable).PKey.Columns }}
{{- $canSoftDelete := (getTable $.Tables .ForeignTable).CanSoftDelete $.AutoColumns.Deleted }}
func test{{$ltable.UpSingular}}OneToOneSetOp{{$ftable.UpSingular}}Using{{$relAlias.Local}}(t *testing.T) {
var err error
{{if not $.NoContext}}ctx := context.Background(){{end}}
tx := MustTx({{if $.NoContext}}boil.Begin(){{else}}boil.BeginTx(ctx, nil){{end}})
defer func() { _ = tx.Rollback() }()
var a {{$ltable.UpSingular}}
var b, c {{$ftable.UpSingular}}
seed := randomize.NewSeed()
if err = randomize.Struct(seed, &a, {{$ltable.DownSingular}}DBTypes, false, strmangle.SetComplement({{$ltable.DownSingular}}PrimaryKeyColumns, {{$ltable.DownSingular}}ColumnsWithoutDefault)...); err != nil {
t.Fatal(err)
}
if err = randomize.Struct(seed, &b, {{$ftable.DownSingular}}DBTypes, false, strmangle.SetComplement({{$ftable.DownSingular}}PrimaryKeyColumns, {{$ftable.DownSingular}}ColumnsWithoutDefault)...); err != nil {
t.Fatal(err)
}
if err = randomize.Struct(seed, &c, {{$ftable.DownSingular}}DBTypes, false, strmangle.SetComplement({{$ftable.DownSingular}}PrimaryKeyColumns, {{$ftable.DownSingular}}ColumnsWithoutDefault)...); err != nil {
t.Fatal(err)
}
if err := a.Insert({{if not $.NoContext}}ctx, {{end -}} tx, boil.Infer()); err != nil {
t.Fatal(err)
}
if err = b.Insert({{if not $.NoContext}}ctx, {{end -}} tx, boil.Infer()); err != nil {
t.Fatal(err)
}
for i, x := range []*{{$ftable.UpSingular}}{&b, &c} {
err = a.Set{{$relAlias.Local}}({{if not $.NoContext}}ctx, {{end -}} tx, i != 0, x)
if err != nil {
t.Fatal(err)
}
if a.R.{{$relAlias.Local}} != x {
t.Error("relationship struct not set to correct value")
}
if x.R.{{$relAlias.Foreign}} != &a {
t.Error("failed to append to foreign relationship struct")
}
{{if $usesPrimitives -}}
if a.{{$colField}} != x.{{$fcolField}} {
{{else -}}
if !queries.Equal(a.{{$colField}}, x.{{$fcolField}}) {
{{end -}}
t.Error("foreign key was wrong value", a.{{$colField}})
}
{{if setInclude .ForeignColumn $foreignPKeyCols -}}
if exists, err := {{$ftable.UpSingular}}Exists({{if not $.NoContext}}ctx, {{end -}} tx, x.{{$foreignPKeyCols | stringMap $.StringFuncs.titleCase | join ", x."}}); err != nil {
t.Fatal(err)
} else if !exists {
t.Error("want 'x' to exist")
}
{{else -}}
zero := reflect.Zero(reflect.TypeOf(x.{{$fcolField}}))
reflect.Indirect(reflect.ValueOf(&x.{{$fcolField}})).Set(zero)
if err = x.Reload({{if not $.NoContext}}ctx, {{end -}} tx); err != nil {
t.Fatal("failed to reload", err)
}
{{- end}}
{{if $usesPrimitives -}}
if a.{{$colField}} != x.{{$fcolField}} {
{{else -}}
if !queries.Equal(a.{{$colField}}, x.{{$fcolField}}) {
{{end -}}
t.Error("foreign key was wrong value", a.{{$colField}}, x.{{$fcolField}})
}
if {{if not $.NoRowsAffected}}_, {{end -}} err = x.Delete({{if not $.NoContext}}ctx, {{end -}} tx {{- if and $.AddSoftDeletes $canSoftDelete}}, true{{end}}); err != nil {
t.Fatal("failed to delete x", err)
}
}
}
{{- if $rel.ForeignColumnNullable}}
func test{{$ltable.UpSingular}}OneToOneRemoveOp{{$ftable.UpSingular}}Using{{$relAlias.Local}}(t *testing.T) {
var err error
{{if not $.NoContext}}ctx := context.Background(){{end}}
tx := MustTx({{if $.NoContext}}boil.Begin(){{else}}boil.BeginTx(ctx, nil){{end}})
defer func() { _ = tx.Rollback() }()
var a {{$ltable.UpSingular}}
var b {{$ftable.UpSingular}}
seed := randomize.NewSeed()
if err = randomize.Struct(seed, &a, {{$ltable.DownSingular}}DBTypes, false, strmangle.SetComplement({{$ltable.DownSingular}}PrimaryKeyColumns, {{$ltable.DownSingular}}ColumnsWithoutDefault)...); err != nil {
t.Fatal(err)
}
if err = randomize.Struct(seed, &b, {{$ftable.DownSingular}}DBTypes, false, strmangle.SetComplement({{$ftable.DownSingular}}PrimaryKeyColumns, {{$ftable.DownSingular}}ColumnsWithoutDefault)...); err != nil {
t.Fatal(err)
}
if err = a.Insert({{if not $.NoContext}}ctx, {{end -}} tx, boil.Infer()); err != nil {
t.Fatal(err)
}
if err = a.Set{{$relAlias.Local}}({{if not $.NoContext}}ctx, {{end -}} tx, true, &b); err != nil {
t.Fatal(err)
}
if err = a.Remove{{$relAlias.Local}}({{if not $.NoContext}}ctx, {{end -}} tx, &b); err != nil {
t.Error("failed to remove relationship")
}
count, err := a.{{$relAlias.Local}}().Count({{if not $.NoContext}}ctx, {{end -}} tx)
if err != nil {
t.Error(err)
}
if count != 0 {
t.Error("want no relationships remaining")
}
if a.R.{{$relAlias.Local}} != nil {
t.Error("R struct entry should be nil")
}
if !queries.IsValuerNil(b.{{$fcolField}}) {
t.Error("foreign key column should be nil")
}
if b.R.{{$relAlias.Foreign}} != nil {
t.Error("failed to remove a from b's relationships")
}
}
{{end -}}{{/* end if foreign key nullable */}}
{{- end -}}{{/* range */}}
{{- end -}}{{/* join table */}}
```
|
```objective-c
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
//
// This Source Code Form is subject to the terms of the Mozilla
// with this file, You can obtain one at path_to_url
#ifndef EIGEN_HYPERPLANE_H
#define EIGEN_HYPERPLANE_H
namespace Eigen {
/** \geometry_module \ingroup Geometry_Module
*
* \class Hyperplane
*
* \brief A hyperplane
*
* A hyperplane is an affine subspace of dimension n-1 in a space of dimension n.
* For example, a hyperplane in a plane is a line; a hyperplane in 3-space is a plane.
*
* \tparam _Scalar the scalar type, i.e., the type of the coefficients
* \tparam _AmbientDim the dimension of the ambient space, can be a compile time value or Dynamic.
* Notice that the dimension of the hyperplane is _AmbientDim-1.
*
* This class represents an hyperplane as the zero set of the implicit equation
* \f$ n \cdot x + d = 0 \f$ where \f$ n \f$ is a unit normal vector of the plane (linear part)
* and \f$ d \f$ is the distance (offset) to the origin.
*/
template <typename _Scalar, int _AmbientDim, int _Options>
class Hyperplane
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(_Scalar,_AmbientDim==Dynamic ? Dynamic : _AmbientDim+1)
enum {
AmbientDimAtCompileTime = _AmbientDim,
Options = _Options
};
typedef _Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Eigen::Index Index; ///< \deprecated since Eigen 3.3
typedef Matrix<Scalar,AmbientDimAtCompileTime,1> VectorType;
typedef Matrix<Scalar,Index(AmbientDimAtCompileTime)==Dynamic
? Dynamic
: Index(AmbientDimAtCompileTime)+1,1,Options> Coefficients;
typedef Block<Coefficients,AmbientDimAtCompileTime,1> NormalReturnType;
typedef const Block<const Coefficients,AmbientDimAtCompileTime,1> ConstNormalReturnType;
/** Default constructor without initialization */
EIGEN_DEVICE_FUNC inline Hyperplane() {}
template<int OtherOptions>
EIGEN_DEVICE_FUNC Hyperplane(const Hyperplane<Scalar,AmbientDimAtCompileTime,OtherOptions>& other)
: m_coeffs(other.coeffs())
{}
/** Constructs a dynamic-size hyperplane with \a _dim the dimension
* of the ambient space */
EIGEN_DEVICE_FUNC inline explicit Hyperplane(Index _dim) : m_coeffs(_dim+1) {}
/** Construct a plane from its normal \a n and a point \a e onto the plane.
* \warning the vector normal is assumed to be normalized.
*/
EIGEN_DEVICE_FUNC inline Hyperplane(const VectorType& n, const VectorType& e)
: m_coeffs(n.size()+1)
{
normal() = n;
offset() = -n.dot(e);
}
/** Constructs a plane from its normal \a n and distance to the origin \a d
* such that the algebraic equation of the plane is \f$ n \cdot x + d = 0 \f$.
* \warning the vector normal is assumed to be normalized.
*/
EIGEN_DEVICE_FUNC inline Hyperplane(const VectorType& n, const Scalar& d)
: m_coeffs(n.size()+1)
{
normal() = n;
offset() = d;
}
/** Constructs a hyperplane passing through the two points. If the dimension of the ambient space
* is greater than 2, then there isn't uniqueness, so an arbitrary choice is made.
*/
EIGEN_DEVICE_FUNC static inline Hyperplane Through(const VectorType& p0, const VectorType& p1)
{
Hyperplane result(p0.size());
result.normal() = (p1 - p0).unitOrthogonal();
result.offset() = -p0.dot(result.normal());
return result;
}
/** Constructs a hyperplane passing through the three points. The dimension of the ambient space
* is required to be exactly 3.
*/
EIGEN_DEVICE_FUNC static inline Hyperplane Through(const VectorType& p0, const VectorType& p1, const VectorType& p2)
{
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(VectorType, 3)
Hyperplane result(p0.size());
VectorType v0(p2 - p0), v1(p1 - p0);
result.normal() = v0.cross(v1);
RealScalar norm = result.normal().norm();
if(norm <= v0.norm() * v1.norm() * NumTraits<RealScalar>::epsilon())
{
Matrix<Scalar,2,3> m; m << v0.transpose(), v1.transpose();
JacobiSVD<Matrix<Scalar,2,3> > svd(m, ComputeFullV);
result.normal() = svd.matrixV().col(2);
}
else
result.normal() /= norm;
result.offset() = -p0.dot(result.normal());
return result;
}
/** Constructs a hyperplane passing through the parametrized line \a parametrized.
* If the dimension of the ambient space is greater than 2, then there isn't uniqueness,
* so an arbitrary choice is made.
*/
// FIXME to be consistent with the rest this could be implemented as a static Through function ??
EIGEN_DEVICE_FUNC explicit Hyperplane(const ParametrizedLine<Scalar, AmbientDimAtCompileTime>& parametrized)
{
normal() = parametrized.direction().unitOrthogonal();
offset() = -parametrized.origin().dot(normal());
}
EIGEN_DEVICE_FUNC ~Hyperplane() {}
/** \returns the dimension in which the plane holds */
EIGEN_DEVICE_FUNC inline Index dim() const { return AmbientDimAtCompileTime==Dynamic ? m_coeffs.size()-1 : Index(AmbientDimAtCompileTime); }
/** normalizes \c *this */
EIGEN_DEVICE_FUNC void normalize(void)
{
m_coeffs /= normal().norm();
}
/** \returns the signed distance between the plane \c *this and a point \a p.
* \sa absDistance()
*/
EIGEN_DEVICE_FUNC inline Scalar signedDistance(const VectorType& p) const { return normal().dot(p) + offset(); }
/** \returns the absolute distance between the plane \c *this and a point \a p.
* \sa signedDistance()
*/
EIGEN_DEVICE_FUNC inline Scalar absDistance(const VectorType& p) const { return numext::abs(signedDistance(p)); }
/** \returns the projection of a point \a p onto the plane \c *this.
*/
EIGEN_DEVICE_FUNC inline VectorType projection(const VectorType& p) const { return p - signedDistance(p) * normal(); }
/** \returns a constant reference to the unit normal vector of the plane, which corresponds
* to the linear part of the implicit equation.
*/
EIGEN_DEVICE_FUNC inline ConstNormalReturnType normal() const { return ConstNormalReturnType(m_coeffs,0,0,dim(),1); }
/** \returns a non-constant reference to the unit normal vector of the plane, which corresponds
* to the linear part of the implicit equation.
*/
EIGEN_DEVICE_FUNC inline NormalReturnType normal() { return NormalReturnType(m_coeffs,0,0,dim(),1); }
/** \returns the distance to the origin, which is also the "constant term" of the implicit equation
* \warning the vector normal is assumed to be normalized.
*/
EIGEN_DEVICE_FUNC inline const Scalar& offset() const { return m_coeffs.coeff(dim()); }
/** \returns a non-constant reference to the distance to the origin, which is also the constant part
* of the implicit equation */
EIGEN_DEVICE_FUNC inline Scalar& offset() { return m_coeffs(dim()); }
/** \returns a constant reference to the coefficients c_i of the plane equation:
* \f$ c_0*x_0 + ... + c_{d-1}*x_{d-1} + c_d = 0 \f$
*/
EIGEN_DEVICE_FUNC inline const Coefficients& coeffs() const { return m_coeffs; }
/** \returns a non-constant reference to the coefficients c_i of the plane equation:
* \f$ c_0*x_0 + ... + c_{d-1}*x_{d-1} + c_d = 0 \f$
*/
EIGEN_DEVICE_FUNC inline Coefficients& coeffs() { return m_coeffs; }
/** \returns the intersection of *this with \a other.
*
* \warning The ambient space must be a plane, i.e. have dimension 2, so that \c *this and \a other are lines.
*
* \note If \a other is approximately parallel to *this, this method will return any point on *this.
*/
EIGEN_DEVICE_FUNC VectorType intersection(const Hyperplane& other) const
{
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(VectorType, 2)
Scalar det = coeffs().coeff(0) * other.coeffs().coeff(1) - coeffs().coeff(1) * other.coeffs().coeff(0);
// since the line equations ax+by=c are normalized with a^2+b^2=1, the following tests
// whether the two lines are approximately parallel.
if(internal::isMuchSmallerThan(det, Scalar(1)))
{ // special case where the two lines are approximately parallel. Pick any point on the first line.
if(numext::abs(coeffs().coeff(1))>numext::abs(coeffs().coeff(0)))
return VectorType(coeffs().coeff(1), -coeffs().coeff(2)/coeffs().coeff(1)-coeffs().coeff(0));
else
return VectorType(-coeffs().coeff(2)/coeffs().coeff(0)-coeffs().coeff(1), coeffs().coeff(0));
}
else
{ // general case
Scalar invdet = Scalar(1) / det;
return VectorType(invdet*(coeffs().coeff(1)*other.coeffs().coeff(2)-other.coeffs().coeff(1)*coeffs().coeff(2)),
invdet*(other.coeffs().coeff(0)*coeffs().coeff(2)-coeffs().coeff(0)*other.coeffs().coeff(2)));
}
}
/** Applies the transformation matrix \a mat to \c *this and returns a reference to \c *this.
*
* \param mat the Dim x Dim transformation matrix
* \param traits specifies whether the matrix \a mat represents an #Isometry
* or a more generic #Affine transformation. The default is #Affine.
*/
template<typename XprType>
EIGEN_DEVICE_FUNC inline Hyperplane& transform(const MatrixBase<XprType>& mat, TransformTraits traits = Affine)
{
if (traits==Affine)
{
normal() = mat.inverse().transpose() * normal();
m_coeffs /= normal().norm();
}
else if (traits==Isometry)
normal() = mat * normal();
else
{
eigen_assert(0 && "invalid traits value in Hyperplane::transform()");
}
return *this;
}
/** Applies the transformation \a t to \c *this and returns a reference to \c *this.
*
* \param t the transformation of dimension Dim
* \param traits specifies whether the transformation \a t represents an #Isometry
* or a more generic #Affine transformation. The default is #Affine.
* Other kind of transformations are not supported.
*/
template<int TrOptions>
EIGEN_DEVICE_FUNC inline Hyperplane& transform(const Transform<Scalar,AmbientDimAtCompileTime,Affine,TrOptions>& t,
TransformTraits traits = Affine)
{
transform(t.linear(), traits);
offset() -= normal().dot(t.translation());
return *this;
}
/** \returns \c *this with scalar type casted to \a NewScalarType
*
* Note that if \a NewScalarType is equal to the current scalar type of \c *this
* then this function smartly returns a const reference to \c *this.
*/
template<typename NewScalarType>
EIGEN_DEVICE_FUNC inline typename internal::cast_return_type<Hyperplane,
Hyperplane<NewScalarType,AmbientDimAtCompileTime,Options> >::type cast() const
{
return typename internal::cast_return_type<Hyperplane,
Hyperplane<NewScalarType,AmbientDimAtCompileTime,Options> >::type(*this);
}
/** Copy constructor with scalar type conversion */
template<typename OtherScalarType,int OtherOptions>
EIGEN_DEVICE_FUNC inline explicit Hyperplane(const Hyperplane<OtherScalarType,AmbientDimAtCompileTime,OtherOptions>& other)
{ m_coeffs = other.coeffs().template cast<Scalar>(); }
/** \returns \c true if \c *this is approximately equal to \a other, within the precision
* determined by \a prec.
*
* \sa MatrixBase::isApprox() */
template<int OtherOptions>
EIGEN_DEVICE_FUNC bool isApprox(const Hyperplane<Scalar,AmbientDimAtCompileTime,OtherOptions>& other, const typename NumTraits<Scalar>::Real& prec = NumTraits<Scalar>::dummy_precision()) const
{ return m_coeffs.isApprox(other.m_coeffs, prec); }
protected:
Coefficients m_coeffs;
};
} // end namespace Eigen
#endif // EIGEN_HYPERPLANE_H
```
|
```xml
// See LICENSE in the project root for license information.
import { createColorGrid } from './createColorGrid';
import { Colorize } from '../Colorize';
import { AnsiEscape } from '../AnsiEscape';
describe(Colorize.name, () => {
test('writes color grid correctly', () => {
let lineCount: number = 0;
for (const line of createColorGrid()) {
expect(line.map((linePart) => AnsiEscape.formatForTests(linePart))).toMatchSnapshot(
`line ${lineCount++}`
);
}
expect(lineCount).toMatchInlineSnapshot(`10`);
});
it('generates codes as expected', () => {
type ColorsFunctionNames = {
[K in keyof typeof Colorize]: (typeof Colorize)[K] extends (str: string) => string ? K : never;
}[keyof typeof Colorize];
function testColorFunction(functionName: ColorsFunctionNames): void {
expect(Colorize[functionName]('x')).toMatchSnapshot(functionName);
}
testColorFunction('black');
testColorFunction('red');
testColorFunction('green');
testColorFunction('yellow');
testColorFunction('blue');
testColorFunction('magenta');
testColorFunction('cyan');
testColorFunction('white');
testColorFunction('gray');
testColorFunction('blackBackground');
testColorFunction('redBackground');
testColorFunction('greenBackground');
testColorFunction('yellowBackground');
testColorFunction('blueBackground');
testColorFunction('magentaBackground');
testColorFunction('cyanBackground');
testColorFunction('whiteBackground');
testColorFunction('grayBackground');
testColorFunction('bold');
testColorFunction('dim');
testColorFunction('underline');
testColorFunction('blink');
testColorFunction('invertColor');
testColorFunction('hidden');
});
});
```
|
```xml
/*
* @license Apache-2.0
*
*
*
* 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.
*/
// TypeScript Version: 4.1
/// <reference types="@stdlib/types"/>
import { Collection, AccessorArrayLike } from '@stdlib/types/array';
/**
* Returns a transformed element.
*
* @param value - current array element
* @returns transformed array element
*/
type Unary<T, U, V> = ( this: U, value: T ) => V;
/**
* Returns a transformed element.
*
* @param value - current array element
* @param index - current array element index
* @returns transformed array element
*/
type Binary<T, U, V> = ( this: U, value: T, index: number ) => V;
/**
* Returns a transformed element.
*
* @param value - current array element
* @param index - current array element index
* @param arr - input array
* @returns transformed array element
*/
type Ternary<T, U, V> = ( this: U, value: T, index: number, arr: Collection<T> | AccessorArrayLike<T> ) => V;
/**
* Returns a transformed element.
*
* @param value - current array element
* @param index - current array element index
* @param arr - input array
* @returns transformed array element
*/
type Callback<T, U, V> = Unary<T, U, V> | Binary<T, U, V> | Ternary<T, U, V>;
/**
* Interface describing `mskrejectMap`.
*/
interface MskrejectMap {
/**
* Returns a new array by applying a mask and mapping the unmasked values according to a callback function.
*
* @param x - input array
* @param mask - mask array
* @param clbk - mapping function
* @param thisArg - function context
* @returns output array
*
* @example
* var x = [ 1, 2, 3, 4 ];
*
* var y = mskrejectMap( x, [ 0, 1, 0, 1 ], function( val ) {
* return val * 2;
* } );
* // returns [ 2, 6 ]
*/
<T = unknown, U = unknown, V = unknown>( x: Collection<T> | AccessorArrayLike<T>, mask: Collection, clbk: Callback<T, U, V>, thisArg?: U ): Array<T>;
/**
* Applies a mask to a provided input array, maps the unmasked values according to a callback function, and assigns to elements in a provided output array.
*
* @param x - input array
* @param mask - mask array
* @param out - output array
* @param stride - output array stride
* @param offset - output array offset
* @param clbk - mapping function
* @param thisArg - function context
* @returns output array
*
* @example
* var x = [ 1, 2, 3, 4 ];
* var mask = [ 1, 0, 1, 0 ];
* var out = [ 0, 0, 0, 0 ];
*
* function clbk( val ) {
* return val * 2;
* }
*
* var arr = mskrejectMap.assign( x, mask, out, -2, out.length-1, clbk );
* // returns [ 0, 8, 0, 4 ]
*
* var bool = ( arr === out );
* // returns true
*/
assign<T = unknown, U = unknown, V = unknown>( x: Collection | AccessorArrayLike<T>, mask: Collection, out: Collection<T>, stride: number, offset: number, clbk: Callback<T, U, V>, thisArg?: U ): Collection<T>;
}
/**
* Returns a new array by applying a mask and mapping the unmasked values according to a callback function.
*
* @param x - input array
* @param mask - mask array
* @param clbk - mapping function
* @param thisArg - function context
* @returns output array
*
* @example
* var x = [ 1, 2, 3, 4 ];
*
* var y = mskrejectMap( x, [ 0, 1, 0, 1 ], function( val ) {
* return val * 2;
* } );
* // returns [ 2, 6 ]
*
* @example
* var x = [ 1, 2, 3, 4 ];
* var mask = [ 1, 0, 1, 0 ];
* var out = [ 0, 0, 0, 0 ];
*
* function clbk( val ) {
* return val * 2;
* }
*
* var arr = mskrejectMap.assign( x, mask, out, -2, out.length-1, clbk );
* // returns [ 0, 8, 0, 4 ]
*
* var bool = ( arr === out );
* // returns true
*/
declare var mskrejectMap: MskrejectMap;
// EXPORTS //
export = mskrejectMap;
```
|
```java
/*
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
*/
package com.itextpdf.signatures.sign;
import com.itextpdf.kernel.pdf.PdfArray;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfObject;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfString;
import com.itextpdf.signatures.PdfSignature;
import com.itextpdf.signatures.PdfSignatureApp;
import com.itextpdf.signatures.SignatureUtil;
import com.itextpdf.test.ExtendedITextTest;
import com.itextpdf.test.annotations.type.UnitTest;
import java.io.IOException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Tag;
@Tag("UnitTest")
public class PdfSignatureTest extends ExtendedITextTest {
public static final String sourceFolder = "./src/test/resources/com/itextpdf/signatures/sign/PdfSignatureTest/";
@Test
public void setByteRangeTest() throws IOException {
PdfSignature signature = getTestSignature(sourceFolder + "simpleSignature.pdf");
int[] byteRange = {0, 141, 16526, 2494};
signature.setByteRange(byteRange);
PdfArray expected = new PdfArray((new int[] {0, 141, 16526, 2494}));
Assertions.assertArrayEquals(expected.toIntArray(), signature.getByteRange().toIntArray());
}
@Test
public void setContentsTest() throws IOException {
PdfSignature signature = getTestSignature(sourceFolder + "simpleSignature.pdf");
byte[] newContents = new PdfString("new iText signature").getValueBytes();
signature.setContents(newContents);
Assertions.assertEquals("new iText signature", signature.getContents().getValue());
}
@Test
public void setAndGetCertTest() throws IOException {
PdfSignature signature = getTestSignature(sourceFolder + "adbe.x509.rsa_sha1_signature.pdf");
byte[] certChain = new PdfString("Hello, iText!!").getValueBytes();
signature.setCert(certChain);
Assertions.assertEquals("Hello, iText!!", signature.getCertObject().toString());
}
@Test
public void getCertObjectTest() throws IOException {
PdfSignature signature = getTestSignature(sourceFolder + "adbe.x509.rsa_sha1_signature.pdf");
Assertions.assertTrue(signature.getCertObject().isArray());
}
@Test
public void setAndGetNameTest() throws IOException {
PdfSignature signature = getTestSignature(sourceFolder + "simpleSignature.pdf");
Assertions.assertNull(signature.getName());
String name = "iText person";
signature.setName(name);
Assertions.assertEquals(name, signature.getName());
}
@Test
public void setSignatureCreatorTest() throws IOException {
PdfSignature signature = getTestSignature(sourceFolder + "noPropBuilds.pdf");
Assertions.assertNull(signature.getPdfObject().getAsDictionary(PdfName.Prop_Build));
signature.setSignatureCreator("iText.Name");
String propBuild = signature.getPdfObject().getAsDictionary(PdfName.Prop_Build)
.getAsDictionary(PdfName.App).getAsName(PdfName.Name).getValue();
Assertions.assertEquals("iText.Name", propBuild);
}
@Test
public void pdfSignatureAppDefaultConstructorTest() {
PdfSignatureApp signatureApp = new PdfSignatureApp();
Assertions.assertTrue(signatureApp.getPdfObject().isDictionary());
}
@Test
public void certAsArrayNotStringTest() throws IOException {
PdfSignature signature = getTestSignature(sourceFolder + "adbe.x509.rsa_sha1_signature.pdf");
PdfObject certObject = signature.getCertObject();
Assertions.assertTrue(certObject instanceof PdfArray);
Assertions.assertNull(signature.getCert());
}
private static PdfSignature getTestSignature(String pathToPdf) throws IOException {
try (PdfDocument doc = new PdfDocument(new PdfReader(pathToPdf))) {
SignatureUtil sigUtil = new SignatureUtil(doc);
return sigUtil.getSignature("Signature1");
}
}
}
```
|
```objective-c
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* This Source Code Form is subject to the terms of the Mozilla Public
* file, You can obtain one at path_to_url */
#ifndef builtin_SIMD_h
#define builtin_SIMD_h
#include "jsapi.h"
#include "jsobj.h"
#include "builtin/TypedObject.h"
#include "js/Conversions.h"
#include "vm/GlobalObject.h"
/*
* JS SIMD functions.
* Spec matching polyfill:
* path_to_url
*/
#define FLOAT32X4_UNARY_FUNCTION_LIST(V) \
V(abs, (UnaryFunc<Float32x4, Abs, Float32x4>), 1, 0) \
V(check, (UnaryFunc<Float32x4, Identity, Float32x4>), 1, 0) \
V(fromFloat64x2, (FuncConvert<Float64x2, Float32x4> ), 1, 0) \
V(fromFloat64x2Bits, (FuncConvertBits<Float64x2, Float32x4>), 1, 0) \
V(fromInt32x4, (FuncConvert<Int32x4, Float32x4> ), 1, 0) \
V(fromInt32x4Bits, (FuncConvertBits<Int32x4, Float32x4>), 1, 0) \
V(neg, (UnaryFunc<Float32x4, Neg, Float32x4>), 1, 0) \
V(not, (CoercedUnaryFunc<Float32x4, Int32x4, Not, Float32x4>), 1, 0) \
V(reciprocal, (UnaryFunc<Float32x4, Rec, Float32x4>), 1, 0) \
V(reciprocalSqrt, (UnaryFunc<Float32x4, RecSqrt, Float32x4>), 1, 0) \
V(splat, (FuncSplat<Float32x4>), 1, 0) \
V(sqrt, (UnaryFunc<Float32x4, Sqrt, Float32x4>), 1, 0)
#define FLOAT32X4_BINARY_FUNCTION_LIST(V) \
V(add, (BinaryFunc<Float32x4, Add, Float32x4>), 2, 0) \
V(and, (CoercedBinaryFunc<Float32x4, Int32x4, And, Float32x4>), 2, 0) \
V(div, (BinaryFunc<Float32x4, Div, Float32x4>), 2, 0) \
V(equal, (CompareFunc<Float32x4, Equal>), 2, 0) \
V(greaterThan, (CompareFunc<Float32x4, GreaterThan>), 2, 0) \
V(greaterThanOrEqual, (CompareFunc<Float32x4, GreaterThanOrEqual>), 2, 0) \
V(lessThan, (CompareFunc<Float32x4, LessThan>), 2, 0) \
V(lessThanOrEqual, (CompareFunc<Float32x4, LessThanOrEqual>), 2, 0) \
V(load, (Load<Float32x4, 4>), 2, 0) \
V(loadXYZ, (Load<Float32x4, 3>), 2, 0) \
V(loadXY, (Load<Float32x4, 2>), 2, 0) \
V(loadX, (Load<Float32x4, 1>), 2, 0) \
V(max, (BinaryFunc<Float32x4, Maximum, Float32x4>), 2, 0) \
V(maxNum, (BinaryFunc<Float32x4, MaxNum, Float32x4>), 2, 0) \
V(min, (BinaryFunc<Float32x4, Minimum, Float32x4>), 2, 0) \
V(minNum, (BinaryFunc<Float32x4, MinNum, Float32x4>), 2, 0) \
V(mul, (BinaryFunc<Float32x4, Mul, Float32x4>), 2, 0) \
V(notEqual, (CompareFunc<Float32x4, NotEqual>), 2, 0) \
V(or, (CoercedBinaryFunc<Float32x4, Int32x4, Or, Float32x4>), 2, 0) \
V(store, (Store<Float32x4, 4>), 3, 0) \
V(storeXYZ, (Store<Float32x4, 3>), 3, 0) \
V(storeXY, (Store<Float32x4, 2>), 3, 0) \
V(storeX, (Store<Float32x4, 1>), 3, 0) \
V(sub, (BinaryFunc<Float32x4, Sub, Float32x4>), 2, 0) \
V(withX, (FuncWith<Float32x4, WithX>), 2, 0) \
V(withY, (FuncWith<Float32x4, WithY>), 2, 0) \
V(withZ, (FuncWith<Float32x4, WithZ>), 2, 0) \
V(withW, (FuncWith<Float32x4, WithW>), 2, 0) \
V(xor, (CoercedBinaryFunc<Float32x4, Int32x4, Xor, Float32x4>), 2, 0)
#define FLOAT32X4_TERNARY_FUNCTION_LIST(V) \
V(bitselect, BitSelect<Float32x4>, 3, 0) \
V(clamp, Clamp<Float32x4>, 3, 0) \
V(select, Select<Float32x4>, 3, 0)
#define FLOAT32X4_SHUFFLE_FUNCTION_LIST(V) \
V(swizzle, Swizzle<Float32x4>, 2, 0) \
V(shuffle, Shuffle<Float32x4>, 3, 0)
#define FLOAT32X4_FUNCTION_LIST(V) \
FLOAT32X4_UNARY_FUNCTION_LIST(V) \
FLOAT32X4_BINARY_FUNCTION_LIST(V) \
FLOAT32X4_TERNARY_FUNCTION_LIST(V) \
FLOAT32X4_SHUFFLE_FUNCTION_LIST(V)
#define FLOAT64X2_UNARY_FUNCTION_LIST(V) \
V(abs, (UnaryFunc<Float64x2, Abs, Float64x2>), 1, 0) \
V(check, (UnaryFunc<Float64x2, Identity, Float64x2>), 1, 0) \
V(fromFloat32x4, (FuncConvert<Float32x4, Float64x2> ), 1, 0) \
V(fromFloat32x4Bits, (FuncConvertBits<Float32x4, Float64x2>), 1, 0) \
V(fromInt32x4, (FuncConvert<Int32x4, Float64x2> ), 1, 0) \
V(fromInt32x4Bits, (FuncConvertBits<Int32x4, Float64x2>), 1, 0) \
V(neg, (UnaryFunc<Float64x2, Neg, Float64x2>), 1, 0) \
V(reciprocal, (UnaryFunc<Float64x2, Rec, Float64x2>), 1, 0) \
V(reciprocalSqrt, (UnaryFunc<Float64x2, RecSqrt, Float64x2>), 1, 0) \
V(splat, (FuncSplat<Float64x2>), 1, 0) \
V(sqrt, (UnaryFunc<Float64x2, Sqrt, Float64x2>), 1, 0)
#define FLOAT64X2_BINARY_FUNCTION_LIST(V) \
V(add, (BinaryFunc<Float64x2, Add, Float64x2>), 2, 0) \
V(div, (BinaryFunc<Float64x2, Div, Float64x2>), 2, 0) \
V(equal, (CompareFunc<Float64x2, Equal>), 2, 0) \
V(greaterThan, (CompareFunc<Float64x2, GreaterThan>), 2, 0) \
V(greaterThanOrEqual, (CompareFunc<Float64x2, GreaterThanOrEqual>), 2, 0) \
V(lessThan, (CompareFunc<Float64x2, LessThan>), 2, 0) \
V(lessThanOrEqual, (CompareFunc<Float64x2, LessThanOrEqual>), 2, 0) \
V(load, (Load<Float64x2, 2>), 2, 0) \
V(loadX, (Load<Float64x2, 1>), 2, 0) \
V(max, (BinaryFunc<Float64x2, Maximum, Float64x2>), 2, 0) \
V(maxNum, (BinaryFunc<Float64x2, MaxNum, Float64x2>), 2, 0) \
V(min, (BinaryFunc<Float64x2, Minimum, Float64x2>), 2, 0) \
V(minNum, (BinaryFunc<Float64x2, MinNum, Float64x2>), 2, 0) \
V(mul, (BinaryFunc<Float64x2, Mul, Float64x2>), 2, 0) \
V(notEqual, (CompareFunc<Float64x2, NotEqual>), 2, 0) \
V(store, (Store<Float64x2, 2>), 3, 0) \
V(storeX, (Store<Float64x2, 1>), 3, 0) \
V(sub, (BinaryFunc<Float64x2, Sub, Float64x2>), 2, 0) \
V(withX, (FuncWith<Float64x2, WithX>), 2, 0) \
V(withY, (FuncWith<Float64x2, WithY>), 2, 0)
#define FLOAT64X2_TERNARY_FUNCTION_LIST(V) \
V(bitselect, BitSelect<Float64x2>, 3, 0) \
V(clamp, Clamp<Float64x2>, 3, 0) \
V(select, Select<Float64x2>, 3, 0)
#define FLOAT64X2_SHUFFLE_FUNCTION_LIST(V) \
V(swizzle, Swizzle<Float64x2>, 2, 0) \
V(shuffle, Shuffle<Float64x2>, 3, 0)
#define FLOAT64X2_FUNCTION_LIST(V) \
FLOAT64X2_UNARY_FUNCTION_LIST(V) \
FLOAT64X2_BINARY_FUNCTION_LIST(V) \
FLOAT64X2_TERNARY_FUNCTION_LIST(V) \
FLOAT64X2_SHUFFLE_FUNCTION_LIST(V)
#define INT32X4_UNARY_FUNCTION_LIST(V) \
V(check, (UnaryFunc<Int32x4, Identity, Int32x4>), 1, 0) \
V(fromFloat32x4, (FuncConvert<Float32x4, Int32x4>), 1, 0) \
V(fromFloat32x4Bits, (FuncConvertBits<Float32x4, Int32x4>), 1, 0) \
V(fromFloat64x2, (FuncConvert<Float64x2, Int32x4>), 1, 0) \
V(fromFloat64x2Bits, (FuncConvertBits<Float64x2, Int32x4>), 1, 0) \
V(neg, (UnaryFunc<Int32x4, Neg, Int32x4>), 1, 0) \
V(not, (UnaryFunc<Int32x4, Not, Int32x4>), 1, 0) \
V(splat, (FuncSplat<Int32x4>), 0, 0)
#define INT32X4_BINARY_FUNCTION_LIST(V) \
V(add, (BinaryFunc<Int32x4, Add, Int32x4>), 2, 0) \
V(and, (BinaryFunc<Int32x4, And, Int32x4>), 2, 0) \
V(equal, (CompareFunc<Int32x4, Equal>), 2, 0) \
V(greaterThan, (CompareFunc<Int32x4, GreaterThan>), 2, 0) \
V(greaterThanOrEqual, (CompareFunc<Int32x4, GreaterThanOrEqual>), 2, 0) \
V(lessThan, (CompareFunc<Int32x4, LessThan>), 2, 0) \
V(lessThanOrEqual, (CompareFunc<Int32x4, LessThanOrEqual>), 2, 0) \
V(load, (Load<Int32x4, 4>), 2, 0) \
V(loadXYZ, (Load<Int32x4, 3>), 2, 0) \
V(loadXY, (Load<Int32x4, 2>), 2, 0) \
V(loadX, (Load<Int32x4, 1>), 2, 0) \
V(mul, (BinaryFunc<Int32x4, Mul, Int32x4>), 2, 0) \
V(notEqual, (CompareFunc<Int32x4, NotEqual>), 2, 0) \
V(or, (BinaryFunc<Int32x4, Or, Int32x4>), 2, 0) \
V(sub, (BinaryFunc<Int32x4, Sub, Int32x4>), 2, 0) \
V(shiftLeftByScalar, (Int32x4BinaryScalar<ShiftLeft>), 2, 0) \
V(shiftRightArithmeticByScalar, (Int32x4BinaryScalar<ShiftRight>), 2, 0) \
V(shiftRightLogicalByScalar, (Int32x4BinaryScalar<ShiftRightLogical>), 2, 0) \
V(store, (Store<Int32x4, 4>), 3, 0) \
V(storeXYZ, (Store<Int32x4, 3>), 3, 0) \
V(storeXY, (Store<Int32x4, 2>), 3, 0) \
V(storeX, (Store<Int32x4, 1>), 3, 0) \
V(withX, (FuncWith<Int32x4, WithX>), 2, 0) \
V(withY, (FuncWith<Int32x4, WithY>), 2, 0) \
V(withZ, (FuncWith<Int32x4, WithZ>), 2, 0) \
V(withW, (FuncWith<Int32x4, WithW>), 2, 0) \
V(xor, (BinaryFunc<Int32x4, Xor, Int32x4>), 2, 0)
#define INT32X4_TERNARY_FUNCTION_LIST(V) \
V(bitselect, BitSelect<Int32x4>, 3, 0) \
V(select, Select<Int32x4>, 3, 0)
#define INT32X4_QUARTERNARY_FUNCTION_LIST(V) \
V(bool, Int32x4Bool, 4, 0)
#define INT32X4_SHUFFLE_FUNCTION_LIST(V) \
V(swizzle, Swizzle<Int32x4>, 2, 0) \
V(shuffle, Shuffle<Int32x4>, 3, 0)
#define INT32X4_FUNCTION_LIST(V) \
INT32X4_UNARY_FUNCTION_LIST(V) \
INT32X4_BINARY_FUNCTION_LIST(V) \
INT32X4_TERNARY_FUNCTION_LIST(V) \
INT32X4_QUARTERNARY_FUNCTION_LIST(V) \
INT32X4_SHUFFLE_FUNCTION_LIST(V)
#define FOREACH_INT32X4_SIMD_OP(_) \
_(fromFloat32x4) \
_(fromFloat32x4Bits) \
_(shiftLeftByScalar) \
_(shiftRightArithmeticByScalar) \
_(shiftRightLogicalByScalar)
#define ARITH_FLOAT32X4_SIMD_OP(_) \
_(div) \
_(max) \
_(min) \
_(maxNum) \
_(minNum)
#define FOREACH_FLOAT32X4_SIMD_OP(_) \
ARITH_FLOAT32X4_SIMD_OP(_) \
_(abs) \
_(sqrt) \
_(reciprocal) \
_(reciprocalSqrt) \
_(fromInt32x4) \
_(fromInt32x4Bits)
#define ARITH_COMMONX4_SIMD_OP(_) \
_(add) \
_(sub) \
_(mul)
#define BITWISE_COMMONX4_SIMD_OP(_) \
_(and) \
_(or) \
_(xor)
#define FOREACH_COMMONX4_SIMD_OP(_) \
ARITH_COMMONX4_SIMD_OP(_) \
BITWISE_COMMONX4_SIMD_OP(_) \
_(lessThan) \
_(lessThanOrEqual) \
_(equal) \
_(notEqual) \
_(greaterThan) \
_(greaterThanOrEqual) \
_(bitselect) \
_(select) \
_(swizzle) \
_(shuffle) \
_(splat) \
_(withX) \
_(withY) \
_(withZ) \
_(withW) \
_(not) \
_(neg) \
_(load) \
_(loadX) \
_(loadXY) \
_(loadXYZ) \
_(store) \
_(storeX) \
_(storeXY) \
_(storeXYZ) \
_(check)
#define FORALL_SIMD_OP(_) \
FOREACH_INT32X4_SIMD_OP(_) \
FOREACH_FLOAT32X4_SIMD_OP(_) \
FOREACH_COMMONX4_SIMD_OP(_)
namespace js {
class SIMDObject : public JSObject
{
public:
static const Class class_;
static JSObject* initClass(JSContext* cx, Handle<GlobalObject*> global);
static bool toString(JSContext* cx, unsigned int argc, jsval* vp);
};
// These classes exist for use with templates below.
struct Float32x4 {
typedef float Elem;
static const unsigned lanes = 4;
static const SimdTypeDescr::Type type = SimdTypeDescr::TYPE_FLOAT32;
static TypeDescr& GetTypeDescr(GlobalObject& global) {
return global.float32x4TypeDescr().as<TypeDescr>();
}
static Elem toType(Elem a) {
return a;
}
static bool toType(JSContext* cx, JS::HandleValue v, Elem* out) {
double d;
if (!ToNumber(cx, v, &d))
return false;
*out = float(d);
return true;
}
static void setReturn(CallArgs& args, Elem value) {
args.rval().setDouble(JS::CanonicalizeNaN(value));
}
};
struct Float64x2 {
typedef double Elem;
static const unsigned lanes = 2;
static const SimdTypeDescr::Type type = SimdTypeDescr::TYPE_FLOAT64;
static TypeDescr& GetTypeDescr(GlobalObject& global) {
return global.float64x2TypeDescr().as<TypeDescr>();
}
static Elem toType(Elem a) {
return a;
}
static bool toType(JSContext* cx, JS::HandleValue v, Elem* out) {
return ToNumber(cx, v, out);
}
static void setReturn(CallArgs& args, Elem value) {
args.rval().setDouble(JS::CanonicalizeNaN(value));
}
};
struct Int32x4 {
typedef int32_t Elem;
static const unsigned lanes = 4;
static const SimdTypeDescr::Type type = SimdTypeDescr::TYPE_INT32;
static TypeDescr& GetTypeDescr(GlobalObject& global) {
return global.int32x4TypeDescr().as<TypeDescr>();
}
static Elem toType(Elem a) {
return JS::ToInt32(a);
}
static bool toType(JSContext* cx, JS::HandleValue v, Elem* out) {
return ToInt32(cx, v, out);
}
static void setReturn(CallArgs& args, Elem value) {
args.rval().setInt32(value);
}
};
template<typename V>
JSObject* CreateSimd(JSContext* cx, typename V::Elem* data);
template<typename V>
bool IsVectorObject(HandleValue v);
template<typename V>
bool ToSimdConstant(JSContext* cx, HandleValue v, jit::SimdConstant* out);
#define DECLARE_SIMD_FLOAT32X4_FUNCTION(Name, Func, Operands, Flags) \
extern bool \
simd_float32x4_##Name(JSContext* cx, unsigned argc, Value* vp);
FLOAT32X4_FUNCTION_LIST(DECLARE_SIMD_FLOAT32X4_FUNCTION)
#undef DECLARE_SIMD_FLOAT32X4_FUNCTION
#define DECLARE_SIMD_FLOAT64X2_FUNCTION(Name, Func, Operands, Flags) \
extern bool \
simd_float64x2_##Name(JSContext* cx, unsigned argc, Value* vp);
FLOAT64X2_FUNCTION_LIST(DECLARE_SIMD_FLOAT64X2_FUNCTION)
#undef DECLARE_SIMD_FLOAT64X2_FUNCTION
#define DECLARE_SIMD_INT32x4_FUNCTION(Name, Func, Operands, Flags) \
extern bool \
simd_int32x4_##Name(JSContext* cx, unsigned argc, Value* vp);
INT32X4_FUNCTION_LIST(DECLARE_SIMD_INT32x4_FUNCTION)
#undef DECLARE_SIMD_INT32x4_FUNCTION
} /* namespace js */
JSObject*
js_InitSIMDClass(JSContext* cx, js::HandleObject obj);
#endif /* builtin_SIMD_h */
```
|
Grove High School may refer to:
U.S states A–K
Beech Grove High School in Indiana
Boone Grove High School in Indiana
Buffalo Grove High School in Illinois
Cary-Grove High School in Illinois
Council Grove High School in Kansas
Downers Grove North High School in Illinois
Eagle Grove High School in Iowa
Garden Grove High School in California
Pacific Grove High School in California
Prairie Grove High School in Arkansas
The Grove School in California
Union Grove High School in Georgia
Walden Grove High School in Arizona
Western Grove High School in Arkansas
U.S. states M–Z
Avon Grove High School in Pennsylvania
Blooming Grove High School in Texas
Cedar Grove-Belgium High School in Wisconsin
Coal Grove High School in Ohio
Columbus Grove High School in Ohio
Cottage Grove High School in Oregon
Fair Grove High School in Missouri
Forest Grove High School in Oregon
Grove City High School in Ohio
Grove High School in Oklahoma
Howards Grove High School in Wisconsin
Lone Grove High School in Oklahoma
Maple Grove Junior High School in Minnesota
Maple Grove Senior High School in Minnesota
Monona Grove High School in Wisconsin
Penns Grove High School in New Jersey
Elsewhere
Golden Grove High School in South Australia
Hazel Grove High School in England
King's Grove High School in England
Lynn Grove High School in England
Walnut Grove Secondary School in British Columbia, Canada
See also
Grove School (disambiguation)
Groves High School (disambiguation)
|
```kotlin
plugins {
id("java-library")
id("kotlin")
}
java {
targetCompatibility = JavaVersion.VERSION_17
sourceCompatibility = JavaVersion.VERSION_17
}
dependencies {
compileOnly("com.android.tools.lint:lint-api:31.5.2")
testImplementation("com.android.tools.lint:lint:31.5.2")
testImplementation("com.android.tools.lint:lint-tests:31.5.2")
testImplementation("junit:junit:4.13.2")
}
```
|
Khaman Madit Maluach (born 14 September 2006) is a South Sudanese basketball player who currently plays for the NBA Academy Africa. Standing at , he plays the center position. He is also a current member of the South Sudan national team, whom he joined at age of 16.
Early life and career
Born in Rumbek, South Sudan, Maluach grew up in neighbouring Uganda as a refugee with his siblings and mother. There, in 2019, he was encouraged to play basketball by a motorcyclist who had stopped down when he saw the tall Maluach walking along the road. He attended a local camp organised by Luol Deng and started playing basketball. He later joined the NBA Academy Africa in Saly, Senegal, where basketball is combined with education.
Maluach played for South Sudanese professional team Cobra Sport in the 2022 BAL season, as part of the BAL Elevate program. Through this programme, one NBA Academy player was assigned to each BAL team. He made his BAL debut on April 9 against defending champions Zamalek, scoring two points and recording two rebounds in seven minutes.
In March 2023, Maluach played in his second BAL season after he was drafted by the AS Douanes, the defending Senegalese champions. The Douanes reached the final, in which Maluach started and contributed 2 points and 4 rebounds, as they lost to Al Ahly.
He attended the 2023 Basketball Without Borders in Johannesburg, South Africa, and was named the camp's MVP.
National team career
In August 2023, Maluach was selected for the South Sudan national team roster for the 2023 FIBA Basketball World Cup. At age 16, he was the youngest player on the Bright Stars' roster. On 28 August, he made his debut in a victory against China, becoming the third-youngest player to appear in a World Cup game. Maluach and South Sudan were the best-ranked African team in the tournament, and thus qualified for the 2024 Summer Olympics in Paris, another milestone in the national team’s history.
References
2006 births
Living people
South Sudanese men's basketball players
Cobra Sport players
AS Douanes basketball players
NBA Academy Africa players
Centers (basketball)
2023 FIBA Basketball World Cup players
|
```smalltalk
/* ========================================================================
*
*
* 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.
*
* The complete license agreement can be found here:
* ======================================================================*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Opc.Ua;
namespace Boiler
{
public partial class BoilerStateMachineState
{
#region Initialization
/// <summary>
/// Initializes the object as a collection of counters which change value on read.
/// </summary>
protected override void OnAfterCreate(ISystemContext context, NodeState node)
{
base.OnAfterCreate(context, node);
Start.OnCallMethod = OnStart;
Start.OnReadExecutable = IsStartExecutable;
Start.OnReadUserExecutable = IsStartUserExecutable;
Suspend.OnCallMethod = OnSuspend;
Suspend.OnReadExecutable = IsSuspendExecutable;
Suspend.OnReadUserExecutable = IsSuspendUserExecutable;
Resume.OnCallMethod = OnResume;
Resume.OnReadExecutable = IsResumeExecutable;
Resume.OnReadUserExecutable = IsResumeUserExecutable;
Halt.OnCallMethod = OnHalt;
Halt.OnReadExecutable = IsHaltExecutable;
Halt.OnReadUserExecutable = IsHaltUserExecutable;
Reset.OnCallMethod = OnReset;
Reset.OnReadExecutable = IsResetExecutable;
Reset.OnReadUserExecutable = IsResetUserExecutable;
}
#endregion
}
}
```
|
```yaml
properties:
prop1:
type: array
items:
"$ref": Error.yaml
```
|
United States v. McMahon et al (9:93-cr-01276) is a 1994 United States District Court for the Eastern District of New York criminal court case brought against Vince McMahon, chairman of the World Wrestling Federation on suspicion of supplying illegal anabolic steroids to his professional wrestlers. The jury found McMahon not guilty on July 23, 1994.
Background
Vince McMahon was the chairman of Titan Sports Inc., the parent company of the World Wrestling Federation, a professional wrestling promotion. In the late 1980s, the WWF had undergone a large expansion from being a National Wrestling Alliance (NWA) regional territorial wrestling promotion into an independent national one.
In 1991, Dr George Zahorian III, a Pennsylvania doctor who had worked as a ringside doctor for the WWF, had been convicted of illegally supplying anabolic steroids. At his trial, it was revealed that Zahorian had supplied steroids to the WWF and their wrestlers, specifically to Vince McMahon's office at Titan Towers. The WWF CEO Linda McMahon, married to Vince, had sent a memo in 1989 advising that Zahorian should not be used by the WWF prior to his arrest and trial on the grounds of suspicion of illicit steroids distribution. In 1992, prior to being indicted, Vince McMahon closed down the World Bodybuilding Federation that he owned.
As a result of Zahorian co-operating with prosecutors, McMahon was indicted in 1993. The United States Attorney for the Eastern District of New York Zachary W. Carter charged McMahon with conspiring to distribute steroids, possession of illegal steroids with intent to distribute and embezzlement for allegedly using money from Titan Sports Inc to purchase illegal steroids.
Prior to the trial, McMahon had lost a civil lawsuit brought by Jesse "The Body" Ventura over $800,000 owed in royalties for Ventura's color commentary on WWF programming. The case was set to be heard at the United States District Court for the Eastern District of New York rather than in McMahon's and the WWF's home state of Connecticut. This was because the prosecutors alleged that the distribution of steroids occurred in Long Island. The trial was due to start in June 1994 but was delayed until the following month. Ted Turner, the owner of the WWF's rival World Championship Wrestling (WCW), suggested that he would try to get CNN to cover the trial for Turner Broadcasting System.
Trial
The United States government brought six charges against McMahon; however, three of the six were thrown out of court before the full trial. The three that remained were for two counts of distributing steroids and one of conspiracy to distribute steroids. The case was heard by Judge Jacob Mishler. The prosecution alleged that McMahon was in charge of distribution of illegal steroids to WWF wrestlers; they also charged that McMahon had required wrestlers to take steroids while they were in the WWF. Appearing as the prosecution's main witness was Hulk Hogan, who had been the WWF's biggest star during the expansion and was working for WCW at the time of the trial. Testifying under immunity from prosecution, Hogan said that while he had taken steroids previously under his own prescription for medical purposes and received them from Zahorian with his fanmail and paychecks, McMahon had never asked him to take any nor bought any on his behalf.
Eleven wrestlers, including Hogan, were called to testify by the prosecution. No other wrestlers called to the stand attested that McMahon had supplied them with steroids apart from Nailz. Nailz claimed that McMahon had pressured him into taking steroids to make him bigger. However, McMahon's defense attorney argued that Nailz was a hostile witness as he had been fired from the WWF previously and was disgruntled and looking for revenge. Nailz contradicted himself during his testimony by stating that he had no animosity towards McMahon but later answered in the affirmative that he hated McMahon.
McMahon's legal team did not enter a defense. McMahon's lawyer stated he had only had one discussion with Zahorian about steroids and that was over McMahon's concerns about the health of his wrestlers. Judge Mishler dismissed the distribution charges on the grounds that the prosecution had provided insufficient evidence that they occurred within the court's jurisdiction. The jury deliberated for sixteen hours on the conspiracy charge before pronouncing a "not guilty" verdict. McMahon stated that he had used steroids but before they became illegal in 1991 under the Controlled Substances Act. McMahon declared his company drug-free and the WWF brought in a tough independent drugs-testing policy following this. Any WWF wrestler caught with drugs would be fired, as occurred a year later when Crush was arrested for being in possession of steroids and marijuana in Hawaii. He was fired by the WWF as a result, in accordance with McMahon's new policy.
Consequences
Zahorian was sentenced to three years in prison after his conviction. By 2010, he had resumed practicing medicine in Harrisburg, Pennsylvania.
After the trial, the WWF retained their drug-testing policy brought in as a result of the investigation and even used it in their Billionaire Ted skits on WWF programming to make the point that WCW did not have one. However, according to Linda, they suspended it in 1996 due to cost. The WWF also started promoting smaller wrestlers rather than the muscular ones that they had since the 1980s. In 2003, the trial was used as a part of angle for a feud between Hogan and McMahon which culminated in them having a wrestling match at WrestleMania XIX which was won by Hogan.
During Linda McMahon's 2010 United States Senate campaign, the steroid trial was used by her political opponents to attack her. A lawyer representing WWE stated that she was unrelated to the scandal.
Media portrayals
The trial was the focus of an episode of the third season of the Viceland pro wrestling docuseries Dark Side of the Ring. On July 26, 2021, it was reported that a television series adaptation of McMahon's life was in development by WWE Studios and Blumhouse Television. Titled The United States of America vs. Vince McMahon, the series will be a fictionalized version of the court case.
References
1994 in New York (state)
20th-century American trials
Criminal trials that ended in acquittal
Doping cases in wrestling
History of WWE
Hulk Hogan
Professional wrestling controversies
United States district court cases
|
```rust
use crate::{
metrics::{self, record_metric, Endpoint, HasLabelsCore, Outcome},
request_database::Handle,
server_axum::api_orchestrator_integration_impls::*,
};
use axum::extract::ws::{Message, WebSocket};
use futures::{future::Fuse, Future, FutureExt, StreamExt, TryFutureExt};
use orchestrator::{
coordinator::{self, Coordinator, CoordinatorFactory, DockerBackend},
DropErrorDetailsExt,
};
use snafu::prelude::*;
use std::{
collections::BTreeMap,
convert::TryFrom,
mem,
pin::pin,
sync::{
atomic::{AtomicU64, Ordering},
Arc,
},
time::{Duration, Instant},
};
use tokio::{
sync::{mpsc, Semaphore},
task::{AbortHandle, JoinSet},
time,
};
use tokio_util::sync::CancellationToken;
use tracing::{error, instrument, warn, Instrument};
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct MetaInner {
sequence_number: i64,
}
type Meta = Arc<MetaInner>;
#[derive(serde::Deserialize)]
#[serde(tag = "type")]
enum HandshakeMessage {
#[serde(rename = "websocket/connected")]
Connected {
payload: Connected,
#[allow(unused)]
meta: Meta,
},
}
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct Connected {
i_accept_this_is_an_unsupported_api: bool,
}
#[derive(serde::Deserialize)]
#[serde(tag = "type")]
enum WSMessageRequest {
#[serde(rename = "output/execute/wsExecuteRequest")]
ExecuteRequest { payload: ExecuteRequest, meta: Meta },
#[serde(rename = "output/execute/wsExecuteStdin")]
ExecuteStdin { payload: String, meta: Meta },
#[serde(rename = "output/execute/wsExecuteStdinClose")]
ExecuteStdinClose { meta: Meta },
#[serde(rename = "output/execute/wsExecuteKill")]
ExecuteKill { meta: Meta },
}
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct ExecuteRequest {
channel: String,
mode: String,
edition: String,
crate_type: String,
tests: bool,
code: String,
backtrace: bool,
}
impl TryFrom<ExecuteRequest> for coordinator::ExecuteRequest {
type Error = ExecuteRequestParseError;
fn try_from(value: ExecuteRequest) -> Result<Self, Self::Error> {
let ExecuteRequest {
channel,
mode,
edition,
crate_type,
tests,
code,
backtrace,
} = value;
Ok(coordinator::ExecuteRequest {
channel: parse_channel(&channel)?,
mode: parse_mode(&mode)?,
edition: parse_edition(&edition)?,
crate_type: parse_crate_type(&crate_type)?,
tests,
backtrace,
code,
})
}
}
#[derive(Debug, Snafu)]
pub(crate) enum ExecuteRequestParseError {
#[snafu(transparent)]
Channel { source: ParseChannelError },
#[snafu(transparent)]
CrateType { source: ParseCrateTypeError },
#[snafu(transparent)]
Mode { source: ParseModeError },
#[snafu(transparent)]
Edition { source: ParseEditionError },
}
#[derive(Debug, serde::Serialize)]
#[serde(tag = "type")]
enum MessageResponse {
#[serde(rename = "websocket/error")]
Error { payload: WSError, meta: Meta },
#[serde(rename = "featureFlags")]
FeatureFlags { payload: FeatureFlags, meta: Meta },
#[serde(rename = "output/execute/wsExecuteBegin")]
ExecuteBegin { meta: Meta },
#[serde(rename = "output/execute/wsExecuteStdout")]
ExecuteStdout { payload: String, meta: Meta },
#[serde(rename = "output/execute/wsExecuteStderr")]
ExecuteStderr { payload: String, meta: Meta },
#[serde(rename = "output/execute/wsExecuteStatus")]
ExecuteStatus { payload: ExecuteStatus, meta: Meta },
#[serde(rename = "output/execute/wsExecuteEnd")]
ExecuteEnd {
payload: ExecuteResponse,
meta: Meta,
},
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct WSError {
error: String,
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct FeatureFlags {}
impl From<crate::FeatureFlags> for FeatureFlags {
fn from(_value: crate::FeatureFlags) -> Self {
Self {}
}
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ExecuteStatus {
resident_set_size_bytes: u64,
total_time_secs: f64,
}
impl From<orchestrator::coordinator::ExecuteStatus> for ExecuteStatus {
fn from(value: orchestrator::coordinator::ExecuteStatus) -> Self {
let coordinator::ExecuteStatus {
resident_set_size_bytes,
total_time_secs,
} = value;
Self {
resident_set_size_bytes,
total_time_secs,
}
}
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct ExecuteResponse {
success: bool,
exit_detail: String,
}
#[instrument(skip_all, fields(ws_id))]
pub(crate) async fn handle(
socket: WebSocket,
factory: Arc<CoordinatorFactory>,
feature_flags: FeatureFlags,
db: Handle,
) {
static WEBSOCKET_ID: AtomicU64 = AtomicU64::new(0);
metrics::LIVE_WS.inc();
let start = Instant::now();
let id = WEBSOCKET_ID.fetch_add(1, Ordering::SeqCst);
tracing::Span::current().record("ws_id", &id);
handle_core(socket, factory, feature_flags, db).await;
metrics::LIVE_WS.dec();
let elapsed = start.elapsed();
metrics::DURATION_WS.observe(elapsed.as_secs_f64());
}
type TaggedError = (Error, Option<Meta>);
type ResponseTx = mpsc::Sender<Result<MessageResponse, TaggedError>>;
type SharedCoordinator = Arc<Coordinator<DockerBackend>>;
/// Manages a limited amount of access to the `Coordinator`.
///
/// Has a number of responsibilities:
///
/// - Constructs the `Coordinator` on demand.
///
/// - Only allows one job of a certain kind at a time (e.g. executing
/// vs formatting). Older jobs will be cancelled.
///
/// - Allows limited parallelism between jobs of different types.
struct CoordinatorManager {
coordinator: SharedCoordinator,
tasks: JoinSet<Result<(), TaggedError>>,
semaphore: Arc<Semaphore>,
abort_handles: [Option<AbortHandle>; Self::N_KINDS],
}
impl CoordinatorManager {
const IDLE_TIMEOUT: Duration = Duration::from_secs(60);
const SESSION_TIMEOUT: Duration = Duration::from_secs(45 * 60);
const N_PARALLEL: usize = 2;
const N_KINDS: usize = 1;
const KIND_EXECUTE: usize = 0;
fn new(factory: &CoordinatorFactory) -> Self {
Self {
coordinator: Arc::new(factory.build()),
tasks: Default::default(),
semaphore: Arc::new(Semaphore::new(Self::N_PARALLEL)),
abort_handles: Default::default(),
}
}
fn is_empty(&self) -> bool {
self.tasks.is_empty()
}
async fn join_next(
&mut self,
) -> Option<Result<Result<(), TaggedError>, tokio::task::JoinError>> {
self.tasks.join_next().await
}
async fn spawn<F, Fut>(&mut self, handler: F) -> CoordinatorManagerResult<()>
where
F: FnOnce(SharedCoordinator) -> Fut,
F: 'static + Send,
Fut: Future<Output = Result<(), TaggedError>>,
Fut: 'static + Send,
{
let coordinator = self.coordinator.clone();
let semaphore = self.semaphore.clone();
let new_abort_handle = self.tasks.spawn(
async move {
let _permit = semaphore.acquire().await;
handler(coordinator).await
}
.in_current_span(),
);
let kind = Self::KIND_EXECUTE; // TODO: parameterize when we get a second kind
let old_abort_handle = self.abort_handles[kind].replace(new_abort_handle);
if let Some(abort_handle) = old_abort_handle {
abort_handle.abort();
}
Ok(())
}
async fn idle(&mut self) -> CoordinatorManagerResult<()> {
use coordinator_manager_error::*;
Arc::get_mut(&mut self.coordinator)
.context(OutstandingCoordinatorIdleSnafu)?
.idle()
.await
.context(IdleSnafu)?;
Ok(())
}
async fn shutdown(mut self) -> CoordinatorManagerResult<()> {
use coordinator_manager_error::*;
self.tasks.shutdown().await;
Arc::into_inner(self.coordinator)
.context(OutstandingCoordinatorShutdownSnafu)?
.shutdown()
.await
.context(ShutdownSnafu)?;
Ok(())
}
}
#[derive(Debug, Snafu)]
#[snafu(module)]
pub enum CoordinatorManagerError {
#[snafu(display("The coordinator is still referenced and cannot be idled"))]
OutstandingCoordinatorIdle,
#[snafu(display("Could not idle the coordinator"))]
Idle { source: coordinator::Error },
#[snafu(display("The coordinator is still referenced and cannot be shut down"))]
OutstandingCoordinatorShutdown,
#[snafu(display("Could not shut down the coordinator"))]
Shutdown { source: coordinator::Error },
}
type CoordinatorManagerResult<T, E = CoordinatorManagerError> = std::result::Result<T, E>;
async fn handle_core(
mut socket: WebSocket,
factory: Arc<CoordinatorFactory>,
feature_flags: FeatureFlags,
db: Handle,
) {
if !connect_handshake(&mut socket).await {
return;
}
let (tx, mut rx) = mpsc::channel(3);
let ff = MessageResponse::FeatureFlags {
payload: feature_flags,
meta: create_server_meta(),
};
if tx.send(Ok(ff)).await.is_err() {
return;
}
let mut manager = CoordinatorManager::new(&factory);
let mut session_timeout = pin!(time::sleep(CoordinatorManager::SESSION_TIMEOUT));
let mut idle_timeout = pin!(Fuse::terminated());
let mut active_executions = BTreeMap::new();
let mut active_execution_gc_interval = time::interval(Duration::from_secs(30));
loop {
tokio::select! {
request = socket.recv() => {
metrics::WS_INCOMING.inc();
match request {
None => {
// browser disconnected
break;
}
Some(Ok(Message::Text(txt))) => handle_msg(txt, &tx, &mut manager, &mut active_executions, &db).await,
Some(Ok(_)) => {
// unknown message type
continue;
}
Some(Err(e)) => super::record_websocket_error(e.to_string()),
}
},
resp = rx.recv() => {
let resp = resp.expect("The rx should never close as we have a tx");
let success = resp.is_ok();
let resp = resp.unwrap_or_else(error_to_response);
let resp = response_to_message(resp);
if socket.send(resp).await.is_err() {
// We can't send a response
break;
}
let success = if success { "true" } else { "false" };
metrics::WS_OUTGOING.with_label_values(&[success]).inc();
},
// We don't care if there are no running tasks
Some(task) = manager.join_next() => {
// The last task has completed which means we are a
// candidate for idling in a little while.
if manager.is_empty() {
idle_timeout.set(time::sleep(CoordinatorManager::IDLE_TIMEOUT).fuse());
}
let (error, meta) = match task {
Ok(Ok(())) => continue,
Ok(Err(error)) => error,
Err(error) => {
// The task was cancelled; no need to report
let Ok(panic) = error.try_into_panic() else { continue };
let text = match panic.downcast::<String>() {
Ok(text) => *text,
Err(panic) => match panic.downcast::<&str>() {
Ok(text) => text.to_string(),
_ => "An unknown panic occurred".into(),
}
};
(WebSocketTaskPanicSnafu { text }.build(), None)
}
};
if tx.send(Err((error, meta))).await.is_err() {
// We can't send a response
break;
}
},
_ = active_execution_gc_interval.tick() => {
active_executions = mem::take(&mut active_executions)
.into_iter()
.filter(|(_id, (_, tx))| tx.as_ref().map_or(false, |tx| !tx.is_closed()))
.collect();
},
_ = &mut idle_timeout, if manager.is_empty() => {
let idled = manager.idle().await.context(StreamingCoordinatorIdleSnafu);
let Err(error) = idled else { continue };
if tx.send(Err((error, None))).await.is_err() {
// We can't send a response
break;
}
},
_ = &mut session_timeout => {
break;
}
}
}
drop((tx, rx, socket));
if let Err(e) = manager.shutdown().await {
error!("Could not shut down the Coordinator: {e:?}");
}
}
async fn connect_handshake(socket: &mut WebSocket) -> bool {
let Some(Ok(Message::Text(txt))) = socket.recv().await else {
return false;
};
let Ok(HandshakeMessage::Connected { payload, .. }) =
serde_json::from_str::<HandshakeMessage>(&txt)
else {
return false;
};
if !payload.i_accept_this_is_an_unsupported_api {
return false;
}
socket.send(Message::Text(txt)).await.is_ok()
}
fn create_server_meta() -> Meta {
Arc::new(MetaInner {
sequence_number: -1,
})
}
fn error_to_response((error, meta): TaggedError) -> MessageResponse {
let error = snafu::CleanedErrorText::new(&error)
.map(|(_, t, _)| t)
.reduce(|e, t| e + ": " + &t)
.unwrap_or_default();
let payload = WSError { error };
let meta = meta.unwrap_or_else(create_server_meta);
MessageResponse::Error { payload, meta }
}
fn response_to_message(response: MessageResponse) -> Message {
const LAST_CHANCE_ERROR: &str =
r#"{ "type": "WEBSOCKET_ERROR", "error": "Unable to serialize JSON" }"#;
let resp = serde_json::to_string(&response).unwrap_or_else(|_| LAST_CHANCE_ERROR.into());
Message::Text(resp)
}
type ActiveExecutionInfo = (CancellationToken, Option<mpsc::Sender<String>>);
async fn handle_msg(
txt: String,
tx: &ResponseTx,
manager: &mut CoordinatorManager,
active_executions: &mut BTreeMap<i64, ActiveExecutionInfo>,
db: &Handle,
) {
use WSMessageRequest::*;
let msg = serde_json::from_str(&txt).context(DeserializationSnafu);
match msg {
Ok(ExecuteRequest { payload, meta }) => {
let token = CancellationToken::new();
let (execution_tx, execution_rx) = mpsc::channel(8);
let guard = db.clone().start_with_guard("ws.Execute", &txt).await;
active_executions.insert(meta.sequence_number, (token.clone(), Some(execution_tx)));
// TODO: Should a single execute / build / etc. session have a timeout of some kind?
let spawned = manager
.spawn({
let tx = tx.clone();
let meta = meta.clone();
|coordinator| async {
let r = handle_execute(
token,
execution_rx,
tx,
coordinator,
payload,
meta.clone(),
)
.context(StreamingExecuteSnafu)
.map_err(|e| (e, Some(meta)))
.await;
guard.complete_now(r)
}
})
.await
.context(StreamingCoordinatorSpawnSnafu);
if let Err(e) = spawned {
tx.send(Err((e, Some(meta)))).await.ok(/* We don't care if the channel is closed */);
}
}
Ok(ExecuteStdin { payload, meta }) => {
let Some((_, Some(execution_tx))) = active_executions.get(&meta.sequence_number) else {
warn!("Received stdin for an execution that is no longer active");
return;
};
let sent = execution_tx
.send(payload)
.await
.drop_error_details()
.context(StreamingCoordinatorExecuteStdinSnafu);
if let Err(e) = sent {
tx.send(Err((e, Some(meta)))).await.ok(/* We don't care if the channel is closed */);
}
}
Ok(ExecuteStdinClose { meta }) => {
let Some((_, execution_tx)) = active_executions.get_mut(&meta.sequence_number) else {
warn!("Received stdin close for an execution that is no longer active");
return;
};
*execution_tx = None; // Drop to signal closed
}
Ok(ExecuteKill { meta }) => {
let Some((token, _)) = active_executions.get(&meta.sequence_number) else {
warn!("Received kill for an execution that is no longer active");
return;
};
token.cancel();
}
Err(e) => {
tx.send(Err((e, None))).await.ok(/* We don't care if the channel is closed */);
}
}
}
#[derive(Debug)]
enum CompletedOrAbandoned<T> {
Abandoned,
Completed(T),
}
macro_rules! abandon_if_closed {
($sent:expr) => {
if $sent.is_err() {
return Ok(CompletedOrAbandoned::Abandoned);
}
};
}
async fn handle_execute(
token: CancellationToken,
rx: mpsc::Receiver<String>,
tx: ResponseTx,
coordinator: SharedCoordinator,
req: ExecuteRequest,
meta: Meta,
) -> ExecuteResult<()> {
use execute_error::*;
use CompletedOrAbandoned::*;
let req = coordinator::ExecuteRequest::try_from(req).context(BadRequestSnafu)?;
let labels_core = req.labels_core();
let start = Instant::now();
let v = handle_execute_inner(token, rx, tx, coordinator, req, meta).await;
let elapsed = start.elapsed();
let outcome = match &v {
Ok(Abandoned) => Outcome::Abandoned,
Ok(Completed(v)) => *v,
Err(_) => Outcome::ErrorServer,
};
record_metric(Endpoint::Execute, labels_core, outcome, elapsed);
v?;
Ok(())
}
async fn handle_execute_inner(
token: CancellationToken,
mut rx: mpsc::Receiver<String>,
tx: ResponseTx,
coordinator: SharedCoordinator,
req: coordinator::ExecuteRequest,
meta: Meta,
) -> ExecuteResult<CompletedOrAbandoned<Outcome>> {
use execute_error::*;
use CompletedOrAbandoned::*;
let coordinator::ActiveExecution {
permit: _permit,
mut task,
stdin_tx,
mut stdout_rx,
mut stderr_rx,
mut status_rx,
} = coordinator
.begin_execute(token.clone(), req.clone())
.await
.context(BeginSnafu)?;
let sent = tx
.send(Ok(MessageResponse::ExecuteBegin { meta: meta.clone() }))
.await;
abandon_if_closed!(sent);
let mut stdin_tx = Some(stdin_tx);
let send_stdout = |payload| async {
let meta = meta.clone();
tx.send(Ok(MessageResponse::ExecuteStdout { payload, meta }))
.await
};
let send_stderr = |payload| async {
let meta = meta.clone();
tx.send(Ok(MessageResponse::ExecuteStderr { payload, meta }))
.await
};
let mut reported = false;
let status = loop {
tokio::select! {
status = &mut task => break status,
stdin = rx.recv(), if stdin_tx.is_some() => {
match stdin {
Some(stdin) => {
stdin_tx
.as_ref()
.unwrap(/* This is a precondition */)
.send(stdin)
.await
.drop_error_details()
.context(StdinSnafu)?;
}
None => {
let stdin_tx = stdin_tx.take();
drop(stdin_tx); // Signal closed
}
}
}
Some(stdout) = stdout_rx.recv() => {
let sent = send_stdout(stdout).await;
abandon_if_closed!(sent);
},
Some(stderr) = stderr_rx.recv() => {
let sent = send_stderr(stderr).await;
abandon_if_closed!(sent);
},
Some(status) = status_rx.next() => {
if !reported && status.total_time_secs > 60.0 {
error!("Request consumed more than 60s of CPU time: {req:?}");
reported = true;
}
let payload = status.into();
let meta = meta.clone();
let sent = tx.send(Ok(MessageResponse::ExecuteStatus { payload, meta })).await;
abandon_if_closed!(sent);
}
}
};
// Drain any remaining output
while let Some(Some(stdout)) = stdout_rx.recv().now_or_never() {
let sent = send_stdout(stdout).await;
abandon_if_closed!(sent);
}
while let Some(Some(stderr)) = stderr_rx.recv().now_or_never() {
let sent = send_stderr(stderr).await;
abandon_if_closed!(sent);
}
let status = status.context(EndSnafu)?;
let outcome = Outcome::from_success(&status);
let coordinator::ExecuteResponse {
success,
exit_detail,
} = status;
let sent = tx
.send(Ok(MessageResponse::ExecuteEnd {
payload: ExecuteResponse {
success,
exit_detail,
},
meta,
}))
.await;
abandon_if_closed!(sent);
Ok(Completed(outcome))
}
#[derive(Debug, Snafu)]
#[snafu(module)]
pub(crate) enum ExecuteError {
#[snafu(display("The request could not be parsed"))]
BadRequest { source: ExecuteRequestParseError },
#[snafu(display("Could not begin the execution session"))]
Begin { source: coordinator::ExecuteError },
#[snafu(display("Could not end the execution session"))]
End { source: coordinator::ExecuteError },
#[snafu(display("Could not send stdin to the coordinator"))]
Stdin {
source: tokio::sync::mpsc::error::SendError<()>,
},
}
type ExecuteResult<T, E = ExecuteError> = std::result::Result<T, E>;
#[derive(Debug, Snafu)]
enum Error {
#[snafu(display("Unable to deserialize request"))]
Deserialization { source: serde_json::Error },
#[snafu(display("The WebSocket worker panicked: {}", text))]
WebSocketTaskPanic { text: String },
#[snafu(display("Unable to spawn a coordinator task"))]
StreamingCoordinatorSpawn { source: CoordinatorManagerError },
#[snafu(display("Unable to idle the coordinator"))]
StreamingCoordinatorIdle { source: CoordinatorManagerError },
#[snafu(display("Unable to perform a streaming execute"))]
StreamingExecute { source: ExecuteError },
#[snafu(display("Unable to pass stdin to the active execution"))]
StreamingCoordinatorExecuteStdin {
source: tokio::sync::mpsc::error::SendError<()>,
},
}
```
|
```rust
/*
*
* This software may be used and distributed according to the terms of the
*/
use std::fmt;
use std::future::Future;
use std::num::NonZeroU32;
use std::sync::Arc;
use std::time::Duration;
use anyhow::format_err;
use anyhow::Result;
use async_trait::async_trait;
use blobstore::Blobstore;
use blobstore::BlobstoreGetData;
use blobstore::BlobstoreIsPresent;
use blobstore::BlobstorePutOps;
use blobstore::BlobstoreUnlinkOps;
use blobstore::CountedBlobstore;
use blobstore::OverwriteStatus;
use blobstore::PutBehaviour;
use context::CoreContext;
use context::PerfCounterType;
use mononoke_types::BlobstoreBytes;
use rusoto_s3::DeleteObjectRequest;
use rusoto_s3::GetObjectRequest;
use rusoto_s3::HeadObjectRequest;
use rusoto_s3::PutObjectRequest;
use crate::S3ClientBackend;
const MAX_ATTEMPT_NUM: NonZeroU32 = nonzero_ext::nonzero!(4u32);
async fn retry<Retryable, V, Fut>(ctx: &CoreContext, retryable: Retryable) -> Result<V>
where
Retryable: Fn() -> Fut,
V: Send + Sync + 'static,
Fut: Future<Output = Result<V>>,
{
let mut attempt = nonzero_ext::nonzero!(1u32);
loop {
let resp = retryable().await;
match resp {
Ok(v) => return Ok(v),
Err(e) => {
let duration = if attempt >= MAX_ATTEMPT_NUM {
None
} else {
Some(Duration::from_millis(100 * 4u64.pow(attempt.get() - 1)))
};
if let Some(duration) = duration {
let pc = ctx.perf_counters();
pc.increment_counter(PerfCounterType::S3BlobRetries);
pc.add_to_counter(PerfCounterType::S3BlobSumDelay, duration.as_millis() as i64);
tokio::time::sleep(duration).await;
attempt = NonZeroU32::new(attempt.get() + 1).unwrap();
continue;
} else {
return Err(e.context(format_err!("Request failed on attempt {}", attempt)));
}
}
}
}
}
pub struct S3Blob<ClientBackend: S3ClientBackend + Send + Sync> {
bucket: String,
client_pool: Arc<ClientBackend>,
put_behaviour: PutBehaviour,
}
impl<ClientBackend: S3ClientBackend + Send + Sync> fmt::Display for S3Blob<ClientBackend> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "S3Blob")
}
}
impl<ClientBackend: S3ClientBackend + Send + Sync> fmt::Debug for S3Blob<ClientBackend> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("S3Blob")
.field("bucket", &self.bucket)
.field("client", &"S3Client")
.finish()
}
}
impl<ClientBackend: S3ClientBackend + Send + Sync> S3Blob<ClientBackend> {
pub async fn new<T: ToString>(
bucket: T,
client_backend: Arc<ClientBackend>,
put_behaviour: PutBehaviour,
) -> Result<CountedBlobstore<Self>> {
let blob = Self {
bucket: bucket.to_string(),
client_pool: client_backend,
put_behaviour,
};
Ok(CountedBlobstore::new(
format!("s3.{}", bucket.to_string()),
blob,
))
}
}
#[async_trait]
impl<ClientBackend: S3ClientBackend + Send + Sync> Blobstore for S3Blob<ClientBackend> {
async fn get<'a>(
&'a self,
ctx: &'a CoreContext,
key: &'a str,
) -> Result<Option<BlobstoreGetData>> {
retry(ctx, || {
let key = ClientBackend::get_sharded_key(key);
let request = GetObjectRequest {
bucket: self.bucket.to_string(),
key,
..Default::default()
};
async move { self.client_pool.get_client().get(ctx, request).await }
})
.await
}
async fn is_present<'a>(
&'a self,
ctx: &'a CoreContext,
key: &'a str,
) -> Result<BlobstoreIsPresent> {
retry(ctx, || {
let key = ClientBackend::get_sharded_key(key);
let request = HeadObjectRequest {
bucket: self.bucket.to_string(),
key,
..Default::default()
};
async move {
let present = self
.client_pool
.get_client()
.is_present(ctx, request)
.await?;
Ok(if present {
BlobstoreIsPresent::Present
} else {
BlobstoreIsPresent::Absent
})
}
})
.await
}
async fn put<'a>(
&'a self,
ctx: &'a CoreContext,
key: String,
value: BlobstoreBytes,
) -> Result<()> {
BlobstorePutOps::put_with_status(self, ctx, key, value).await?;
Ok(())
}
}
#[async_trait]
impl<ClientBackend: S3ClientBackend + Send + Sync> BlobstorePutOps for S3Blob<ClientBackend> {
async fn put_explicit<'a>(
&'a self,
ctx: &'a CoreContext,
orig_key: String,
value: BlobstoreBytes,
put_behaviour: PutBehaviour,
) -> Result<OverwriteStatus> {
retry(ctx, || {
let key = ClientBackend::get_sharded_key(&orig_key);
let content: Vec<u8> = value.as_bytes().as_ref().to_vec();
let request = PutObjectRequest {
bucket: self.bucket.to_string(),
key,
body: Some(content.into()),
..Default::default()
};
let orig_key = &orig_key;
async move {
let put_fut = async {
self.client_pool.get_client().put(ctx, request).await?;
Ok(OverwriteStatus::NotChecked)
};
match put_behaviour {
PutBehaviour::Overwrite => put_fut.await,
PutBehaviour::IfAbsent | PutBehaviour::OverwriteAndLog => {
if self.is_present(ctx, orig_key).await?.fail_if_unsure()? {
if put_behaviour.should_overwrite() {
put_fut.await?;
Ok(OverwriteStatus::Overwrote)
} else {
// discard the put
std::mem::drop(put_fut);
Ok(OverwriteStatus::Prevented)
}
} else {
put_fut.await?;
Ok(OverwriteStatus::New)
}
}
}
}
})
.await
}
async fn put_with_status<'a>(
&'a self,
ctx: &'a CoreContext,
key: String,
value: BlobstoreBytes,
) -> Result<OverwriteStatus> {
self.put_explicit(ctx, key, value, self.put_behaviour).await
}
}
#[async_trait]
impl<ClientBackend: S3ClientBackend + Send + Sync> BlobstoreUnlinkOps for S3Blob<ClientBackend> {
async fn unlink<'a>(&'a self, ctx: &'a CoreContext, key: &'a str) -> Result<()> {
retry(ctx, || {
let key = ClientBackend::get_sharded_key(key);
let request = DeleteObjectRequest {
bucket: self.bucket.to_string(),
key,
..Default::default()
};
async move { self.client_pool.get_client().unlink(ctx, request).await }
})
.await
}
}
```
|
```c
/*
FSearch - A fast file search utility
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
*/
#define G_LOG_DOMAIN "fsearch-dynamic-array"
#include "fsearch_array.h"
#include <glib.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#define MAX_SORT_THREADS 8
struct DynamicArray {
// number of items in array
uint32_t num_items;
// total size of array
uint32_t max_items;
// data
void **data;
volatile int ref_count;
};
static void
darray_free(DynamicArray *array) {
if (array == NULL) {
return;
}
g_debug("[darray_free] freed");
g_clear_pointer(&array->data, free);
g_clear_pointer(&array, free);
}
DynamicArray *
darray_ref(DynamicArray *array) {
if (!array || g_atomic_int_get(&array->ref_count) <= 0) {
return NULL;
}
g_atomic_int_inc(&array->ref_count);
// g_debug("[darray_ref] increased to: %d", array->ref_count);
return array;
}
void
darray_unref(DynamicArray *array) {
if (!array || g_atomic_int_get(&array->ref_count) <= 0) {
return;
}
// g_debug("[darray_unref] dropped to: %d", array->ref_count - 1);
if (g_atomic_int_dec_and_test(&array->ref_count)) {
g_clear_pointer(&array, darray_free);
}
}
typedef struct {
DynamicArray *m1;
DynamicArray *m2;
DynamicArray *dest;
gpointer user_data;
DynamicArrayCompareDataFunc comp_func;
} DynamicArraySortContext;
static void
insertion_sort(DynamicArray *array, DynamicArrayCompareDataFunc comp_func, void *data) {
for (uint32_t i = 0; i < array->num_items; ++i) {
void *val_a = array->data[i];
uint32_t j = i;
while (j > 0 && comp_func(&array->data[j - 1], &val_a, data) > 0) {
array->data[j] = array->data[j - 1];
j--;
}
array->data[j] = val_a;
}
}
static void
merge(DynamicArray *src,
DynamicArray *dest,
uint32_t start_idx,
uint32_t center_idx,
uint32_t end_idx,
GCancellable *cancellable,
DynamicArrayCompareDataFunc comp_func,
gpointer comp_data) {
if (cancellable && g_cancellable_is_cancelled(cancellable)) {
return;
}
uint32_t i = start_idx;
uint32_t j = center_idx;
for (uint32_t k = start_idx; k < end_idx; k++) {
if (i < center_idx && (j >= end_idx || comp_func(&src->data[i], &src->data[j], comp_data) < 1)) {
dest->data[k] = src->data[i];
i = i + 1;
}
else {
dest->data[k] = src->data[j];
j = j + 1;
}
}
}
static void
split_merge(DynamicArray *src,
DynamicArray *dest,
uint32_t start_idx,
uint32_t end_idx,
GCancellable *cancellable,
DynamicArrayCompareDataFunc comp_func,
gpointer comp_data) {
if (end_idx - 1 <= start_idx) {
return;
}
if (cancellable && g_cancellable_is_cancelled(cancellable)) {
return;
}
uint32_t center_idx = (end_idx + start_idx) / 2;
split_merge(dest, src, start_idx, center_idx, cancellable, comp_func, comp_data);
split_merge(dest, src, center_idx, end_idx, cancellable, comp_func, comp_data);
merge(src, dest, start_idx, center_idx, end_idx, cancellable, comp_func, comp_data);
}
static void
merge_sort(DynamicArray *to_sort,
DynamicArray *tmp,
GCancellable *cancellable,
DynamicArrayCompareDataFunc comp_func,
gpointer comp_data) {
split_merge(tmp, to_sort, 0, to_sort->num_items, cancellable, comp_func, comp_data);
}
static void
sort_thread(gpointer data, gpointer user_data) {
DynamicArraySortContext *ctx = data;
DynamicArray *tmp = darray_copy(ctx->dest);
merge_sort(ctx->dest, tmp, user_data, (DynamicArrayCompareDataFunc)ctx->comp_func, ctx->user_data);
g_clear_pointer(&tmp, darray_unref);
}
static void
merge_thread(gpointer data, gpointer user_data) {
DynamicArraySortContext *ctx = data;
int i = 0;
int j = 0;
const uint32_t n1 = ctx->m1->num_items;
const uint32_t n2 = ctx->m2->num_items;
while (true) {
void *d1 = darray_get_item(ctx->m1, i);
void *d2 = darray_get_item(ctx->m2, j);
if (i < n1 && j < n2) {
const int res = ctx->comp_func(&d1, &d2, user_data);
if (res <= 0) {
darray_add_item(ctx->dest, d1);
i++;
}
else {
darray_add_item(ctx->dest, d2);
j++;
}
}
else {
if (i < n1) {
darray_add_items(ctx->dest, &ctx->m1->data[i], ctx->m1->num_items - i);
return;
}
else if (j < n2) {
darray_add_items(ctx->dest, &ctx->m2->data[j], ctx->m2->num_items - j);
return;
}
else {
return;
}
}
}
}
DynamicArray *
darray_new(size_t num_items) {
DynamicArray *new = calloc(1, sizeof(DynamicArray));
g_assert(new);
new->max_items = num_items;
new->num_items = 0;
new->data = calloc(num_items, sizeof(void *));
g_assert(new->data);
new->ref_count = 1;
return new;
}
static void
darray_expand(DynamicArray *array, size_t min) {
g_assert(array);
g_assert(array->data);
const size_t old_max_items = array->max_items;
const size_t expand_rate = MAX(array->max_items / 2, min - old_max_items);
array->max_items += expand_rate;
void *new_data = realloc(array->data, array->max_items * sizeof(void *));
g_assert(new_data);
array->data = new_data;
memset(array->data + old_max_items, 0, expand_rate + 1);
}
void
darray_add_items(DynamicArray *array, void **items, uint32_t num_items) {
g_assert(array);
g_assert(array->data);
g_assert(items);
if (array->num_items + num_items > array->max_items) {
darray_expand(array, array->num_items + num_items);
}
memcpy(array->data + array->num_items, items, num_items * sizeof(void *));
array->num_items += num_items;
}
void
darray_add_item(DynamicArray *array, void *data) {
g_assert(array);
g_assert(array->data);
// g_assert(data );
if (array->num_items >= array->max_items) {
darray_expand(array, array->num_items + 1);
}
array->data[array->num_items++] = data;
}
bool
darray_get_item_idx(DynamicArray *array, void *item, DynamicArrayCompareDataFunc compare_func, void *data, uint32_t *index) {
g_assert(array);
g_assert(index);
if (compare_func) {
return darray_binary_search_with_data(array, item, compare_func, data, index);
}
bool found = false;
for (uint32_t i = 0; i < array->num_items; i++) {
if (item == array->data[i]) {
found = true;
*index = i;
break;
}
}
return found;
}
void *
darray_get_item_next(DynamicArray *array,
void *item,
DynamicArrayCompareDataFunc compare_func,
void *data,
uint32_t *next_idx) {
g_assert(array);
uint32_t index = 0;
if (!darray_get_item_idx(array, item, compare_func, data, &index)) {
return NULL;
}
if (index >= array->num_items - 1) {
return NULL;
}
if (next_idx) {
*next_idx = index + 1;
}
return array->data[index + 1];
}
void *
darray_get_item(DynamicArray *array, uint32_t idx) {
g_assert(array);
g_assert(array->data);
if (idx >= array->num_items) {
return NULL;
}
return array->data[idx];
}
uint32_t
darray_get_num_items(DynamicArray *array) {
g_assert(array);
g_assert(array->data);
return array->num_items;
}
uint32_t
darray_get_size(DynamicArray *array) {
g_assert(array);
g_assert(array->data);
return array->max_items;
}
static DynamicArray *
new_array_from_data(void **data, uint32_t num_items) {
DynamicArray *array = darray_new(num_items);
darray_add_items(array, data, num_items);
return array;
}
static GArray *
merge_sorted(GArray *merge_me, DynamicArrayCompareDataFunc comp_func, GCancellable *cancellable) {
if (merge_me->len == 1) {
return merge_me;
}
if (cancellable && g_cancellable_is_cancelled(cancellable)) {
return merge_me;
}
const uint32_t num_threads = merge_me->len / 2;
g_debug("[sort] merge with %d thread(s)", num_threads);
GArray *merged_data = g_array_sized_new(TRUE, TRUE, sizeof(DynamicArraySortContext), num_threads);
GThreadPool *merge_pool = g_thread_pool_new(merge_thread, NULL, (gint)num_threads, FALSE, NULL);
for (int i = 0; i < num_threads; ++i) {
DynamicArraySortContext *c1 = &g_array_index(merge_me, DynamicArraySortContext, 2 * i);
DynamicArraySortContext *c2 = &g_array_index(merge_me, DynamicArraySortContext, 2 * i + 1);
DynamicArray *i1 = c1->dest;
DynamicArray *i2 = c2->dest;
DynamicArraySortContext merge_ctx = {};
merge_ctx.m1 = i1;
merge_ctx.m2 = i2;
merge_ctx.comp_func = comp_func;
merge_ctx.dest = darray_new(i1->num_items + i2->num_items);
g_array_insert_val(merged_data, i, merge_ctx);
g_thread_pool_push(merge_pool, &g_array_index(merged_data, DynamicArraySortContext, i), NULL);
}
g_thread_pool_free(g_steal_pointer(&merge_pool), FALSE, TRUE);
for (int i = 0; i < merge_me->len; i++) {
DynamicArraySortContext *c = &g_array_index(merge_me, DynamicArraySortContext, i);
if (c && c->dest) {
g_clear_pointer(&c->dest, darray_free);
}
}
return merge_sorted(merged_data, comp_func, cancellable);
}
static int
get_ideal_thread_count() {
// int num_processors = 1;
const int num_processors = (int)g_get_num_processors();
const int e = floor(log2(num_processors));
const int num_threads = (int)pow(2, e);
return MAX(num_threads, MAX_SORT_THREADS);
}
void
darray_sort_multi_threaded(DynamicArray *array,
DynamicArrayCompareDataFunc comp_func,
GCancellable *cancellable,
void *data) {
const int num_threads = get_ideal_thread_count();
if (num_threads < 2 || num_threads > array->num_items) {
return darray_sort(array, comp_func, NULL, data);
}
g_debug("[sort] sorting with %d threads", num_threads);
const int num_items_per_thread = (int)(array->num_items / num_threads);
GThreadPool *sort_pool = g_thread_pool_new(sort_thread, cancellable, num_threads, FALSE, NULL);
g_autoptr(GArray) sort_ctx_array = g_array_sized_new(TRUE, TRUE, sizeof(DynamicArraySortContext), num_threads);
int start = 0;
for (int i = 0; i < num_threads; ++i) {
DynamicArraySortContext sort_ctx;
sort_ctx.dest = new_array_from_data(array->data + start,
i == num_threads - 1 ? array->num_items - start : num_items_per_thread);
sort_ctx.comp_func = comp_func;
sort_ctx.user_data = data;
start += num_items_per_thread;
g_array_insert_val(sort_ctx_array, i, sort_ctx);
g_thread_pool_push(sort_pool, &g_array_index(sort_ctx_array, DynamicArraySortContext, i), NULL);
}
g_thread_pool_free(g_steal_pointer(&sort_pool), FALSE, TRUE);
g_autoptr(GArray) result = merge_sorted(sort_ctx_array, comp_func, cancellable);
if (result) {
g_clear_pointer(&array->data, free);
DynamicArraySortContext *c = &g_array_index(result, DynamicArraySortContext, 0);
array->data = g_steal_pointer(&c->dest->data);
array->num_items = c->dest->num_items;
array->max_items = c->dest->max_items;
g_clear_pointer(&c->dest, free);
}
}
void
darray_sort(DynamicArray *array, DynamicArrayCompareDataFunc comp_func, GCancellable *cancellable, void *data) {
g_assert(array);
g_assert(array->data);
g_assert(comp_func);
if (array->num_items < 64) {
g_debug("[sort] insertion sort: %d\n", array->num_items);
insertion_sort(array, comp_func, data);
}
else {
g_debug("[sort] merge sort: %d\n", array->num_items);
DynamicArray *src = darray_copy(array);
merge_sort(array, src, cancellable, comp_func, data);
g_clear_pointer(&src, darray_unref);
}
}
bool
darray_binary_search_with_data(DynamicArray *array,
void *item,
DynamicArrayCompareDataFunc comp_func,
void *data,
uint32_t *matched_index) {
g_assert(array);
g_assert(array->data);
g_assert(comp_func);
if (array->num_items <= 0) {
return false;
}
bool result = false;
uint32_t left = 0;
uint32_t middle = 0;
uint32_t right = array->num_items - 1;
while (left <= right) {
middle = left + (right - left) / 2;
int32_t match = comp_func(&array->data[middle], &item, data);
if (match == 0) {
result = true;
break;
}
else if (match < 0) {
left = middle + 1;
}
else if (middle > 0) {
// match > 0
// This means the item is to the left of middle
// If middle == 0 then the item is not in the array
right = middle - 1;
}
else {
break;
}
}
if (result && matched_index != NULL)
*matched_index = middle;
return result;
}
DynamicArray *
darray_copy(DynamicArray *array) {
if (!array) {
return NULL;
}
DynamicArray *new = calloc(1, sizeof(DynamicArray));
g_assert(new);
new->max_items = array->max_items;
new->num_items = array->num_items;
new->data = calloc(new->max_items, sizeof(void *));
g_assert(new->data);
new->ref_count = 1;
memcpy(new->data, array->data, new->max_items * sizeof(void *));
return new;
}
```
|
```kotlin
/*
* that can be found in the LICENSE file.
*/
package kotlin.ranges
/**
* An iterator over a progression of values of type `Char`.
* @property step the number by which the value is incremented on each step.
*/
internal class CharProgressionIterator(first: Char, last: Char, val step: Int) : CharIterator() {
private val finalElement = last.toInt()
private var hasNext: Boolean = if (step > 0) first <= last else first >= last
private var next = if (hasNext) first.toInt() else finalElement
override fun hasNext(): Boolean = hasNext
override fun nextChar(): Char {
val value = next
if (value == finalElement) {
if (!hasNext) throw kotlin.NoSuchElementException()
hasNext = false
}
else {
next += step
}
return value.toChar()
}
}
/**
* An iterator over a progression of values of type `Int`.
* @property step the number by which the value is incremented on each step.
*/
internal class IntProgressionIterator(first: Int, last: Int, val step: Int) : IntIterator() {
private val finalElement = last
private var hasNext: Boolean = if (step > 0) first <= last else first >= last
private var next = if (hasNext) first else finalElement
override fun hasNext(): Boolean = hasNext
override fun nextInt(): Int {
val value = next
if (value == finalElement) {
if (!hasNext) throw kotlin.NoSuchElementException()
hasNext = false
}
else {
next += step
}
return value
}
}
/**
* An iterator over a progression of values of type `Long`.
* @property step the number by which the value is incremented on each step.
*/
internal class LongProgressionIterator(first: Long, last: Long, val step: Long) : LongIterator() {
private val finalElement = last
private var hasNext: Boolean = if (step > 0) first <= last else first >= last
private var next = if (hasNext) first else finalElement
override fun hasNext(): Boolean = hasNext
override fun nextLong(): Long {
val value = next
if (value == finalElement) {
if (!hasNext) throw kotlin.NoSuchElementException()
hasNext = false
}
else {
next += step
}
return value
}
}
```
|
Nicolaas van Buren (1578–1619), Latinized Nicolaus Burenus, was a Dutch Jesuit and a translator of controversial and devotional writings. Born in Arnhem, he became a Jesuit in 1596, and died in the Spanish Netherlands on 18 October 1619.
Authors that he translated include Martin Becanus, Francisco Arias, Robert Bellarmine, Luca Pinelli and Fulvio Androzzi.
Translations
Francisco Arias, Het goedt ghebruyck van de twee H. Sacramenten der Biechten ende des Autaers (Antwerp, Joachim Trognaesius, 1603; 2nd edition 1607)
Robert Bellarmine, Opclimminghe des gheests tot Godt door de leeder der creatueren (Antwerp, Willem Lesteens, 1617)
Fulvio Androzzi, Onderwys oft practycke om dikwils het H. Sacrament des Autaers profytelyck te nutten (Antwerp, Willem Lesteens, 1618)
Martin Becanus, Verschillen oft verscheijden titels der Calvinisten (Antwerp, Willem Lesteens, 1618)
Francisco Arias, Van de tegenwoordigheid Gods (Antwerp, Willem Lesteens, 1619)
Luca Pinelli, De cracht ende Misterie der H. Misse (Antwerp, Willem Lesteens, 1620)
References
People from Arnhem
1578 births
1619 deaths
16th-century Dutch Jesuits
Latin–Dutch translators
17th-century Dutch Jesuits
|
```html
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "path_to_url">
<html xmlns="path_to_url" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.6: path_to_url" />
<title>Parallel BGL s-t Connectivity</title>
<link rel="stylesheet" href="../../../../rst.css" type="text/css" />
</head>
<body>
<div class="document" id="logo-s-t-connectivity">
<h1 class="title"><a class="reference external" href="path_to_url"><img align="middle" alt="Parallel BGL" class="align-middle" src="pbgl-logo.png" /></a> s-t Connectivity</h1>
Use, modification and distribution is subject to the Boost Software
path_to_url -->
<pre class="literal-block">
namespace graph { namespace distributed {
template<typename DistributedGraph, typename ColorMap>
inline bool
st_connected(const DistributedGraph& g,
typename graph_traits<DistributedGraph>::vertex_descriptor s,
typename graph_traits<DistributedGraph>::vertex_descriptor t,
ColorMap color)
template<typename DistributedGraph>
inline bool
st_connected(const DistributedGraph& g,
typename graph_traits<DistributedGraph>::vertex_descriptor s,
typename graph_traits<DistributedGraph>::vertex_descriptor t)
template<typename DistributedGraph, typename ColorMap, typename OwnerMap>
bool
st_connected(const DistributedGraph& g,
typename graph_traits<DistributedGraph>::vertex_descriptor s,
typename graph_traits<DistributedGraph>::vertex_descriptor t,
ColorMap color, OwnerMap owner)
} }
</pre>
<p>The <tt class="docutils literal"><span class="pre">st_connected()</span></tt> function determines whether there exists a path
from <tt class="docutils literal"><span class="pre">s</span></tt> to <tt class="docutils literal"><span class="pre">t</span></tt> in a graph <tt class="docutils literal"><span class="pre">g</span></tt>. If a path exists the function
returns <tt class="docutils literal"><span class="pre">true</span></tt>, otherwise it returns <tt class="docutils literal"><span class="pre">false</span></tt>.</p>
<p>This algorithm is currently <em>level-synchronized</em>, meaning that all
vertices in a given level of the search tree will be processed
(potentially in parallel) before any vertices from a successive level
in the tree are processed. This is not necessary for the correctness
of the algorithm but rather is an implementation detail. This
algorithm could be rewritten fully-asynchronously using triggers which
would remove the level-synchronized behavior.</p>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#where-defined" id="id1">Where Defined</a></li>
<li><a class="reference internal" href="#parameters" id="id2">Parameters</a></li>
<li><a class="reference internal" href="#complexity" id="id3">Complexity</a></li>
<li><a class="reference internal" href="#algorithm-description" id="id4">Algorithm Description</a></li>
</ul>
</div>
<div class="section" id="where-defined">
<h1><a class="toc-backref" href="#id1">Where Defined</a></h1>
<p><<tt class="docutils literal"><span class="pre">boost/graph/distributed/st_connected.hpp</span></tt>></p>
</div>
<div class="section" id="parameters">
<h1><a class="toc-backref" href="#id2">Parameters</a></h1>
<dl class="docutils">
<dt>IN: <tt class="docutils literal"><span class="pre">const</span> <span class="pre">DistributedGraph&</span> <span class="pre">g</span></tt></dt>
<dd>The graph type must be a model of <a class="reference external" href="DistributedGraph.html">Distributed Graph</a>. The graph
type must also model the <a class="reference external" href="path_to_url">Incidence Graph</a>.</dd>
</dl>
<p>IN: <tt class="docutils literal"><span class="pre">vertex_descriptor</span> <span class="pre">s</span></tt></p>
<p>IN: <tt class="docutils literal"><span class="pre">vertex_descriptor</span> <span class="pre">t</span></tt></p>
<dl class="docutils">
<dt>UTIL/OUT: <tt class="docutils literal"><span class="pre">color_map(ColorMap</span> <span class="pre">color)</span></tt></dt>
<dd>The color map must be a <a class="reference external" href="distributed_property_map.html">Distributed Property Map</a> with the same
process group as the graph <tt class="docutils literal"><span class="pre">g</span></tt> whose colors must monotonically
darken (white -> gray/green -> black). The default value is a
distributed <tt class="docutils literal"><span class="pre">two_bit_color_map</span></tt>.</dd>
<dt>IN: <tt class="docutils literal"><span class="pre">OwnerMap</span> <span class="pre">owner</span></tt></dt>
<dd>The owner map must map from vertices to the process that owns them
as described in the <a class="reference external" href="GlobalDescriptor.html">GlobalDescriptor</a> concept.</dd>
<dt>OUT: <tt class="docutils literal"><span class="pre">bool</span></tt></dt>
<dd>The algorithm returns <tt class="docutils literal"><span class="pre">true</span></tt> if a path from <tt class="docutils literal"><span class="pre">s</span></tt> to <tt class="docutils literal"><span class="pre">t</span></tt> is
found, and false otherwise.</dd>
</dl>
</div>
<div class="section" id="complexity">
<h1><a class="toc-backref" href="#id3">Complexity</a></h1>
<p>This algorithm performs <em>O(V + E)</em> work in <em>d/2 + 1</em> BSP supersteps,
where <em>d</em> is the shortest distance from <tt class="docutils literal"><span class="pre">s</span></tt> to <tt class="docutils literal"><span class="pre">t</span></tt>. Over all
supersteps, <em>O(E)</em> messages of constant size will be transmitted.</p>
</div>
<div class="section" id="algorithm-description">
<h1><a class="toc-backref" href="#id4">Algorithm Description</a></h1>
<p>The algorithm consists of two simultaneous breadth-first traversals
from <tt class="docutils literal"><span class="pre">s</span></tt> and <tt class="docutils literal"><span class="pre">t</span></tt> respectively. The algorithm utilizes a single
queue for both traversals with the traversal from <tt class="docutils literal"><span class="pre">s</span></tt> being denoted
by a <tt class="docutils literal"><span class="pre">gray</span></tt> entry in the color map and the traversal from <tt class="docutils literal"><span class="pre">t</span></tt>
being denoted by a <tt class="docutils literal"><span class="pre">green</span></tt> entry. The traversal method is similar
to breadth-first search except that no visitor event points are
called. When any process detects a collision in the two traversals
(by attempting to set a <tt class="docutils literal"><span class="pre">gray</span></tt> vertex to <tt class="docutils literal"><span class="pre">green</span></tt> or vice-versa),
it signals all processes to terminate on the next superstep and all
processes return <tt class="docutils literal"><span class="pre">true</span></tt>. If the queues on all processes are empty
and no collision is detected then all processes terminate and return
<tt class="docutils literal"><span class="pre">false</span></tt>.</p>
<hr class="docutils" />
<p>Authors: Nick Edmonds and Andrew Lumsdaine</p>
</div>
</div>
<div class="footer">
<hr class="footer" />
Generated on: 2009-05-31 00:21 UTC.
Generated by <a class="reference external" href="path_to_url">Docutils</a> from <a class="reference external" href="path_to_url">reStructuredText</a> source.
</div>
</body>
</html>
```
|
```java
// 2017 and later: Unicode, Inc. and others.
package com.ibm.icu.impl.number.parse;
import com.ibm.icu.impl.StringSegment;
/**
* The core interface implemented by all matchers used for number parsing.
*
* Given a string, there should NOT be more than one way to consume the string with the same matcher
* applied multiple times. If there is, the non-greedy parsing algorithm will be unhappy and may enter an
* exponential-time loop. For example, consider the "A Matcher" that accepts "any number of As". Given
* the string "AAAA", there are 2^N = 8 ways to apply the A Matcher to this string: you could have the A
* Matcher apply 4 times to each character; you could have it apply just once to all the characters; you
* could have it apply to the first 2 characters and the second 2 characters; and so on. A better version
* of the "A Matcher" would be for it to accept exactly one A, and allow the algorithm to run it
* repeatedly to consume a string of multiple As. The A Matcher can implement the Flexible interface
* below to signal that it can be applied multiple times in a row.
*
* @author sffc
*/
public interface NumberParseMatcher {
/**
* Matchers can implement the Flexible interface to indicate that they are optional and can be run
* repeatedly. Used by SeriesMatcher, primarily in the context of IgnorablesMatcher.
*/
public interface Flexible {
}
/**
* Runs this matcher starting at the beginning of the given StringSegment. If this matcher finds
* something interesting in the StringSegment, it should update the offset of the StringSegment
* corresponding to how many chars were matched.
*
* @param segment
* The StringSegment to match against. Matches always start at the beginning of the
* segment. The segment is guaranteed to contain at least one char.
* @param result
* The data structure to store results if the match succeeds.
* @return Whether this matcher thinks there may be more interesting chars beyond the end of the
* string segment.
*/
public boolean match(StringSegment segment, ParsedNumber result);
/**
* Performs a fast "smoke check" for whether or not this matcher could possibly match against the
* given string segment. The test should be as fast as possible but also as restrictive as possible.
* For example, matchers can maintain a UnicodeSet of all code points that count possibly start a
* match. Matchers should use the {@link StringSegment#startsWith} method in order to correctly
* handle case folding.
*
* @param segment
* The segment to check against.
* @return true if the matcher might be able to match against this segment; false if it definitely
* will not be able to match.
*/
public boolean smokeTest(StringSegment segment);
/**
* Method called at the end of a parse, after all matchers have failed to consume any more chars.
* Allows a matcher to make final modifications to the result given the knowledge that no more
* matches are possible.
*
* @param result
* The data structure to store results.
*/
public void postProcess(ParsedNumber result);
}
```
|
```php
<?php
/*
* This file is part of Piplin.
*
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterHooksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('hooks', function (Blueprint $table) {
$table->renameColumn('on_deployment_success', 'on_task_success');
});
Schema::table('hooks', function (Blueprint $table) {
$table->renameColumn('on_deployment_failure', 'on_task_failure');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('hooks', function (Blueprint $table) {
$table->renameColumn('on_task_success', 'on_deployment_success');
});
Schema::table('hooks', function (Blueprint $table) {
$table->renameColumn('on_task_failure', 'on_deployment_failure');
});
}
}
```
|
Shadows of the Past is the debut album by the Finnish metal band Sentenced. It was released in 1991 and reissued by Century Media in 1995, including the Journey to Pohjola demo. It was reissued again in 2001 with North from Here and again in 2008 as a two-CD set along with their first two demos.
Shadows of the Past features more prominent death metal elements than would be present later in their career. On the introduction speech of North from Here 2008 re-release, Jarva states that at the time of Shadows of the Past the band was just a "Death clone" amongst others, so the band chose to pursue a more technical and personal-sounding direction on their second album.
The album has had three different covers: the original release drawn by Luxi Lahtinen, the Century Media 1995 reissue drawn by Taneli Jarva, and the 2008 reissue which is a reproduction of a medieval woodcut print. This version also includes an insert featuring the first two covers.
Track listing
1995 reissue bonus tracks
2008 reissue bonus disc
When Death Joins Us (demo 1990)
"Hallucinations" – 2:20
"When Death Joins Us" – 4:54
"Shadows of the Past" – 4:24
"Obscurity ..." – 5:10
"Desperationed Future" – 4:29
Rotting Ways to Misery (demo 1991)
"Rotting Ways to Misery" – 5:42
"Disengagement" – 6:18
"Suffocated Beginning of Life" – 6:15
"Under the Suffer" – 5:16
"Descending Curtain of Death" – 5:34
"The Truth" – 5:28
Credits
Miika Tenkula – lead guitar, vocals
Sami Lopakka – guitar
Taneli Jarva – bass
Vesa Ranta – drums
References
Sentenced albums
1991 debut albums
|
A Tour For Me + You was the third concert tour by American singer Austin Mahone in support of his second mixtape, ForMe+You. The tour began in Fort Lauderdale, and concluded in Los Angeles.
Background and development
Following the release of ForMe+You, Mahone announced he would be embarking on his third headlining concert tour, visiting 22 cities around North America.
Shows
References
2017 concert tours
|
```java
/**
*
* path_to_url
*
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package com.linkedin.xinfra.monitor.consumer;
import java.util.Map;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.consumer.OffsetCommitCallback;
import org.apache.kafka.common.TopicPartition;
/**
* A base consumer used to abstract different consumer classes.
*
* Implementations of this class must have constructor with the following signature:
* Constructor({@link java.util.Properties} properties).
*/
public interface KMBaseConsumer {
BaseConsumerRecord receive() throws Exception;
void commitAsync();
void commitAsync(final Map<TopicPartition, OffsetAndMetadata> offsets, OffsetCommitCallback callback);
void commitAsync(OffsetCommitCallback callback);
OffsetAndMetadata committed(TopicPartition tp);
void close();
long lastCommitted();
void updateLastCommit();
}
```
|
Alfred Thompson Adams (January 8, 1898 – December 4, 1982) was an attorney and an American football and basketball player and coach. He played for the Vanderbilt Commodores of Vanderbilt University.
Early years
Alfred Thompson Adams was born on January 8, 1898, in Nashville, Tennessee, to Adams Gillespie Adams, II and Sue Howell. He was the sixth son, and his father died early in Adams' life.
Vanderbilt University
At Vanderbilt he was a member of the Phi Delta Theta fraternity. He graduated with a B. S in 1918 and an LL.B from Vanderbilt Law School in 1921.
Football
Adams was a prominent member of Dan McGugin's Vanderbilt Commodores football teams. Adams was selected as an All-Southern end in 1917 and 1919.
1917
He was captain of the 1917 football team, the last non-senior to be such until 2003. Adams was selected All-Southern in 1917, a season which featured the south's first national champion in Georgia Tech. Tech gave Vandy its worst ever loss, 83 to 0. Adams praised Tech: "Tech's magnificent machine won easily over Vanderbilt. It was simply the matter of a splendid eleven winning over an unseasoned, inexperienced team. "Tech played hard, clean football, and we were somewhat surprised to meet such a fair, aggressive team, after the reports we had heard. I think that Vanderbilt could have broken that Tech shift if we had had last year's eleven. Being outweighed, Vanderbilt could not check the heavy forwards, or open up the line. Thereby hangs the tale."
Basketball
1919–1920
Adams played on the 1920 SIAA championship team with the likes of Josh Cody and Tom Zerfoss.
High school football
In 1920 he coached the Hume-Fogg High School football team.
Legal career
Following his passing the bar, Adams entered practice with his uncle R. B. C. Howell and former Vandy quarterback Myles P. O'Connor.
External links
Oral history interview with Judge Alfred Thompson Adams
References
1898 births
1982 deaths
All-Southern college football players
American football ends
Guards (basketball)
Vanderbilt Commodores football players
Vanderbilt Commodores men's basketball players
Players of American football from Nashville, Tennessee
Basketball players from Nashville, Tennessee
Vanderbilt University Law School alumni
20th-century American judges
American men's basketball players
|
In the area of mathematics called combinatorial group theory, the Schreier coset graph is a graph associated with a group G, a generating set S={si : i in I } of G, and a subgroup H ≤ G. The Schreier graph encodes the abstract structure of a group modulo an equivalence relation formed by the coset.
The graph is named after Otto Schreier, who used the term “Nebengruppenbild”. An equivalent definition was made in an early paper of Todd and Coxeter.
Description
The Schreier graph of a group G, a subgroup H, and a generating set S⊆G is denoted by Sch(G,H,S) or Sch(H\G,S). Its vertices are the right cosets Hg = {hg : h in H } for g in G, and its edges are of the form (Hg, Hgs) for g in G and s in S.
More generally, if X is a G-set, the Schreier graph of the action of G on X (with respect to S⊆G) is denoted by Sch(G,X,S) or Sch(X,S). Its vertices are the elements of X, and its edges are of the form (x,xs) for x in X and s in S. This includes the original Schreier coset graph definition, as H\G is a naturally a G-set with respect to multiplication from the right. From an algebraic-topological perspective, the graph Sch(X,S) has no distinguished vertex, whereas Sch(G,H,S) has the distinguished vertex H, and is thus a pointed graph.
The Cayley graph of the group G itself is the Schreier coset graph for H = {1G} .
A spanning tree of a Schreier coset graph corresponds to a Schreier transversal, as in Schreier's subgroup lemma .
The book "Categories and Groupoids" listed below relates this to the theory of covering morphisms of groupoids. A subgroup H of a group G determines a covering morphism of groupoids and if S is a generating set for G then its inverse image under p is the Schreier graph of (G, S).
Applications
The graph is useful to understand coset enumeration and the Todd–Coxeter algorithm.
Coset graphs can be used to form large permutation representations of groups and were used by Graham Higman to show that the alternating groups of large enough degree are Hurwitz groups, .
Stallings' core graphs are retracts of Schreier graphs of free groups, and are an essential tool for computing with subgroups of a free group.
Every vertex-transitive graph is a coset graph.
References
Schreier graphs of the Basilica group Authors: Daniele D'Angeli, Alfredo Donno, Michel Matter, Tatiana Nagnibeda
Philip J. Higgins, Categories and Groupoids, van Nostrand, New York, Lecture Notes, 1971, Republished as TAC Reprint, 2005
Combinatorial group theory
|
Honokaa High & Intermediate School is a public, co-educational high school and middle school of the Hawaii State Department of Education. It serves grades seven through twelve and was established in 1889. It was added to the Hawaiʻi Register of Historic Places in 2002 under its former name, Honokaa High & Elementary School.
General information
Honokaa High & Intermediate School is located in Honokaa in Hawaii County on the Island of Hawaii. The campus is at coordinates , 45-527 Pakalana Street, on both the same side, and across the street from Honokaa Elementary School, one of its three feeder schools. The others are Waimea Middle School and Paauilo Intermediate School. The mascot is the Dragon and its school colors are green and gold.
History
Honokaa School was started in 1889 for students from the Hamakua Coastal Sugar Cane Communities and children of Parker Ranch workers. The high school was established a few years later. The weak public interest eventually grew stronger as the public realized the benefits from a high school on the Hamakua Coast of the Big Island.
The school, originally known as Honokaa High & Elementary, was located at its original location on the eastern side of Pakalana Street, and in 1957 was expanded to include new elementary school buildings and a cafeteria on the western side of Pakalana Street. In the early 2000s, the school was broken up into Honokaa High & Intermediate School and Honokaa Elementary School. Honokaa High & Intermediate School's rival is Kohala High School.
Alma Mater
Beneath the calm blue azure skies,
Our Alma Mater lies.
The glorious creed we onward bare,
We will fail thee never.
To highest goals we forward march,
With never failing vigor.
We're first and last and always for,
The green and gold forever.
The green and gold our colors dear,
The green and gold forever.
We're one and all and always for,
The green and gold forever!
Clubs
Honokaa High & Intermediate School supports clubs that include:
Academic Decathlon
National Honors Society
Fishing Club
Future Farmers of America
Robotics
Science Club
Student Body Government
Notable alumni
Nelson Doi (1922–2015), former Hawai'i Lieutenant Governor and State Senator
Kaulana Noa (born 1976), former American football offensive guard drafted by the St. Louis Rams in the 2000 NFL Draft.
Poncie Ponce (born 1933), actor, musician and stand-up comedian
Dwight Takamine (born 1953), former Hawai'i State Representative and Senator
Yoshito Takamine (1924–2015), former Hawai'i State Representative and labor leader
John David Waiheʻe III (born 1946), fourth Governor of Hawaiʻi from 1986 to 1994
References
External links
Honoka'a High & Intermediate School Official Website
Educational institutions established in 1889
Public high schools in Hawaii County, Hawaii
Public schools in Hawaii County, Hawaii
Middle schools in Hawaii County, Hawaii
Public middle schools in Hawaii
1889 establishments in Hawaii
Hawaii Register of Historic Places in Hawaii County, Hawaii
|
God Loves Ugly is the second studio album by American hip hop group Atmosphere. It was released on Rhymesayers Entertainment on June 11, 2002.
Release
The album, via distribution with Fat Beats, went on to sell more than 130,000 copies in the United States. The single from the album, titled "Modern Man's Hustle", reached #18 on the Billboard Hot Rap Tracks chart.
On January 20, 2009, God Loves Ugly was re-released with a bonus DVD, featuring cameos from Eyedea, Aesop Rock and Crescent Moon, among others. Originally released as Sad Clown Bad Dub 4, the DVD features two hours of live performance footage, special guest appearances, and music videos for "GodLovesUgly", "Summer Song", and "Say Shh".
Reception and legacy
At Metacritic, which assigns a weighted average score out of 100 to reviews from mainstream critics, God Loves Ugly received an average score of 76% based on 9 reviews, indicating "generally favorable reviews".
In 2011, "Modern Man's Hustle" ranked at number 6 on Complexs "25 Best Rhymesayers Songs" list.
In 2015, God Loves Ugly was listed by HipHopDX as one of the "30 Best Underground Hip Hop Albums Since 2000".
Track listing
Personnel
Ant – Production
Slug – Vocals
Mankwe Ndosi – vocal accompaniment on "GodLovesUgly" and "Shrapnel"
George Faber – harmonica help on "Give Me"
Sara Lindsay – vocal accompaniment on "Fuck You Lucy"
Sara Schrantz – vocal accompaniment on "Fuck You Lucy"
Charts
References
External links
2002 albums
Atmosphere (music group) albums
Rhymesayers Entertainment albums
|
```objective-c
/* -*- mode:C; c-file-style: "bsd" -*- */
/*****************************************************************************************
** **
** Y K D E F - Common Yubikey project header **
** **
** Date / Rev / Sign / Remark **
** 06-06-03 / 0.9.0 / J E / Main **
** 06-08-25 / 1.0.0 / J E / Rewritten for final spec **
** 08-06-03 / 1.3.0 / J E / Added static OTP feature **
** 09-06-02 / 2.0.0 / J E / Added version 2 flags **
** 09-09-23 / 2.1.0 / J E / Added version 2.1 flags (OATH-HOTP) **
** 10-05-01 / 2.2.0 / J E / Added support for 2.2 ext. + frame **
** 11-04-15 / 2.3.0 / J E / Added support for 2.3 extensions **
** 11-12-05 / 2.4.0 / J E / Added support for NFC and NDEF **
** 12-10-28 / 3.0.0 / J E / NEO changes **
** 13-03-05 / 3.1.0 / J E / Added EXTFLAG_LED_INV flag **
** 13-03-06 / 3.1.0 / J E / Added NEO startup busy flag **
** 14-06-13 / 3.3.0 / J E / Added U2F mode modifiers **
** 14-11-20 / 4.0.0 / J E / Updated with Yubikey 4 PIDs **
** 15-03-27 / 4.1.0 / K L / Added YK4 Capabilities **
** 15-06-23 / 4.2.0 / K L / Added more YK4 Capabilities **
** **
*****************************************************************************************/
#ifndef __YKDEF_H_INCLUDED__
#define __YKDEF_H_INCLUDED__
/* We need the structures defined here to be packed byte-wise */
#if defined(_WIN32) || defined(__GNUC__)
#pragma pack(push, 1)
#endif
/* Slot entries */
#define SLOT_CONFIG 1 /* First (default / V1) configuration */
#define SLOT_NAV 2 /* V1 only */
#define SLOT_CONFIG2 3 /* Second (V2) configuration */
#define SLOT_UPDATE1 4 /* Update slot 1 */
#define SLOT_UPDATE2 5 /* Update slot 2 */
#define SLOT_SWAP 6 /* Swap slot 1 and 2 */
#define SLOT_NDEF 8 /* Write NDEF record */
#define SLOT_NDEF2 9 /* Write NDEF record for slot 2 */
#define SLOT_DEVICE_SERIAL 0x10 /* Device serial number */
#define SLOT_DEVICE_CONFIG 0x11 /* Write device configuration record */
#define SLOT_SCAN_MAP 0x12 /* Write scancode map */
#define SLOT_YK4_CAPABILITIES 0x13 /* Read YK4 capabilities (device info) list */
#define SLOT_YK4_SET_DEVICE_INFO 0x15 /* Write device info */
#define SLOT_CHAL_OTP1 0x20 /* Write 6 byte challenge to slot 1, get Yubico OTP response */
#define SLOT_CHAL_OTP2 0x28 /* Write 6 byte challenge to slot 2, get Yubico OTP response */
#define SLOT_CHAL_HMAC1 0x30 /* Write 64 byte challenge to slot 1, get HMAC-SHA1 response */
#define SLOT_CHAL_HMAC2 0x38 /* Write 64 byte challenge to slot 2, get HMAC-SHA1 response */
#define RESP_ITEM_MASK 0x07 /* Mask for slice item # in responses */
#define RESP_TIMEOUT_WAIT_MASK 0x1f /* Mask to get timeout value */
#define RESP_TIMEOUT_WAIT_FLAG 0x20 /* Waiting for timeout operation - seconds left in lower 5 bits */
#define RESP_PENDING_FLAG 0x40 /* Response pending flag */
#define SLOT_WRITE_FLAG 0x80 /* Write flag - set by app - cleared by device */
#define DUMMY_REPORT_WRITE 0x8f /* Write a dummy report to force update or abort */
#define NEO_STARTUP_BUSY 0x9f /* Status during startup (writes blocked) */
#define SHA1_MAX_BLOCK_SIZE 64 /* Max size of input SHA1 block */
#define SHA1_DIGEST_SIZE 20 /* Size of SHA1 digest = 160 bits */
#define SERIAL_NUMBER_SIZE 4 /* Size of device serial number */
/* Frame structure */
#define SLOT_DATA_SIZE 64
struct frame_st {
unsigned char payload[SLOT_DATA_SIZE]; /* Frame payload */
unsigned char slot; /* Slot # field */
unsigned short crc; /* CRC field */
unsigned char filler[3]; /* Filler */
};
/* Ticket structure */
#define UID_SIZE 6 /* Size of secret ID field */
struct ticket_st {
unsigned char uid[UID_SIZE]; /* Unique (secret) ID */
unsigned short useCtr; /* Use counter (incremented by 1 at first use after power up) + usage flag in msb */
unsigned short tstpl; /* Timestamp incremented by approx 8Hz (low part) */
unsigned char tstph; /* Timestamp (high part) */
unsigned char sessionCtr; /* Number of times used within session. 0 for first use. After it wraps from 0xff to 1 */
unsigned short rnd; /* Pseudo-random value */
unsigned short crc; /* CRC16 value of all fields */
};
/* Activation modifier of sessionUse field (bitfields not uses as they are not portable) */
#define TICKET_ACT_HIDRPT 0x8000 /* Ticket generated at activation by keyboard (scroll/num/caps) */
#define TICKET_CTR_MASK 0x7fff /* Mask for useCtr value (except HID flag) */
/* Configuration structure */
#define FIXED_SIZE 16 /* Max size of fixed field */
#define KEY_SIZE 16 /* Size of AES key */
#define KEY_SIZE_OATH 20 /* Size of OATH-HOTP key (key field + first 4 of UID field) */
#define ACC_CODE_SIZE 6 /* Size of access code to re-program device */
struct config_st {
unsigned char fixed[FIXED_SIZE];/* Fixed data in binary format */
unsigned char uid[UID_SIZE]; /* Fixed UID part of ticket */
unsigned char key[KEY_SIZE]; /* AES key */
unsigned char accCode[ACC_CODE_SIZE]; /* Access code to re-program device */
unsigned char fixedSize; /* Number of bytes in fixed field (0 if not used) */
unsigned char extFlags; /* Extended flags - YubiKey 2.? and above */
unsigned char tktFlags; /* Ticket configuration flags */
unsigned char cfgFlags; /* General configuration flags */
unsigned char rfu[2]; /* Reserved for future use */
unsigned short crc; /* CRC16 value of all fields */
};
/* Ticket flags **************************************************************/
/* Yubikey 1 and above */
#define TKTFLAG_TAB_FIRST 0x01 /* Send TAB before first part */
#define TKTFLAG_APPEND_TAB1 0x02 /* Send TAB after first part */
#define TKTFLAG_APPEND_TAB2 0x04 /* Send TAB after second part */
#define TKTFLAG_APPEND_DELAY1 0x08 /* Add 0.5s delay after first part */
#define TKTFLAG_APPEND_DELAY2 0x10 /* Add 0.5s delay after second part */
#define TKTFLAG_APPEND_CR 0x20 /* Append CR as final character */
/* Yubikey 2 and above */
#define TKTFLAG_PROTECT_CFG2 0x80 /* Block update of config 2 unless config 2 is configured and has this bit set */
/* Configuration flags *******************************************************/
/* Yubikey 1 and above */
#define CFGFLAG_SEND_REF 0x01 /* Send reference string (0..F) before data */
#define CFGFLAG_PACING_10MS 0x04 /* Add 10ms intra-key pacing */
#define CFGFLAG_PACING_20MS 0x08 /* Add 20ms intra-key pacing */
#define CFGFLAG_STATIC_TICKET 0x20 /* Static ticket generation */
/* Yubikey 1 only */
#define CFGFLAG_TICKET_FIRST 0x02 /* Send ticket first (default is fixed part) */
#define CFGFLAG_ALLOW_HIDTRIG 0x10 /* Allow trigger through HID/keyboard */
/* Yubikey 2 and above */
#define CFGFLAG_SHORT_TICKET 0x02 /* Send truncated ticket (half length) */
#define CFGFLAG_STRONG_PW1 0x10 /* Strong password policy flag #1 (mixed case) */
#define CFGFLAG_STRONG_PW2 0x40 /* Strong password policy flag #2 (substitute 0..7 to digits) */
#define CFGFLAG_MAN_UPDATE 0x80 /* Allow manual (local) update of static OTP */
/* Yubikey 2.1 and above */
#define TKTFLAG_OATH_HOTP 0x40 /* OATH HOTP mode */
#define CFGFLAG_OATH_HOTP8 0x02 /* Generate 8 digits HOTP rather than 6 digits */
#define CFGFLAG_OATH_FIXED_MODHEX1 0x10 /* First byte in fixed part sent as modhex */
#define CFGFLAG_OATH_FIXED_MODHEX2 0x40 /* First two bytes in fixed part sent as modhex */
#define CFGFLAG_OATH_FIXED_MODHEX 0x50 /* Fixed part sent as modhex */
#define CFGFLAG_OATH_FIXED_MASK 0x50 /* Mask to get out fixed flags */
/* Yubikey 2.2 and above */
#define TKTFLAG_CHAL_RESP 0x40 /* Challenge-response enabled (both must be set) */
#define CFGFLAG_CHAL_YUBICO 0x20 /* Challenge-response enabled - Yubico OTP mode */
#define CFGFLAG_CHAL_HMAC 0x22 /* Challenge-response enabled - HMAC-SHA1 */
#define CFGFLAG_HMAC_LT64 0x04 /* Set when HMAC message is less than 64 bytes */
#define CFGFLAG_CHAL_BTN_TRIG 0x08 /* Challenge-response operation requires button press */
#define EXTFLAG_SERIAL_BTN_VISIBLE 0x01 /* Serial number visible at startup (button press) */
#define EXTFLAG_SERIAL_USB_VISIBLE 0x02 /* Serial number visible in USB iSerial field */
#define EXTFLAG_SERIAL_API_VISIBLE 0x04 /* Serial number visible via API call */
/* V2.3 flags only */
#define EXTFLAG_USE_NUMERIC_KEYPAD 0x08 /* Use numeric keypad for digits */
#define EXTFLAG_FAST_TRIG 0x10 /* Use fast trig if only cfg1 set */
#define EXTFLAG_ALLOW_UPDATE 0x20 /* Allow update of existing configuration (selected flags + access code) */
#define EXTFLAG_DORMANT 0x40 /* Dormant configuration (can be woken up and flag removed = requires update flag) */
/* V2.4/3.1 flags only */
#define EXTFLAG_LED_INV 0x80 /* LED idle state is off rather than on */
/* Flags valid for update */
#define TKTFLAG_UPDATE_MASK (TKTFLAG_TAB_FIRST | TKTFLAG_APPEND_TAB1 | TKTFLAG_APPEND_TAB2 | TKTFLAG_APPEND_DELAY1 | TKTFLAG_APPEND_DELAY2 | TKTFLAG_APPEND_CR)
#define CFGFLAG_UPDATE_MASK (CFGFLAG_PACING_10MS | CFGFLAG_PACING_20MS)
#define EXTFLAG_UPDATE_MASK (EXTFLAG_SERIAL_BTN_VISIBLE | EXTFLAG_SERIAL_USB_VISIBLE | EXTFLAG_SERIAL_API_VISIBLE | EXTFLAG_USE_NUMERIC_KEYPAD | EXTFLAG_FAST_TRIG | EXTFLAG_ALLOW_UPDATE | EXTFLAG_DORMANT | EXTFLAG_LED_INV)
/* NDEF structure */
#define NDEF_DATA_SIZE 54
/* backwards compatibility with version 1.7.0 */
typedef struct ndef_st YKNDEF;
struct ndef_st {
unsigned char len; /* Payload length */
unsigned char type; /* NDEF type specifier */
unsigned char data[NDEF_DATA_SIZE]; /* Payload size */
unsigned char curAccCode[ACC_CODE_SIZE]; /* Access code */
};
/* Navigation */
/* NOTE: Navigation isn't available since Yubikey 1.3.5 and is strongly
discouraged. */
#define MAX_URL 48
struct nav_st {
unsigned char scancode[MAX_URL];/* Scancode (lower 7 bits) */
unsigned char scanmod[MAX_URL >> 2]; /* Modifier fields (packed 2 bits each) */
unsigned char flags; /* NAVFLAG_xxx flags */
unsigned char filler; /* Filler byte */
unsigned short crc; /* CRC16 value of all fields */
};
#define SCANMOD_SHIFT 0x80 /* Highest bit in scancode */
#define SCANMOD_ALT_GR 0x01 /* Lowest bit in mod */
#define SCANMOD_WIN 0x02 /* WIN key */
/* Navigation flags */
#define NAVFLAG_INSERT_TRIG 0x01 /* Automatic trigger when device is inserted */
#define NAVFLAG_APPEND_TKT 0x02 /* Append ticket to URL */
#define NAVFLAG_DUAL_KEY_USAGE 0x04 /* Dual usage of key: Short = ticket Long = Navigate */
/* Device configuration block (version 3.0) */
struct device_config_st {
unsigned char mode; /* Device mode */
unsigned char crTimeout; /* Challenge-response timeout in seconds */
unsigned short autoEjectTime; /* Auto eject time in x10 seconds */
};
#define MODE_OTP 0x00 /* OTP only */
#define MODE_CCID 0x01 /* CCID only, no eject */
#define MODE_OTP_CCID 0x02 /* OTP + CCID composite */
#define MODE_U2F 0x03 /* U2F mode */
#define MODE_OTP_U2F 0x04 /* OTP + U2F composite */
#define MODE_U2F_CCID 0x05 /* U2F + CCID composite */
#define MODE_OTP_U2F_CCID 0x06 /* OTP + U2F + CCID composite */
#define MODE_MASK 0x07 /* Mask for mode bits */
#define MODE_FLAG_EJECT 0x80 /* CCID device supports eject (mode 1 only) */
#define DEFAULT_CHAL_TIMEOUT 15 /* Default challenge timeout in seconds */
/* Scancode mapping (version 3.0) */
#define SCAN_MAP "cbdefghijklnrtuvCBDEFGHIJKLNRTUV0123456789!\t\r"
#define SHIFT_FLAG 0x80 /* Flag for shifted scan codes */
/* Status block */
struct status_st {
unsigned char versionMajor; /* Firmware version information */
unsigned char versionMinor;
unsigned char versionBuild;
unsigned char pgmSeq; /* Programming sequence number. 0 if no valid configuration */
unsigned short touchLevel; /* Level from touch detector */
};
#define CONFIG1_VALID 0x01 /* Bit in touchLevel indicating that configuration 1 is valid (from firmware 2.1) */
#define CONFIG2_VALID 0x02 /* Bit in touchLevel indicating that configuration 2 is valid (from firmware 2.1) */
#define CONFIG1_TOUCH 0x04 /* Bit in touchLevel indicating that configuration 1 requires touch (from firmware 3.0) */
#define CONFIG2_TOUCH 0x08 /* Bit in touchLevel indicating that configuration 2 requires touch (from firmware 3.0) */
#define CONFIG_LED_INV 0x10 /* Bit in touchLevel indicating that LED behavior is inverted (EXTFLAG_LED_INV mirror) */
#define CONFIG_STATUS_MASK 0x1f /* Mask for status bits */
/* Modified hex string mapping */
#define MODHEX_MAP "cbdefghijklnrtuv"
/* USB vendor ID (VID) and product ID (PID) mapping */
#define YUBICO_VID 0x1050 /* Global vendor ID */
#define YUBIKEY_PID 0x0010 /* Yubikey (version 1 and 2) */
#define NEO_OTP_PID 0x0110 /* Yubikey NEO - OTP only */
#define NEO_OTP_CCID_PID 0x0111 /* Yubikey NEO - OTP and CCID */
#define NEO_CCID_PID 0x0112 /* Yubikey NEO - CCID only */
#define NEO_U2F_PID 0x0113 /* Yubikey NEO - U2F only */
#define NEO_OTP_U2F_PID 0x0114 /* Yubikey NEO - OTP and U2F */
#define NEO_U2F_CCID_PID 0x0115 /* Yubikey NEO - U2F and CCID */
#define NEO_OTP_U2F_CCID_PID 0x0116 /* Yubikey NEO - OTP, U2F and CCID */
#define YK4_OTP_PID 0x0401 /* Yubikey 4 - OTP only */
#define YK4_U2F_PID 0x0402 /* Yubikey 4 - U2F only */
#define YK4_OTP_U2F_PID 0x0403 /* Yubikey 4 - OTP and U2F */
#define YK4_CCID_PID 0x0404 /* Yubikey 4 - CCID only */
#define YK4_OTP_CCID_PID 0x0405 /* Yubikey 4 - OTP and CCID */
#define YK4_U2F_CCID_PID 0x0406 /* Yubikey 4 - U2F and CCID */
#define YK4_OTP_U2F_CCID_PID 0x0407 /* Yubikey 4 - OTP, U2F and CCID */
#define PLUS_U2F_OTP_PID 0x0410 /* Yubikey plus - OTP+U2F */
#define ONLYKEY_VID 0x1d50
#define ONLYKEY_PID 0x60fc
#define YK4_CAPA_TAG 0x01 /* TAG for capabilities */
#define YK4_SERIAL_TAG 0x02 /* TAG for serial number */
#define YK4_CAPA1_OTP 0x01 /* Capability bit for OTP functionality */
#define YK4_CAPA1_U2F 0x02 /* Capability bit for U2F functionality */
#define YK4_CAPA1_CCID 0x04 /* Capability bit for CCID functionality */
#define YK4_CAPA1_OPGP 0x08 /* Capability bit for OpenPGP functionality */
#define YK4_CAPA1_PIV 0x10 /* Capability bit for PIV functionality */
#define YK4_CAPA1_OATH 0x20 /* Capability bit for OATH functionality */
#if defined(_WIN32) || defined(__GNUC__)
#pragma pack(pop)
#endif
#endif /* __YKDEF_H_INCLUDED__ */
```
|
Alexander John Waits (born June 21, 1968) is a former American football punter who played for the Seattle Seahawks of the National Football League (NFL). He played college football at University of Texas.
References
Living people
1968 births
American football punters
Texas Longhorns football players
Seattle Seahawks players
|
Silver Springs State Fish and Wildlife Area is an Illinois state park on in Kendall County, Illinois, United States. The park was established in the late 1960s and is named for the natural spring within its boundaries. The park has two artificial lakes and the Fox River flows through the northern end of the park. Silver Springs hosts a variety of activities including fishing, hunting, boating and hiking. The park has areas of native prairie restoration, a sledding hill and a seven-mile (11 km) equestrian trail. The prairie restoration areas hold many species of plants including lead plant, and purple coneflower.
Location
The Park is divided by the Fox River, with the northern area situated next to the Farnsworth House, designed by Ludwig Mies van der Rohe. The property that Mrs. Farnsworth bought frames part of the western side of the Park. One of the main access points to the park is a bridge that takes Fox River Drive (Ben Street in Plano), over the river, and to an adjoining road (Fox Road) that runs past the entrance to the park. In the 1960s when the current bridge was being constructed, Mrs. Farnsworth appealed to the Kendall County Board, suggesting a block to the bridge, citing ecological concerns among other things.
History
There is evidence that the Fox River valley near Silver Springs was populated by indigenous people near the end of the last ice age, 10–14,000 years ago. The original tract of land that became Silver Springs State Fish and Wildlife Area was purchased by the state of Illinois in 1969, and has been open since January of that year. The park is located in Kendall County, Illinois, west of the city of Yorkville. Since the original acquisition in 1969, have been added to the park
Silver Springs State Fish and Wildlife Area was one of five new state parks opened in northern Illinois from 1969–1971. As part of more than added to the Illinois state park system during this period, Silver Springs opened to alleviate traffic at other state parks in the area. At the time, the Illinois Department of Natural Resources (IDNR), which oversees the state park system, was attempting to provide the Chicago area with the most state park facilities in Illinois.
The park had nine extant wells tapping the Galena–Platteville Aquifer when the state purchased the property. By 1973 a modern well was drilled, reaching a depth of . The well, located near the park entrance, was drilled by K & K Well Drilling Co. of Mokena, Illinois through black dirt, gravel, clay, and limestone. Upon completion, the well produced about per day during the summer. The well provides the park with water, but the other nine wells remained in use following its completion.
A prairie restoration project began on within Silver Springs in 1980; was added to the restoration project in 1991. The IDNR undertook another prairie restoration in an area within the park, on the north side of the Fox River, in 2002. For the 2002 project, the IDNR removed numerous invasive species from the area including: basswood, ash, maple, and exotic honeysuckle. The non-native exotic honeysuckle species had thrived in the absence of fire through human intervention. These actions were meant to allow native burr and black oak, and shagbark hickory a chance to reproduce.
Bodies of water
Silver Springs State Fish and Wildlife Area covers and includes four distinct bodies of water, two artificial lakes, the Fox River, and Silver Springs. The larger of the two lakes, Loon Lake, covers and has of shoreline. Loon Lake's maximum depth is and it has an average depth of . Loon Lake, sometimes known as Silver Spring Lake, was constructed in 1960 when a lowland area was excavated. The lake's water level is maintained through a small watershed and groundwater seepage. Water quality at Loon Lake was identified as "good" in 1996 by the Illinois Environmental Protection Agency. Beaver Lake, north of Loon Lake, is smaller, covering . It has almost a half mile (800 m) of shoreline and a maximum depth of ; Beaver Lake's average depth is .
The park's name comes from a natural spring located along a trail on the south end of the park. The spring's name is derived from the effect of sunlight on its surface, which makes the pool appear to shimmer like silver. Even through the winter, the bubbling spring never freezes, and plants often poke through snow surrounding the watercress-bordered pool in the coldest months. Three miles of the Fox River, which Silver Springs empties into, flows through the park's north end.
Wildlife
Plant species native to Illinois prairies prior to European settlement are found within the park's prairie restoration. While the plant life varies by season, species observed in the park include: lead plant, purple coneflower, wild bergamot, and purple prairie clover, black-eyed susan, tall coreopsis, compass plant, wild quinine, rattlesnake master, New Jersey tea, big bluestem, switch grass, and Indian grass. Along the park's trail, several species of trees are found. Six species of oak, three species of ash, and basswood, cottonwood, pawpaw, Kentucky coffeetree and hackberry are among the tree species living within the boundaries of Silver Springs.
The Fox River at Silver Springs has numerous species of freshwater fish including, bluegill, crappie, channel catfish, bullhead, carp, muskie and northern pike. The Loon and Beaver Lake fish population is maintained through human stocking. Channel catfish, bass, bluegill and crappie are stocked in both lakes.
Besides its prairie restorations and bodies of water, Silver Springs has areas of deciduous forests, and wetlands, both of which are populated with species of mammals, birds and insects. Bird life observed in the park includes: osprey, great horned owl, eastern screech owl and long-eared owl; bald eagle have been sighted further upstream along the Fox. Reptiles and amphibians are present in the park but are more elusive than other types of animal life.
Activities
When in season, hunting and fishing are two of the park's primary activities; during the fall and winter over are opened to the public for hunting. Pheasant hunting, through a park operated controlled hunting program, is popular at the park. Dove hunting, squirrel hunting, and bow hunting for deer are also permitted with some restrictions. The park has areas set aside for trap shooting, and archery, participants are required to bring their own equipment and restrictions apply. For anglers, Loon Lake is stocked in the spring and fall with rainbow trout and a small one-half acre pond to the east of the lake is stocked annually for children during the National Hunting and Fishing Days, which is marked yearly by events at Silver Springs. The Fox River is open for fishing from both the bank and boats. There are no motor restrictions and a boat launch is available at the park. The Fox River is shallow near the park and boaters are advised to use caution.
Silver Springs State Fish and Wildlife Area has trails for hiking and horseback riding. A short, half mile (800 m) trail leads to Silver Springs near the park's east entrance. A longer, trail follows the course of the Fox River through the park's wooded areas. The equestrian trail is located in the wildlife management area of the park and stretches . A one-mile (1.6 km) path travels through the prairie restoration area as well. During the winter, much of the park's trail system is open to cross-country skiing, and a four-mile (6 km) trail is open to snowmobiling, weather permitting. When ice thickness permits, the lakes are opened to ice skating and ice fishing. Sledding is another popular activity; Toboggan Hill is located inside the park's east entrance.
Notes
State parks of Illinois
Protected areas of Kendall County, Illinois
Springs of Illinois
Protected areas established in 1969
Landforms of Kendall County, Illinois
1969 establishments in Illinois
|
```javascript
// @flow
import type { Styles } from '../types/style'
/**
* CSS to fully cover an area. Can optionally be passed an offset to act as a "padding".
*
* @example
* // Styles as object usage
* const styles = {
* ...cover()
* }
*
* // styled-components usage
* const div = styled.div`
* ${cover()}
* `
*
* // CSS as JS Output
*
* div: {
* 'position': 'absolute',
* 'top': '0',
* 'right: '0',
* 'bottom': '0',
* 'left: '0'
* }
*/
export default function cover(offset?: number | string = 0): Styles {
return {
position: 'absolute',
top: offset,
right: offset,
bottom: offset,
left: offset,
}
}
```
|
The Armenia national under-21 football team is the youth football team of Armenia. The team is based mostly on the young players from the league and competes every two years in order to qualify for the European Under-21 Football Championship. The team played its first match in 1994, Armenia having until 1992 been part of the Soviet Union.
UEFA U-21 record
1978 - 1991: part of Soviet Union
1992 - 1994: did not participate
1996: 6th of 6 in qualification group.
1998: 5th of 5 in qualification group.
2000: 5th of 5 in qualification group.
2002: 5th of 6 in qualification group.
2004: 5th of 5 in qualification group.
2006: 6th of 6 in qualification group.
2007: 2nd of 3 in qualification group.
2009: 4th of 5 in qualification group.
2011: 4th of 6 in qualification group.
2013: 2nd of 5 in qualification group.
2015: 4th of 5 in qualification group.
2017: 6th of 6 in qualification group.
2019: 4th of 6 in qualification group.
Managers
Oganes Zanazanyan
Samvel Petrosyan - From September 1994-
Armen Gyulbudaghyants
Andranik Adamyan
Mihai Stoica - From 2003-August 2004
Vardan Minasyan - From August 2004 – 2007
Varuzhan Sukiasyan
Flemming Serritslev - From July 1, 2009-June 30, 2011
Rafael Nazaryan - From 2011- October 22, 2013
Abraham Khashmanyan - October 22, 2013 - November 30, 2014
Sargis Hovsepyan - December 1, 2014 - June 5, 2015
Artak Oseyan - June 6, 2015 - November 26, 2015
Karen Barseghyan - January 11, 2016 - October 28, 2016
Artur Voskanyan - May 1, 2017 - June 30, 2018
Armen Gyulbudaghyants - July 1, 2018 - October 6, 2018
Antonio Jesus Flores - May 1, 2019 - 2020
Rafael Nazaryan - October 19, 2020 - September 9, 2023
Players
Current squad
Armenian U-21 team will start the training camp on October 8. In the framework of Euro-2025, Armenian U-21 team will play in Armenia.
Match dates: October 13 and 17, 2023
Opposition: Romania and Switzerland
Caps and goals correct as of:''' 17 October 2023, after the match against
Recent call-ups
Players that have been called up within the past 12 months.
UEFA Euro U-21 qualification
2025 UEFA European Under-21 Championship qualification Group H
Standings
See also
Armenia national football team
Armenia national under-19 football team
Armenia national under-17 football team
References
External links
Uefa Under-21 website Contains fixtures and results
European national under-21 association football teams
Youth football in Armenia
Armenia national youth football team
|
The Norman Baronetcy, of Honeyhanger in the Parish of Shottermill in the County of Surrey, is a title in the Baronetage of the United Kingdom. It was created on 22 June 1915 for the journalist and Liberal politician Henry Norman. The second Baronet, Sir Nigel Norman was an Air Commodore in the Auxiliary Air Force (Reserve) and was killed in action in 1943. The third Baronet was high sheriff of Oxfordshire from 1983 to 1984 and a Deputy Lieutenant of the county in 1985.
Priscilla Norman, second wife of the first Baronet, was a socialite and activist.
Norman baronets, of Honeyhanger (1915)
Sir Henry Norman, 1st Baronet (1858–1939)
Sir (Henry) Nigel St. Valery Norman, 2nd Baronet (1897–1943)
Sir Mark Annesley Norman, 3rd Baronet (1927–2013) He was brother to Desmond Norman and Torquil Norman.
Sir Nigel James Norman, 4th Baronet (born 1956)
The heir apparent is the present holder's son Antony Norman (born 1995).
References
Kidd, Charles, Williamson, David (editors). Debrett's Peerage and Baronetage (1990 edition). New York: St Martin's Press, 1990.
Baronetcies in the Baronetage of the United Kingdom
|
```objective-c
#import <Foundation/Foundation.h>
#import "HTTPResponse.h"
@interface HTTPDataResponse : NSObject <HTTPResponse>
{
NSUInteger offset;
NSData *data;
}
- (id)initWithData:(NSData *)data;
@end
```
|
```java
package com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.upload;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;
/**
* RequestBody
* Created by WZG on 2016/10/20.
*/
public class ProgressRequestBody extends RequestBody {
//RequestBody
private RequestBody delegate;
//
private final UploadProgressListener progressListener;
private CountingSink countingSink;
public ProgressRequestBody(RequestBody requestBody, UploadProgressListener progressListener) {
this.delegate = requestBody;
this.progressListener = progressListener;
}
@Override
public MediaType contentType() {
return delegate.contentType();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
countingSink = new CountingSink(sink);
//CountingSinkBufferedSinkwriteTo()
BufferedSink bufferedSink = Okio.buffer(countingSink);
delegate.writeTo(bufferedSink);
bufferedSink.flush();
}
protected final class CountingSink extends ForwardingSink{
private long byteWritten;
public CountingSink(Sink delegate) {
super(delegate);
}
/**
* ,,
* @param source
* @param byteCount
* @throws IOException
*/
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
byteWritten += byteCount;
progressListener.onProgress(byteWritten, contentLength());
}
}
/**
*
* -1
* @return
*/
@Override
public long contentLength(){
try {
return delegate.contentLength();
} catch (IOException e) {
return -1;
}
}
}
```
|
```xml
import * as React from 'react';
import { makeStyles, SwatchPicker, ImageSwatch } from '@fluentui/react-components';
import type { SwatchPickerOnSelectEventHandler } from '@fluentui/react-components';
const useStyles = makeStyles({
example: {
width: '100%',
height: '466px',
backgroundSize: 'contain',
backgroundRepeat: 'no-repeat',
margin: '20px 0',
},
swatch: {
width: '100px',
height: '100px',
'@media (max-width: 768px)': {
width: '50px',
height: '50px',
},
},
});
const DEFAULT_IMAGE = 'path_to_url
const images = [
{
swatchSrc: 'path_to_url
value: '0',
label: 'sea',
fullImageSrc: 'path_to_url
},
{
swatchSrc: 'path_to_url
value: '1',
label: 'bridge',
fullImageSrc: 'path_to_url
},
{
swatchSrc: 'path_to_url
value: '2',
label: 'park',
fullImageSrc: 'path_to_url
},
];
export const SwatchPickerImage = () => {
const [selectedValue, setSelectedValue] = React.useState('1');
const [selectedImage, setSelectedImage] = React.useState(DEFAULT_IMAGE);
const handleSelect: SwatchPickerOnSelectEventHandler = (_, data) => {
setSelectedValue(data.selectedValue);
const image = images.find(img => img.value === data.selectedValue) || images[0];
setSelectedImage(image.fullImageSrc);
};
const styles = useStyles();
return (
<>
<SwatchPicker
aria-label="SwatchPicker with images"
selectedValue={selectedValue}
onSelectionChange={handleSelect}
>
{images.map(image => (
<ImageSwatch
className={styles.swatch}
key={image.value}
src={image.swatchSrc}
value={image.value}
aria-label={image.label}
/>
))}
</SwatchPicker>
<div
className={styles.example}
style={{
backgroundImage: `url(${selectedImage})`,
}}
/>
</>
);
};
SwatchPickerImage.parameters = {
docs: {
description: {
story: 'A swatch can be represented as an image.',
},
},
};
```
|
```markdown
TSG010 - Get configuration contexts
===================================
Description
-----------
Get the kubernetes contexts
Steps
-----
### Common functions
Define helper functions used in this notebook.```
```python
# Define `run` function for transient fault handling, suggestions on error, and scrolling updates on Windows
import sys
import os
import re
import json
import platform
import shlex
import shutil
import datetime
from subprocess import Popen, PIPE
from IPython.display import Markdown
retry_hints = {} # Output in stderr known to be transient, therefore automatically retry
error_hints = {} # Output in stderr where a known SOP/TSG exists which will be HINTed for further help
install_hint = {} # The SOP to help install the executable if it cannot be found
first_run = True
rules = None
debug_logging = False
def run(cmd, return_output=False, no_output=False, retry_count=0, base64_decode=False, return_as_json=False):
"""Run shell command, stream stdout, print stderr and optionally return output
NOTES:
1. Commands that need this kind of ' quoting on Windows e.g.:
kubectl get nodes -o jsonpath={.items[?(@.metadata.annotations.pv-candidate=='data-pool')].metadata.name}
Need to actually pass in as '"':
kubectl get nodes -o jsonpath={.items[?(@.metadata.annotations.pv-candidate=='"'data-pool'"')].metadata.name}
The ' quote approach, although correct when pasting into Windows cmd, will hang at the line:
`iter(p.stdout.readline, b'')`
The shlex.split call does the right thing for each platform, just use the '"' pattern for a '
"""
MAX_RETRIES = 5
output = ""
retry = False
global first_run
global rules
if first_run:
first_run = False
rules = load_rules()
# When running `azdata sql query` on Windows, replace any
in """ strings, with " ", otherwise we see:
#
# ('HY090', '[HY090] [Microsoft][ODBC Driver Manager] Invalid string or buffer length (0) (SQLExecDirectW)')
#
if platform.system() == "Windows" and cmd.startswith("azdata sql query"):
cmd = cmd.replace("
", " ")
# shlex.split is required on bash and for Windows paths with spaces
#
cmd_actual = shlex.split(cmd)
# Store this (i.e. kubectl, python etc.) to support binary context aware error_hints and retries
#
user_provided_exe_name = cmd_actual[0].lower()
# When running python, use the python in the ADS sandbox ({sys.executable})
#
if cmd.startswith("python "):
cmd_actual[0] = cmd_actual[0].replace("python", sys.executable)
# On Mac, when ADS is not launched from terminal, LC_ALL may not be set, which causes pip installs to fail
# with:
#
# UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 4969: ordinal not in range(128)
#
# Setting it to a default value of "en_US.UTF-8" enables pip install to complete
#
if platform.system() == "Darwin" and "LC_ALL" not in os.environ:
os.environ["LC_ALL"] = "en_US.UTF-8"
# When running `kubectl`, if AZDATA_OPENSHIFT is set, use `oc`
#
if cmd.startswith("kubectl ") and "AZDATA_OPENSHIFT" in os.environ:
cmd_actual[0] = cmd_actual[0].replace("kubectl", "oc")
# To aid supportability, determine which binary file will actually be executed on the machine
#
which_binary = None
# Special case for CURL on Windows. The version of CURL in Windows System32 does not work to
# get JWT tokens, it returns "(56) Failure when receiving data from the peer". If another instance
# of CURL exists on the machine use that one. (Unfortunately the curl.exe in System32 is almost
# always the first curl.exe in the path, and it can't be uninstalled from System32, so here we
# look for the 2nd installation of CURL in the path)
if platform.system() == "Windows" and cmd.startswith("curl "):
path = os.getenv('PATH')
for p in path.split(os.path.pathsep):
p = os.path.join(p, "curl.exe")
if os.path.exists(p) and os.access(p, os.X_OK):
if p.lower().find("system32") == -1:
cmd_actual[0] = p
which_binary = p
break
# Find the path based location (shutil.which) of the executable that will be run (and display it to aid supportability), this
# seems to be required for .msi installs of azdata.cmd/az.cmd. (otherwise Popen returns FileNotFound)
#
# NOTE: Bash needs cmd to be the list of the space separated values hence shlex.split.
#
if which_binary == None:
which_binary = shutil.which(cmd_actual[0])
# Display an install HINT, so the user can click on a SOP to install the missing binary
#
if which_binary == None:
print(f"The path used to search for '{cmd_actual[0]}' was:")
print(sys.path)
if user_provided_exe_name in install_hint and install_hint[user_provided_exe_name] is not None:
display(Markdown(f'HINT: Use [{install_hint[user_provided_exe_name][0]}]({install_hint[user_provided_exe_name][1]}) to resolve this issue.'))
raise FileNotFoundError(f"Executable '{cmd_actual[0]}' not found in path (where/which)")
else:
cmd_actual[0] = which_binary
start_time = datetime.datetime.now().replace(microsecond=0)
print(f"START: {cmd} @ {start_time} ({datetime.datetime.utcnow().replace(microsecond=0)} UTC)")
print(f" using: {which_binary} ({platform.system()} {platform.release()} on {platform.machine()})")
print(f" cwd: {os.getcwd()}")
# Command-line tools such as CURL and AZDATA HDFS commands output
# scrolling progress bars, which causes Jupyter to hang forever, to
# workaround this, use no_output=True
#
# Work around a infinite hang when a notebook generates a non-zero return code, break out, and do not wait
#
wait = True
try:
if no_output:
p = Popen(cmd_actual)
else:
p = Popen(cmd_actual, stdout=PIPE, stderr=PIPE, bufsize=1)
with p.stdout:
for line in iter(p.stdout.readline, b''):
line = line.decode()
if return_output:
output = output + line
else:
if cmd.startswith("azdata notebook run"): # Hyperlink the .ipynb file
regex = re.compile(' "(.*)"\: "(.*)"')
match = regex.match(line)
if match:
if match.group(1).find("HTML") != -1:
display(Markdown(f' - "{match.group(1)}": "{match.group(2)}"'))
else:
display(Markdown(f' - "{match.group(1)}": "[{match.group(2)}]({match.group(2)})"'))
wait = False
break # otherwise infinite hang, have not worked out why yet.
else:
print(line, end='')
if rules is not None:
apply_expert_rules(line)
if wait:
p.wait()
except FileNotFoundError as e:
if install_hint is not None:
display(Markdown(f'HINT: Use {install_hint} to resolve this issue.'))
raise FileNotFoundError(f"Executable '{cmd_actual[0]}' not found in path (where/which)") from e
exit_code_workaround = 0 # WORKAROUND: azdata hangs on exception from notebook on p.wait()
if not no_output:
for line in iter(p.stderr.readline, b''):
try:
line_decoded = line.decode()
except UnicodeDecodeError:
# NOTE: Sometimes we get characters back that cannot be decoded(), e.g.
#
# \xa0
#
# For example see this in the response from `az group create`:
#
# ERROR: Get Token request returned http error: 400 and server
# response: {"error":"invalid_grant",# "error_description":"AADSTS700082:
# The refresh token has expired due to inactivity.\xa0The token was
# issued on 2018-10-25T23:35:11.9832872Z
#
# which generates the exception:
#
# UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 179: invalid start byte
#
print("WARNING: Unable to decode stderr line, printing raw bytes:")
print(line)
line_decoded = ""
pass
else:
# azdata emits a single empty line to stderr when doing an hdfs cp, don't
# print this empty "ERR:" as it confuses.
#
if line_decoded == "":
continue
print(f"STDERR: {line_decoded}", end='')
if line_decoded.startswith("An exception has occurred") or line_decoded.startswith("ERROR: An error occurred while executing the following cell"):
exit_code_workaround = 1
# inject HINTs to next TSG/SOP based on output in stderr
#
if user_provided_exe_name in error_hints:
for error_hint in error_hints[user_provided_exe_name]:
if line_decoded.find(error_hint[0]) != -1:
display(Markdown(f'HINT: Use [{error_hint[1]}]({error_hint[2]}) to resolve this issue.'))
# apply expert rules (to run follow-on notebooks), based on output
#
if rules is not None:
apply_expert_rules(line_decoded)
# Verify if a transient error, if so automatically retry (recursive)
#
if user_provided_exe_name in retry_hints:
for retry_hint in retry_hints[user_provided_exe_name]:
if line_decoded.find(retry_hint) != -1:
if retry_count < MAX_RETRIES:
print(f"RETRY: {retry_count} (due to: {retry_hint})")
retry_count = retry_count + 1
output = run(cmd, return_output=return_output, retry_count=retry_count)
if return_output:
if base64_decode:
import base64
return base64.b64decode(output).decode('utf-8')
else:
return output
elapsed = datetime.datetime.now().replace(microsecond=0) - start_time
# WORKAROUND: We avoid infinite hang above in the `azdata notebook run` failure case, by inferring success (from stdout output), so
# don't wait here, if success known above
#
if wait:
if p.returncode != 0:
raise SystemExit(f'Shell command:
\t{cmd} ({elapsed}s elapsed)
returned non-zero exit code: {str(p.returncode)}.
')
else:
if exit_code_workaround !=0 :
raise SystemExit(f'Shell command:
\t{cmd} ({elapsed}s elapsed)
returned non-zero exit code: {str(exit_code_workaround)}.
')
print(f'
SUCCESS: {elapsed}s elapsed.
')
if return_output:
if base64_decode:
import base64
return base64.b64decode(output).decode('utf-8')
else:
return output
def load_json(filename):
"""Load a json file from disk and return the contents"""
with open(filename, encoding="utf8") as json_file:
return json.load(json_file)
def load_rules():
"""Load any 'expert rules' from the metadata of this notebook (.ipynb) that should be applied to the stderr of the running executable"""
# Load this notebook as json to get access to the expert rules in the notebook metadata.
#
try:
j = load_json("tsg010-get-kubernetes-contexts.ipynb")
except:
pass # If the user has renamed the book, we can't load ourself. NOTE: Is there a way in Jupyter, to know your own filename?
else:
if "metadata" in j and \
"azdata" in j["metadata"] and \
"expert" in j["metadata"]["azdata"] and \
"expanded_rules" in j["metadata"]["azdata"]["expert"]:
rules = j["metadata"]["azdata"]["expert"]["expanded_rules"]
rules.sort() # Sort rules, so they run in priority order (the [0] element). Lowest value first.
# print (f"EXPERT: There are {len(rules)} rules to evaluate.")
return rules
def apply_expert_rules(line):
"""Determine if the stderr line passed in, matches the regular expressions for any of the 'expert rules', if so
inject a 'HINT' to the follow-on SOP/TSG to run"""
global rules
for rule in rules:
notebook = rule[1]
cell_type = rule[2]
output_type = rule[3] # i.e. stream or error
output_type_name = rule[4] # i.e. ename or name
output_type_value = rule[5] # i.e. SystemExit or stdout
details_name = rule[6] # i.e. evalue or text
expression = rule[7].replace("\\*", "*") # Something escaped *, and put a \ in front of it!
if debug_logging:
print(f"EXPERT: If rule '{expression}' satisfied', run '{notebook}'.")
if re.match(expression, line, re.DOTALL):
if debug_logging:
print("EXPERT: MATCH: name = value: '{0}' = '{1}' matched expression '{2}', therefore HINT '{4}'".format(output_type_name, output_type_value, expression, notebook))
match_found = True
display(Markdown(f'HINT: Use [{notebook}]({notebook}) to resolve this issue.'))
print('Common functions defined successfully.')
# Hints for binary (transient fault) retry, (known) error and install guide
#
retry_hints = {'kubectl': ['A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond']}
error_hints = {'kubectl': [['no such host', 'TSG010 - Get configuration contexts', '../monitor-k8s/tsg010-get-kubernetes-contexts.ipynb'], ['No connection could be made because the target machine actively refused it', 'TSG056 - Kubectl fails with No connection could be made because the target machine actively refused it', '../repair/tsg056-kubectl-no-connection-could-be-made.ipynb']]}
install_hint = {'kubectl': ['SOP036 - Install kubectl command line interface', '../install/sop036-install-kubectl.ipynb']}
```
```markdown
### Show the Kubernetes config contexts```
```python
run('kubectl config get-contexts')
```
```python
print('Notebook execution complete.')
```
```markdown
Related
-------
- [SOP011 - Set kubernetes configuration
context](../common/sop011-set-kubernetes-context.ipynb)```
|
```objective-c
namespace winrt::impl
{
inline auto submit_threadpool_callback(void(__stdcall* callback)(void*, void* context), void* context)
{
if (!WINRT_IMPL_TrySubmitThreadpoolCallback(callback, context, nullptr))
{
throw_last_error();
}
}
inline void __stdcall resume_background_callback(void*, void* context) noexcept
{
coroutine_handle<>::from_address(context)();
};
inline auto resume_background(coroutine_handle<> handle)
{
submit_threadpool_callback(resume_background_callback, handle.address());
}
inline std::pair<int32_t, int32_t> get_apartment_type() noexcept
{
int32_t aptType;
int32_t aptTypeQualifier;
if (0 == WINRT_IMPL_CoGetApartmentType(&aptType, &aptTypeQualifier))
{
return { aptType, aptTypeQualifier };
}
else
{
return { 1 /* APTTYPE_MTA */, 1 /* APTTYPEQUALIFIER_IMPLICIT_MTA */ };
}
}
inline bool is_sta_thread() noexcept
{
auto type = get_apartment_type();
switch (type.first)
{
case 0: /* APTTYPE_STA */
case 3: /* APTTYPE_MAINSTA */
return true;
case 2: /* APTTYPE_NA */
return type.second == 3 /* APTTYPEQUALIFIER_NA_ON_STA */ ||
type.second == 5 /* APTTYPEQUALIFIER_NA_ON_MAINSTA */;
}
return false;
}
struct resume_apartment_context
{
resume_apartment_context() = default;
resume_apartment_context(std::nullptr_t) : m_context(nullptr), m_context_type(-1) {}
bool valid() const noexcept
{
return m_context_type.value >= 0;
}
com_ptr<IContextCallback> m_context = try_capture<IContextCallback>(WINRT_IMPL_CoGetObjectContext);
movable_primitive<int32_t, -1> m_context_type = get_apartment_type().first;
};
inline int32_t __stdcall resume_apartment_callback(com_callback_args* args) noexcept
{
coroutine_handle<>::from_address(args->data)();
return 0;
};
[[nodiscard]] inline bool resume_apartment_sync(com_ptr<IContextCallback> const& context, coroutine_handle<> handle, int32_t* failure)
{
com_callback_args args{};
args.data = handle.address();
auto result = context->ContextCallback(resume_apartment_callback, &args, guid_of<ICallbackWithNoReentrancyToApplicationSTA>(), 5, nullptr);
if (result < 0)
{
// Resume the coroutine on the wrong apartment, but tell it why.
*failure = result;
return false;
}
return true;
}
struct threadpool_resume
{
threadpool_resume(com_ptr<IContextCallback> const& context, coroutine_handle<> handle, int32_t* failure) :
m_context(context), m_handle(handle), m_failure(failure) { }
com_ptr<IContextCallback> m_context;
coroutine_handle<> m_handle;
int32_t* m_failure;
};
inline void __stdcall fallback_submit_threadpool_callback(void*, void* p) noexcept
{
std::unique_ptr<threadpool_resume> state{ static_cast<threadpool_resume*>(p) };
if (!resume_apartment_sync(state->m_context, state->m_handle, state->m_failure))
{
state->m_handle.resume();
}
}
inline void resume_apartment_on_threadpool(com_ptr<IContextCallback> const& context, coroutine_handle<> handle, int32_t* failure)
{
auto state = std::make_unique<threadpool_resume>(context, handle, failure);
submit_threadpool_callback(fallback_submit_threadpool_callback, state.get());
state.release();
}
[[nodiscard]] inline auto resume_apartment(resume_apartment_context const& context, coroutine_handle<> handle, int32_t* failure)
{
WINRT_ASSERT(context.valid());
if ((context.m_context == nullptr) || (context.m_context == try_capture<IContextCallback>(WINRT_IMPL_CoGetObjectContext)))
{
return false;
}
else if (context.m_context_type.value == 1 /* APTTYPE_MTA */)
{
resume_background(handle);
return true;
}
else if (is_sta_thread())
{
resume_apartment_on_threadpool(context.m_context, handle, failure);
return true;
}
else
{
return resume_apartment_sync(context.m_context, handle, failure);
}
}
}
WINRT_EXPORT namespace winrt
{
struct cancellable_promise
{
using canceller_t = void(*)(void*);
void set_canceller(canceller_t canceller, void* context)
{
m_context = context;
m_canceller.store(canceller, std::memory_order_release);
}
void revoke_canceller()
{
while (m_canceller.exchange(nullptr, std::memory_order_acquire) == cancelling_ptr)
{
std::this_thread::yield();
}
}
void cancel()
{
auto canceller = m_canceller.exchange(cancelling_ptr, std::memory_order_acquire);
struct unique_cancellation_lock
{
cancellable_promise* promise;
~unique_cancellation_lock()
{
promise->m_canceller.store(nullptr, std::memory_order_release);
}
} lock{ this };
if ((canceller != nullptr) && (canceller != cancelling_ptr))
{
canceller(m_context);
}
}
bool enable_cancellation_propagation(bool value) noexcept
{
return std::exchange(m_propagate_cancellation, value);
}
bool cancellation_propagation_enabled() const noexcept
{
return m_propagate_cancellation;
}
private:
static inline auto const cancelling_ptr = reinterpret_cast<canceller_t>(1);
std::atomic<canceller_t> m_canceller{ nullptr };
void* m_context{ nullptr };
bool m_propagate_cancellation{ false };
};
template <typename Derived>
struct cancellable_awaiter
{
cancellable_awaiter() noexcept = default;
cancellable_awaiter(cancellable_awaiter const&) = default;
~cancellable_awaiter()
{
if (m_promise)
{
m_promise->revoke_canceller();
}
}
void operator=(cancellable_awaiter const&) = delete;
protected:
template <typename T>
void set_cancellable_promise_from_handle(impl::coroutine_handle<T> const& handle)
{
if constexpr (std::is_base_of_v<cancellable_promise, T>)
{
set_cancellable_promise(&handle.promise());
}
}
private:
void set_cancellable_promise(cancellable_promise* promise)
{
if (promise->cancellation_propagation_enabled())
{
m_promise = promise;
static_cast<Derived*>(this)->enable_cancellation(m_promise);
}
}
cancellable_promise* m_promise = nullptr;
};
}
WINRT_EXPORT namespace winrt
{
[[nodiscard]] inline auto resume_background() noexcept
{
struct awaitable
{
bool await_ready() const noexcept
{
return false;
}
void await_resume() const noexcept
{
}
void await_suspend(impl::coroutine_handle<> handle) const
{
impl::resume_background(handle);
}
};
return awaitable{};
}
template <typename T>
[[nodiscard]] auto resume_background(T const& context) noexcept
{
struct awaitable
{
awaitable(T const& context) : m_context(context)
{
}
bool await_ready() const noexcept
{
return false;
}
void await_resume() const noexcept
{
}
void await_suspend(impl::coroutine_handle<> resume)
{
m_resume = resume;
if (!WINRT_IMPL_TrySubmitThreadpoolCallback(callback, this, nullptr))
{
throw_last_error();
}
}
private:
static void __stdcall callback(void*, void* context) noexcept
{
auto that = static_cast<awaitable*>(context);
auto guard = that->m_context();
that->m_resume();
}
T const& m_context;
impl::coroutine_handle<> m_resume{ nullptr };
};
return awaitable{ context };
}
struct apartment_context
{
apartment_context() = default;
apartment_context(std::nullptr_t) : context(nullptr) { }
operator bool() const noexcept { return context.valid(); }
bool operator!() const noexcept { return !context.valid(); }
impl::resume_apartment_context context;
};
}
namespace winrt::impl
{
struct apartment_awaiter
{
apartment_context const& context;
int32_t failure = 0;
bool await_ready() const noexcept
{
return false;
}
void await_resume() const
{
check_hresult(failure);
}
bool await_suspend(impl::coroutine_handle<> handle)
{
auto context_copy = context;
return impl::resume_apartment(context_copy.context, handle, &failure);
}
};
struct timespan_awaiter : cancellable_awaiter<timespan_awaiter>
{
explicit timespan_awaiter(Windows::Foundation::TimeSpan duration) noexcept :
m_duration(duration)
{
}
#if defined(__GNUC__) && !defined(__clang__)
// HACK: GCC seems to require a move when calling operator co_await
// on the return value of resume_after.
// This might be related to upstream bug:
// path_to_url
timespan_awaiter(timespan_awaiter &&other) noexcept :
m_timer{std::move(other.m_timer)},
m_duration{std::move(other.m_duration)},
m_handle{std::move(other.m_handle)},
m_state{other.m_state.load()}
{}
#endif
void enable_cancellation(cancellable_promise* promise)
{
promise->set_canceller([](void* context)
{
auto that = static_cast<timespan_awaiter*>(context);
if (that->m_state.exchange(state::canceled, std::memory_order_acquire) == state::pending)
{
that->fire_immediately();
}
}, this);
}
bool await_ready() const noexcept
{
return m_duration.count() <= 0;
}
template <typename T>
void await_suspend(impl::coroutine_handle<T> handle)
{
set_cancellable_promise_from_handle(handle);
m_handle = handle;
create_threadpool_timer();
}
void await_resume()
{
if (m_state.exchange(state::idle, std::memory_order_relaxed) == state::canceled)
{
throw hresult_canceled();
}
}
private:
void create_threadpool_timer()
{
m_timer.attach(check_pointer(WINRT_IMPL_CreateThreadpoolTimer(callback, this, nullptr)));
int64_t relative_count = -m_duration.count();
WINRT_IMPL_SetThreadpoolTimer(m_timer.get(), &relative_count, 0, 0);
state expected = state::idle;
if (!m_state.compare_exchange_strong(expected, state::pending, std::memory_order_release))
{
fire_immediately();
}
}
void fire_immediately() noexcept
{
if (WINRT_IMPL_SetThreadpoolTimerEx(m_timer.get(), nullptr, 0, 0))
{
int64_t now = 0;
WINRT_IMPL_SetThreadpoolTimer(m_timer.get(), &now, 0, 0);
}
}
static void __stdcall callback(void*, void* context, void*) noexcept
{
auto that = reinterpret_cast<timespan_awaiter*>(context);
that->m_handle();
}
struct timer_traits
{
using type = impl::ptp_timer;
static void close(type value) noexcept
{
WINRT_IMPL_CloseThreadpoolTimer(value);
}
static constexpr type invalid() noexcept
{
return nullptr;
}
};
enum class state { idle, pending, canceled };
handle_type<timer_traits> m_timer;
Windows::Foundation::TimeSpan m_duration;
impl::coroutine_handle<> m_handle;
std::atomic<state> m_state{ state::idle };
};
struct signal_awaiter : cancellable_awaiter<signal_awaiter>
{
signal_awaiter(void* handle, Windows::Foundation::TimeSpan timeout) noexcept :
m_timeout(timeout),
m_handle(handle)
{}
#if defined(__GNUC__) && !defined(__clang__)
// HACK: GCC seems to require a move when calling operator co_await
// on the return value of resume_on_signal.
// This might be related to upstream bug:
// path_to_url
signal_awaiter(signal_awaiter &&other) noexcept :
m_wait{std::move(other.m_wait)},
m_timeout{std::move(other.m_timeout)},
m_handle{std::move(other.m_handle)},
m_result{std::move(other.m_result)},
m_resume{std::move(other.m_resume)},
m_state{other.m_state.load()}
{}
#endif
void enable_cancellation(cancellable_promise* promise)
{
promise->set_canceller([](void* context)
{
auto that = static_cast<signal_awaiter*>(context);
if (that->m_state.exchange(state::canceled, std::memory_order_acquire) == state::pending)
{
that->fire_immediately();
}
}, this);
}
bool await_ready() const noexcept
{
return WINRT_IMPL_WaitForSingleObject(m_handle, 0) == 0;
}
template <typename T>
void await_suspend(impl::coroutine_handle<T> resume)
{
set_cancellable_promise_from_handle(resume);
m_resume = resume;
create_threadpool_wait();
}
bool await_resume()
{
if (m_state.exchange(state::idle, std::memory_order_relaxed) == state::canceled)
{
throw hresult_canceled();
}
return m_result == 0;
}
private:
void create_threadpool_wait()
{
m_wait.attach(check_pointer(WINRT_IMPL_CreateThreadpoolWait(callback, this, nullptr)));
int64_t relative_count = -m_timeout.count();
int64_t* file_time = relative_count != 0 ? &relative_count : nullptr;
WINRT_IMPL_SetThreadpoolWait(m_wait.get(), m_handle, file_time);
state expected = state::idle;
if (!m_state.compare_exchange_strong(expected, state::pending, std::memory_order_release))
{
fire_immediately();
}
}
void fire_immediately() noexcept
{
if (WINRT_IMPL_SetThreadpoolWaitEx(m_wait.get(), nullptr, nullptr, nullptr))
{
int64_t now = 0;
WINRT_IMPL_SetThreadpoolWait(m_wait.get(), WINRT_IMPL_GetCurrentProcess(), &now);
}
}
static void __stdcall callback(void*, void* context, void*, uint32_t result) noexcept
{
auto that = static_cast<signal_awaiter*>(context);
that->m_result = result;
that->m_resume();
}
struct wait_traits
{
using type = impl::ptp_wait;
static void close(type value) noexcept
{
WINRT_IMPL_CloseThreadpoolWait(value);
}
static constexpr type invalid() noexcept
{
return nullptr;
}
};
enum class state { idle, pending, canceled };
handle_type<wait_traits> m_wait;
Windows::Foundation::TimeSpan m_timeout;
void* m_handle;
uint32_t m_result{};
impl::coroutine_handle<> m_resume{ nullptr };
std::atomic<state> m_state{ state::idle };
};
}
WINRT_EXPORT namespace winrt
{
#ifdef WINRT_IMPL_COROUTINES
inline impl::apartment_awaiter operator co_await(apartment_context const& context)
{
return{ context };
}
#endif
[[nodiscard]] inline impl::timespan_awaiter resume_after(Windows::Foundation::TimeSpan duration) noexcept
{
return impl::timespan_awaiter{ duration };
}
#ifdef WINRT_IMPL_COROUTINES
inline impl::timespan_awaiter operator co_await(Windows::Foundation::TimeSpan duration)
{
return resume_after(duration);
}
#endif
[[nodiscard]] inline impl::signal_awaiter resume_on_signal(void* handle, Windows::Foundation::TimeSpan timeout = {}) noexcept
{
return impl::signal_awaiter{ handle, timeout };
}
struct thread_pool
{
thread_pool() :
m_pool(check_pointer(WINRT_IMPL_CreateThreadpool(nullptr)))
{
m_environment.Pool = m_pool.get();
}
void thread_limits(uint32_t const high, uint32_t const low)
{
WINRT_IMPL_SetThreadpoolThreadMaximum(m_pool.get(), high);
check_bool(WINRT_IMPL_SetThreadpoolThreadMinimum(m_pool.get(), low));
}
bool await_ready() const noexcept
{
return false;
}
void await_resume() const noexcept
{
}
void await_suspend(impl::coroutine_handle<> handle)
{
if (!WINRT_IMPL_TrySubmitThreadpoolCallback(callback, handle.address(), &m_environment))
{
throw_last_error();
}
}
private:
static void __stdcall callback(void*, void* context) noexcept
{
impl::coroutine_handle<>::from_address(context)();
}
struct pool_traits
{
using type = impl::ptp_pool;
static void close(type value) noexcept
{
WINRT_IMPL_CloseThreadpool(value);
}
static constexpr type invalid() noexcept
{
return nullptr;
}
};
struct environment // TP_CALLBACK_ENVIRON
{
uint32_t Version{ 3 };
void* Pool{};
void* CleanupGroup{};
void* CleanupGroupCancelCallback{};
void* RaceDll{};
void* ActivationContext{};
void* FinalizationCallback{};
union
{
uint32_t Flags{};
struct
{
uint32_t LongFunction : 1;
uint32_t Persistent : 1;
uint32_t Private : 30;
} s;
} u;
int32_t CallbackPriority{ 1 };
uint32_t Size{ sizeof(environment) };
};
handle_type<pool_traits> m_pool;
environment m_environment;
};
struct fire_and_forget {};
}
#ifdef __cpp_lib_coroutine
namespace std
#else
namespace std::experimental
#endif
{
template <typename... Args>
struct coroutine_traits<winrt::fire_and_forget, Args...>
{
struct promise_type
{
winrt::fire_and_forget get_return_object() const noexcept
{
return{};
}
void return_void() const noexcept
{
}
suspend_never initial_suspend() const noexcept
{
return{};
}
suspend_never final_suspend() const noexcept
{
return{};
}
void unhandled_exception() const noexcept
{
winrt::terminate();
}
};
};
}
```
|
The Residency Museum, also referred to as the Residency Building, is an exhibition space at the Museum of the Great Southern in Albany in the Great Southern region of Western Australia.
Description
The site overlooks Princess Royal Harbour and is where Major Edmund Lockyer hoisted the British flag in 1827.
The museum is a single storey building with a timber shingled roof. The building has an L shape, with the entrance on the northern side. The walls are of brick construction rendered externally and plastered internally. The roof is timber framed and the building is enclosed with a verandah. An entry vestibule is on the inside of the L shape, with brick paving and a parking area.
Initially the building was a single room, used as a store. Over the next few years another three rooms were added, with all four rooms having a common hipped roof. Further extensions and renovations occurred when it became the governor's residence in 1873, with an additional seven rooms being added creating the L shaped building.
History
The building was originally completed in 1854 and served as a store and an office for the nearby convict hiring depot at the Albany Convict Gaol. Following the closure of the depot in 1872 seven more rooms with an exterior verandah were added to the building for renovations to convert it to the Governor's Residency. From 1873 to 1953 the building housed the local government administrator, known as the Government Resident until 1901 and later as the Resident Magistrate. Both positions has social status and the building hosted tea parties, balls, weddings and other social events.
King George V spent his 16th birthday in the Residency with his brother Prince Albert Victor in 1881. The two were on a naval tour when their ship, , broke its rudder during a storm.
The Major Lockyer Memorial was erected in 1936 between the Residency and the harbour.
From 1953 to 1970 the building had various other uses including a school hostel, a sea scout headquarters, naval depot and training facility. By 1975 renovations were completed and it reopened as the Residency Museum, the first branch of the Western Australian Museum to open outside of the Perth metropolitan area.
Elizabeth II visited the site in 1977 to officially open the Lockyer Memorial as part of the 150th anniversary of first British settlement in Western Australia celebrations.
In 1985 the site was renamed as the Western Australian Museum - Albany. The site received temporary heritage listing in 1996, and in 2010 further renovations were completed creating several new galleries used to display Mineng and settlers' stories.
By 1996 the building was cracking badly with rising damp and several leaks.
The building was extensively refurbished in 2010.
The building is now part of the Museum of the Great Southern.
See also
List of places on the State Register of Heritage Places in the City of Albany
References
Heritage places in Albany, Western Australia
1854 establishments in Australia
State Register of Heritage Places in the City of Albany
|
Travbuddy.com was a social networking website specializing in connecting travellers. The site was created by brothers Eric Bjorndahl and David Bjorndahl and launched in 2005 by TravBuddy LLC, a privately owned company.
The site allowed users to find travel buddies planning to travel to the same places at the same times, create travel based blogs, upload travel photos and review bars, restaurants, hotels and attractions.
As of August 2013, the site had nearly 470,000 registered contributors.
As of August 2013, the site provided free access to over 198,000 blogs, 97,000 travel reviews, and 4,600,000 travel photos.
The site ceased operations on April 23, 2018.
Since its launch, the site has been featured on the NBC Nightly News, Popular Science, Real Simple Travel, and the Herald Tribune.
References
External links
TravBuddy Farewell (via YouTube) by sirgerald12th
American travel websites
American social networking websites
Defunct social networking services
Internet properties established in 2005
|
```java
/*
* code is released under a tri EPL/GPL/LGPL license. You can use it,
* redistribute it and/or modify it under the terms of the:
*
*/
package org.truffleruby.core.exception;
import com.oracle.truffle.api.interop.InteropLibrary;
import com.oracle.truffle.api.library.CachedLibrary;
import com.oracle.truffle.api.object.Shape;
import com.oracle.truffle.api.profiles.InlinedConditionProfile;
import org.truffleruby.annotations.SuppressFBWarnings;
import org.truffleruby.annotations.CoreMethod;
import org.truffleruby.builtins.CoreMethodArrayArgumentsNode;
import org.truffleruby.annotations.CoreModule;
import org.truffleruby.annotations.Primitive;
import org.truffleruby.builtins.PrimitiveArrayArgumentsNode;
import org.truffleruby.builtins.PrimitiveNode;
import org.truffleruby.core.array.RubyArray;
import org.truffleruby.core.klass.RubyClass;
import org.truffleruby.core.proc.RubyProc;
import org.truffleruby.language.Nil;
import org.truffleruby.language.NotProvided;
import org.truffleruby.annotations.Visibility;
import org.truffleruby.language.backtrace.Backtrace;
import org.truffleruby.language.backtrace.BacktraceFormatter;
import org.truffleruby.language.control.RaiseException;
import org.truffleruby.language.methods.LookupMethodOnSelfNode;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.VirtualFrame;
import org.truffleruby.language.objects.AllocationTracing;
@CoreModule(value = "Exception", isClass = true)
public abstract class ExceptionNodes {
@CoreMethod(names = { "__allocate__", "__layout_allocate__" }, constructor = true, visibility = Visibility.PRIVATE)
public abstract static class AllocateNode extends CoreMethodArrayArgumentsNode {
@Specialization
RubyException allocateException(RubyClass rubyClass) {
final Shape shape = getLanguage().exceptionShape;
final RubyException instance = new RubyException(rubyClass, shape, nil, null, nil);
AllocationTracing.trace(instance, this);
return instance;
}
}
@CoreMethod(names = "initialize", optional = 1)
public abstract static class InitializeNode extends CoreMethodArrayArgumentsNode {
@Specialization
RubyException initialize(RubyException exception, NotProvided message) {
exception.message = nil;
return exception;
}
@Specialization(guards = "wasProvided(message)")
RubyException initialize(RubyException exception, Object message) {
exception.message = message;
return exception;
}
}
@CoreMethod(names = "initialize_copy", required = 1)
public abstract static class InitializeCopyNode extends CoreMethodArrayArgumentsNode {
@Specialization(guards = "self == from")
RubyException initializeCopySelfIsSameAsFrom(RubyException self, RubyException from) {
return self;
}
@Specialization(
guards = { "self != from", "!isNameError(from)", "!isSystemCallError(from)" })
RubyException initializeCopy(RubyException self, RubyException from) {
initializeExceptionCopy(self, from);
return self;
}
@Specialization(guards = "self != from")
RubyException initializeSystemCallErrorCopy(RubySystemCallError self, RubySystemCallError from) {
initializeExceptionCopy(self, from);
self.errno = from.errno;
return self;
}
@Specialization(guards = "self != from")
RubyException initializeCopyNoMethodError(RubyNoMethodError self, RubyNoMethodError from) {
initializeExceptionCopy(self, from);
initializeNameErrorCopy(self, from);
self.args = from.args;
return self;
}
@Specialization(
guards = { "self != from", "!isNoMethodError(from)" })
RubyException initializeCopyNameError(RubyNameError self, RubyNameError from) {
initializeExceptionCopy(self, from);
initializeNameErrorCopy(self, from);
return self;
}
protected boolean isNameError(RubyException object) {
return object instanceof RubyNameError;
}
protected boolean isNoMethodError(RubyException object) {
return object instanceof RubyNoMethodError;
}
protected boolean isSystemCallError(RubyException object) {
return object instanceof RubySystemCallError;
}
private void initializeNameErrorCopy(RubyNameError self, RubyNameError from) {
self.name = from.name;
self.receiver = from.receiver;
}
private void initializeExceptionCopy(RubyException self, RubyException from) {
Backtrace backtrace = from.backtrace;
if (backtrace != null) {
self.backtrace = backtrace.copy(self);
} else {
self.backtrace = null;
}
self.formatter = from.formatter;
self.message = from.message;
self.cause = from.cause;
self.backtraceStringArray = from.backtraceStringArray;
self.backtraceLocations = from.backtraceLocations;
self.customBacktrace = from.customBacktrace;
}
}
@CoreMethod(names = "backtrace")
public abstract static class BacktraceNode extends CoreMethodArrayArgumentsNode {
@Specialization
Object backtrace(RubyException exception,
@Cached InlinedConditionProfile hasCustomBacktraceProfile,
@Cached InlinedConditionProfile hasBacktraceProfile) {
final Object customBacktrace = exception.customBacktrace;
if (hasCustomBacktraceProfile.profile(this, customBacktrace != null)) {
return customBacktrace;
} else if (hasBacktraceProfile.profile(this, exception.backtrace != null)) {
RubyArray backtraceStringArray = exception.backtraceStringArray;
if (backtraceStringArray == null) {
backtraceStringArray = getContext().getUserBacktraceFormatter().formatBacktraceAsRubyStringArray(
exception,
exception.backtrace);
exception.backtraceStringArray = backtraceStringArray;
}
return backtraceStringArray;
} else {
return nil;
}
}
}
@CoreMethod(names = "backtrace_locations")
public abstract static class BacktraceLocationsNode extends CoreMethodArrayArgumentsNode {
@Specialization
Object backtraceLocations(RubyException exception,
@Cached InlinedConditionProfile hasBacktraceProfile,
@Cached InlinedConditionProfile hasLocationsProfile) {
if (hasBacktraceProfile.profile(this, exception.backtrace != null)) {
Object backtraceLocations = exception.backtraceLocations;
if (hasLocationsProfile.profile(this, backtraceLocations == null)) {
Backtrace backtrace = exception.backtrace;
backtraceLocations = backtrace
.getBacktraceLocations(getContext(), getLanguage(), GetBacktraceException.UNLIMITED, null);
exception.backtraceLocations = backtraceLocations;
}
return backtraceLocations;
} else {
return nil;
}
}
}
@Primitive(name = "exception_backtrace?")
public abstract static class BacktraceQueryPrimitiveNode extends PrimitiveArrayArgumentsNode {
protected static final String METHOD = "backtrace";
/* We can cheaply determine if an Exception has a backtrace via object inspection. However, if
* `Exception#backtrace` is redefined, then `Exception#backtrace?` needs to follow along to be consistent. So,
* we check if the method has been redefined here and if so, fall back to the Ruby code for the method by
* returning `FAILURE` in the fallback specialization. */
@Specialization(
guards = {
"lookupNode.lookupProtected(frame, exception, METHOD) == getContext().getCoreMethods().EXCEPTION_BACKTRACE", },
limit = "1")
boolean backtraceQuery(VirtualFrame frame, RubyException exception,
@Cached LookupMethodOnSelfNode lookupNode) {
return !(exception.customBacktrace == null && exception.backtrace == null);
}
@Specialization
Object fallback(RubyException exception) {
return FAILURE;
}
@Specialization(guards = "!isRubyException(exception)", limit = "getInteropCacheLimit()")
boolean foreignException(Object exception,
@CachedLibrary("exception") InteropLibrary interopLibrary) {
return interopLibrary.hasExceptionStackTrace(exception);
}
}
@Primitive(name = "exception_capture_backtrace", lowerFixnum = 1)
public abstract static class CaptureBacktraceNode extends PrimitiveArrayArgumentsNode {
@Specialization
Object captureBacktrace(RubyException exception, int offset) {
exception.backtrace = getContext().getCallStack().getBacktrace(this, offset);
return nil;
}
}
@Primitive(name = "exception_message")
public abstract static class MessagePrimitiveNode extends PrimitiveArrayArgumentsNode {
@Specialization
Object message(RubyException exception) {
final Object message = exception.message;
if (message == null) {
return nil;
} else {
return message;
}
}
}
@Primitive(name = "exception_set_message")
public abstract static class MessageSetNode extends PrimitiveArrayArgumentsNode {
@Specialization
Object setMessage(RubyException exception, Object message) {
exception.message = message;
return nil;
}
}
@Primitive(name = "exception_set_custom_backtrace")
public abstract static class SetCustomBacktrace extends PrimitiveArrayArgumentsNode {
@Specialization
Object set(RubyException exception, Object customBacktrace) {
exception.customBacktrace = customBacktrace;
return customBacktrace;
}
}
@Primitive(name = "exception_formatter")
public abstract static class FormatterPrimitiveNode extends PrimitiveArrayArgumentsNode {
@Specialization
Object formatter(RubyException exception) {
final RubyProc formatter = exception.formatter;
if (formatter == null) {
return nil;
} else {
return formatter;
}
}
}
@CoreMethod(names = "cause")
public abstract static class CauseNode extends CoreMethodArrayArgumentsNode {
@Specialization
Object cause(RubyException exception) {
return exception.cause;
}
}
@Primitive(name = "exception_set_cause")
public abstract static class ExceptionSetCauseNode extends PrimitiveArrayArgumentsNode {
@Specialization
RubyException setCause(RubyException exception, Object cause) {
exception.cause = cause;
return exception;
}
@Specialization(guards = "!isRubyException(exception)")
Object foreignExceptionNoCause(Object exception, Nil cause) {
return exception;
}
@Specialization(guards = { "!isRubyException(exception)", "!isNil(cause)" })
Object foreignExceptionWithCause(Object exception, Object cause) {
RubyException exc = coreExceptions().runtimeError("Cannot set the cause of a foreign exception", this);
exc.cause = cause;
throw new RaiseException(getContext(), exc);
}
}
@Primitive(name = "exception_errno_error", lowerFixnum = 2)
public abstract static class ExceptionErrnoErrorPrimitiveNode extends PrimitiveArrayArgumentsNode {
@Child ErrnoErrorNode errnoErrorNode = ErrnoErrorNode.create();
@Specialization
RubySystemCallError exceptionErrnoError(RubyClass errorClass, Object message, int errno) {
return errnoErrorNode.execute(errorClass, errno, message, null);
}
}
@Primitive(name = "java_breakpoint")
@SuppressWarnings("unused")
public abstract static class Breakpoint extends PrimitiveNode {
@SuppressFBWarnings("DLS")
@TruffleBoundary
@Specialization
boolean breakpoint() {
// have a Ruby backtrace at hand
String printableRubyBacktrace = BacktraceFormatter.printableRubyBacktrace(this);
return true; // place to put a Java breakpoint
}
}
@Primitive(name = "exception_backtrace_limit")
public abstract static class BacktraceLimitNode extends PrimitiveArrayArgumentsNode {
@Specialization
int limit() {
return getContext().getOptions().BACKTRACE_LIMIT;
}
}
@Primitive(name = "exception_get_raise_exception")
public abstract static class GetRaiseExceptionNode extends PrimitiveArrayArgumentsNode {
@Specialization
Object getRaiseException(RubyException exception) {
RaiseException raiseException = exception.backtrace.getRaiseException();
if (raiseException != null) {
return raiseException;
} else {
return nil;
}
}
}
}
```
|
```shell
Detect your linux distribution
Find the `MAC` address of all network interfaces
Find out if the system's architecture is 32 or 64 bit
Preventing a user from logging into the system
Fixing `locale` issues in Debian systems
```
|
```java
/*
*
*
* 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.springframework.cloud.gateway.filter.factory.rewrite;
import java.util.List;
import java.util.function.Function;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.support.BodyInserterContext;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.web.reactive.function.BodyInserter;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerStrategies;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ServerWebExchange;
import static org.springframework.cloud.gateway.support.GatewayToStringStyler.filterToStringCreator;
/**
* GatewayFilter that modifies the request body.
*/
public class ModifyRequestBodyGatewayFilterFactory
extends AbstractGatewayFilterFactory<ModifyRequestBodyGatewayFilterFactory.Config> {
private final List<HttpMessageReader<?>> messageReaders;
public ModifyRequestBodyGatewayFilterFactory() {
super(Config.class);
this.messageReaders = HandlerStrategies.withDefaults().messageReaders();
}
public ModifyRequestBodyGatewayFilterFactory(List<HttpMessageReader<?>> messageReaders) {
super(Config.class);
this.messageReaders = messageReaders;
}
@Override
@SuppressWarnings("unchecked")
public GatewayFilter apply(Config config) {
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ParameterizedTypeReference inClass = config.getInClass();
ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders);
// TODO: flux or mono
Mono<?> modifiedBody = serverRequest.bodyToMono(inClass)
.flatMap(originalBody -> config.getRewriteFunction().apply(exchange, originalBody))
.switchIfEmpty(Mono.defer(() -> (Mono) config.getRewriteFunction().apply(exchange, null)));
BodyInserter bodyInserter = BodyInserters.fromPublisher(modifiedBody, config.getOutClass());
HttpHeaders headers = new HttpHeaders();
headers.putAll(exchange.getRequest().getHeaders());
// the new content type will be computed by bodyInserter
// and then set in the request decorator
headers.remove(HttpHeaders.CONTENT_LENGTH);
// if the body is changing content types, set it here, to the bodyInserter
// will know about it
if (config.getContentType() != null) {
headers.set(HttpHeaders.CONTENT_TYPE, config.getContentType());
}
CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(exchange, headers);
return bodyInserter.insert(outputMessage, new BodyInserterContext())
// .log("modify_request", Level.INFO)
.then(Mono.defer(() -> {
ServerHttpRequest decorator = decorate(exchange, headers, outputMessage);
return chain.filter(exchange.mutate().request(decorator).build());
}))
.onErrorResume(
(Function<Throwable, Mono<Void>>) throwable -> release(exchange, outputMessage, throwable));
}
@Override
public String toString() {
return filterToStringCreator(ModifyRequestBodyGatewayFilterFactory.this)
.append("Content type", config.getContentType())
.append("In class", config.getInClass())
.append("Out class", config.getOutClass())
.toString();
}
};
}
protected Mono<Void> release(ServerWebExchange exchange, CachedBodyOutputMessage outputMessage,
Throwable throwable) {
if (outputMessage.isCached()) {
return outputMessage.getBody().map(DataBufferUtils::release).then(Mono.error(throwable));
}
return Mono.error(throwable);
}
ServerHttpRequestDecorator decorate(ServerWebExchange exchange, HttpHeaders headers,
CachedBodyOutputMessage outputMessage) {
return new ServerHttpRequestDecorator(exchange.getRequest()) {
@Override
public HttpHeaders getHeaders() {
long contentLength = headers.getContentLength();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.putAll(headers);
if (contentLength > 0) {
httpHeaders.setContentLength(contentLength);
}
else {
// TODO: this causes a 'HTTP/1.1 411 Length Required' // on
// httpbin.org
httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
}
return httpHeaders;
}
@Override
public Flux<DataBuffer> getBody() {
return outputMessage.getBody();
}
};
}
public static class Config {
private ParameterizedTypeReference inClass;
private ParameterizedTypeReference outClass;
private String contentType;
private RewriteFunction rewriteFunction;
public ParameterizedTypeReference getInClass() {
return inClass;
}
public Config setInClass(Class inClass) {
return setInClass(ParameterizedTypeReference.forType(inClass));
}
public Config setInClass(ParameterizedTypeReference inTypeReference) {
this.inClass = inTypeReference;
return this;
}
public ParameterizedTypeReference getOutClass() {
return outClass;
}
public Config setOutClass(Class outClass) {
return setOutClass(ParameterizedTypeReference.forType(outClass));
}
public Config setOutClass(ParameterizedTypeReference outClass) {
this.outClass = outClass;
return this;
}
public RewriteFunction getRewriteFunction() {
return rewriteFunction;
}
public Config setRewriteFunction(RewriteFunction rewriteFunction) {
this.rewriteFunction = rewriteFunction;
return this;
}
public <T, R> Config setRewriteFunction(Class<T> inClass, Class<R> outClass,
RewriteFunction<T, R> rewriteFunction) {
setInClass(inClass);
setOutClass(outClass);
setRewriteFunction(rewriteFunction);
return this;
}
public <T, R> Config setRewriteFunction(ParameterizedTypeReference<T> inClass,
ParameterizedTypeReference<R> outClass, RewriteFunction<T, R> rewriteFunction) {
setInClass(inClass);
setOutClass(outClass);
setRewriteFunction(rewriteFunction);
return this;
}
public String getContentType() {
return contentType;
}
public Config setContentType(String contentType) {
this.contentType = contentType;
return this;
}
}
}
```
|
```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 org.graalvm.visualvm.modules.mbeans;
import org.openide.util.NbBundle;
/**
* Provides resource support for the containing java package.
*/
final class Resources {
private Resources() {
throw new AssertionError();
}
/**
* Returns the text of the resource for the specified
* key formatted with the specified arguments.
*/
public static String getText(String key, Object... args) {
return NbBundle.getMessage(Resources.class, key, args);
}
/**
* Returns the mnemonic keycode int of the resource for
* the specified key.
*/
public static int getMnemonicInt(String key) {
String m = getText(key + ".mnemonic"); // NOI18N
int mnemonic = m.charAt(0);
if (mnemonic >= 'a' && mnemonic <= 'z') {
mnemonic -= ('a' - 'A');
}
return mnemonic;
}
}
```
|
```objective-c
function checkCostFunction(lambda)
%CHECKCOSTFUNCTION Creates a collaborative filering problem
%to check your cost function and gradients
% CHECKCOSTFUNCTION(lambda) Creates a collaborative filering problem
% to check your cost function and gradients, it will output the
% analytical gradients produced by your code and the numerical gradients
% (computed using computeNumericalGradient). These two gradient
% computations should result in very similar values.
% Set lambda
if ~exist('lambda', 'var') || isempty(lambda)
lambda = 0;
end
%% Create small problem
X_t = rand(4, 3);
Theta_t = rand(5, 3);
% Zap out most entries
Y = X_t * Theta_t';
Y(rand(size(Y)) > 0.5) = 0;
R = zeros(size(Y));
R(Y ~= 0) = 1;
%% Run Gradient Checking
X = randn(size(X_t));
Theta = randn(size(Theta_t));
num_users = size(Y, 2);
num_movies = size(Y, 1);
num_features = size(Theta_t, 2);
numgrad = computeNumericalGradient( ...
@(t) cofiCostFunc(t, Y, R, num_users, num_movies, ...
num_features, lambda), [X(:); Theta(:)]);
[cost, grad] = cofiCostFunc([X(:); Theta(:)], Y, R, num_users, ...
num_movies, num_features, lambda);
disp([numgrad grad]);
fprintf(['The above two columns you get should be very similar.\n' ...
'(Left-Your Numerical Gradient, Right-Analytical Gradient)\n\n']);
diff = norm(numgrad-grad)/norm(numgrad+grad);
fprintf(['If your backpropagation implementation is correct, then \n' ...
'the relative difference will be small (less than 1e-9). \n' ...
'\nRelative Difference: %g\n'], diff);
end
```
|
Curtohibolites is a genus of belemnite, an extinct group of cephalopods.
See also
Belemnite
List of belemnites
References
Belemnites
|
Izvorani may refer to several villages in Romania:
Izvorani, a village in the town of Ştefăneşti, Argeș County
Izvorani, a village in Ciolpani Commune, Ilfov County
|
```c++
/* ==========================================================================
* phf.cc - Tiny perfect hash function library.
* your_sha256_hash----------
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
* ==========================================================================
*/
#include <limits.h> /* CHAR_BIT SIZE_MAX */
#include <inttypes.h> /* PRIu32 PRIu64 PRIx64 */
#include <stdint.h> /* UINT32_C UINT64_C uint32_t uint64_t */
#include <stdlib.h> /* abort(3) calloc(3) free(3) qsort(3) */
#include <string.h> /* memset(3) */
#include <errno.h> /* errno */
#include <assert.h> /* assert(3) */
#if !PHF_NO_LIBCXX
#include <string> /* std::string */
#endif
#include "phf.h"
#ifdef __clang__
#pragma clang diagnostic ignored "-Wunused-function"
#if __cplusplus < 201103L
#pragma clang diagnostic ignored "-Wc++11-long-long"
#endif
#elif PHF_GNUC_PREREQ(4, 6)
#pragma GCC diagnostic ignored "-Wunused-function"
#if __cplusplus < 201103L
#pragma GCC diagnostic ignored "-Wlong-long"
#pragma GCC diagnostic ignored "-Wformat" // %zu
#endif
#endif
/*
* M A C R O R O U T I N E S
*
* Mostly copies of <sys/param.h>
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#define PHF_BITS(T) (sizeof (T) * CHAR_BIT)
#define PHF_HOWMANY(x, y) (((x) + ((y) - 1)) / (y))
#define PHF_MIN(a, b) (((a) < (b))? (a) : (b))
#define PHF_MAX(a, b) (((a) > (b))? (a) : (b))
#define PHF_ROTL(x, y) (((x) << (y)) | ((x) >> (PHF_BITS(x) - (y))))
#define PHF_COUNTOF(a) (sizeof (a) / sizeof *(a))
/*
* M O D U L A R A R I T H M E T I C R O U T I N E S
*
* Two modular reduction schemes are supported: bitwise AND and naive
* modular division. For bitwise AND we must round up the values r and m to
* a power of 2.
*
* TODO: Implement and test Barrett reduction as alternative to naive
* modular division.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* round up to nearest power of 2 */
static inline size_t phf_powerup(size_t i) {
#if defined SIZE_MAX
i--;
i |= i >> 1;
i |= i >> 2;
i |= i >> 4;
i |= i >> 8;
i |= i >> 16;
#if SIZE_MAX != 0xffffffffu
i |= i >> 32;
#endif
return ++i;
#else
#error No SIZE_MAX defined
#endif
} /* phf_powerup() */
static inline uint64_t phf_a_s_mod_n(uint64_t a, uint64_t s, uint64_t n) {
uint64_t v;
assert(n <= UINT32_MAX);
v = 1;
a %= n;
while (s > 0) {
if (s % 2 == 1)
v = (v * a) % n;
a = (a * a) % n;
s /= 2;
}
return v;
} /* phf_a_s_mod_n() */
/*
* Rabin-Miller primality test adapted from Niels Ferguson and Bruce
* Schneier, "Practical Cryptography" (Wiley, 2003), 201-204.
*/
static inline bool phf_witness(uint64_t n, uint64_t a, uint64_t s, uint64_t t) {
uint64_t v, i;
assert(a > 0 && a < n);
assert(n <= UINT32_MAX);
if (1 == (v = phf_a_s_mod_n(a, s, n)))
return 1;
for (i = 0; v != n - 1; i++) {
if (i == t - 1)
return 0;
v = (v * v) % n;
}
return 1;
} /* phf_witness() */
static inline bool phf_rabinmiller(uint64_t n) {
/*
* Witness 2 is deterministic for all n < 2047. Witnesses 2, 7, 61
* are deterministic for all n < 4,759,123,141.
*/
static const int witness[] = { 2, 7, 61 };
uint64_t s, t, i;
assert(n <= UINT32_MAX);
if (n < 3 || n % 2 == 0)
return 0;
/* derive 2^t * s = n - 1 where s is odd */
s = n - 1;
t = 0;
while (s % 2 == 0) {
s /= 2;
t++;
}
/* NB: witness a must be 1 <= a < n */
if (n < 2027)
return phf_witness(n, 2, s, t);
for (i = 0; i < PHF_COUNTOF(witness); i++) {
if (!phf_witness(n, witness[i], s, t))
return 0;
}
return 1;
} /* phf_rabinmiller() */
static inline bool phf_isprime(size_t n) {
static const char map[] = { 0, 1, 2, 3, 0, 5, 0, 7 };
size_t i;
if (n < PHF_COUNTOF(map))
return map[n];
for (i = 2; i < PHF_COUNTOF(map); i++) {
if (map[i] && (n % map[i] == 0))
return 0;
}
return phf_rabinmiller(n);
} /* phf_isprime() */
static inline size_t phf_primeup(size_t n) {
/* NB: 4294967291 is largest 32-bit prime */
if (n > 4294967291)
return 0;
while (n < SIZE_MAX && !phf_isprime(n))
n++;
return n;
} /* phf_primeup() */
/*
* B I T M A P R O U T I N E S
*
* We use a bitmap to track output hash occupancy when searching for
* displacement values.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
typedef unsigned long phf_bits_t;
static inline bool phf_isset(phf_bits_t *set, size_t i) {
return set[i / PHF_BITS(*set)] & ((size_t)1 << (i % PHF_BITS(*set)));
} /* phf_isset() */
static inline void phf_setbit(phf_bits_t *set, size_t i) {
set[i / PHF_BITS(*set)] |= ((size_t)1 << (i % PHF_BITS(*set)));
} /* phf_setbit() */
static inline void phf_clrbit(phf_bits_t *set, size_t i) {
set[i / PHF_BITS(*set)] &= ~((size_t)1 << (i % PHF_BITS(*set)));
} /* phf_clrbit() */
static inline void phf_clrall(phf_bits_t *set, size_t n) {
memset(set, '\0', PHF_HOWMANY(n, PHF_BITS(*set)) * sizeof *set);
} /* phf_clrall() */
/*
* K E Y D E D U P L I C A T I O N
*
* Auxiliary routine to ensure uniqueness of each key in array.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
namespace PHF {
namespace Uniq {
static bool operator!=(const phf_string_t &a, const phf_string_t &b) {
return a.n != b.n || 0 != memcmp(a.p, b.p, a.n);
}
template<typename T>
static int cmp(const T *a, const T *b) {
if (*a > *b)
return -1;
if (*a < *b)
return 1;
return 0;
} /* cmp() */
template<>
int cmp(const phf_string_t *a, const phf_string_t *b) {
int cmp = memcmp(a->p, b->p, PHF_MIN(a->n, b->n));
if (cmp)
return cmp;
if (a->n > b->n)
return -1;
if (a->n < b->n)
return 1;
return 0;
} /* cmp<phf_string_t>() */
} /* Uniq:: */
} /* PHF:: */
template<typename key_t>
PHF_PUBLIC size_t PHF::uniq(key_t k[], const size_t n) {
using namespace PHF::Uniq;
size_t i, j;
qsort(k, n, sizeof *k, reinterpret_cast<int(*)(const void *, const void *)>(&cmp<key_t>));
for (i = 1, j = 0; i < n; i++) {
if (k[i] != k[j])
k[++j] = k[i];
}
return (n > 0)? j + 1 : 0;
} /* PHF::uniq() */
template size_t PHF::uniq<uint32_t>(uint32_t[], const size_t);
template size_t PHF::uniq<uint64_t>(uint64_t[], const size_t);
template size_t PHF::uniq<phf_string_t>(phf_string_t[], const size_t);
#if !PHF_NO_LIBCXX
template size_t PHF::uniq<std::string>(std::string[], const size_t);
#endif
PHF_PUBLIC size_t phf_uniq_uint32(uint32_t k[], const size_t n) {
return PHF::uniq(k, n);
} /* phf_uniq_uint32() */
PHF_PUBLIC size_t phf_uniq_uint64(uint64_t k[], const size_t n) {
return PHF::uniq(k, n);
} /* phf_uniq_uint64() */
PHF_PUBLIC size_t phf_uniq_string(phf_string_t k[], const size_t n) {
return PHF::uniq(k, n);
} /* phf_uniq_string() */
/*
* H A S H P R I M I T I V E S
*
* Universal hash based on MurmurHash3_x86_32. Variants for 32- and 64-bit
* integer keys, and string keys.
*
* We use a random seed to address the non-cryptographic-strength collision
* resistance of MurmurHash3. A stronger hash like SipHash is just too slow
* and unnecessary for my particular needs. For some environments a
* cryptographically stronger hash may be prudent.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
static inline uint32_t phf_round32(uint32_t k1, uint32_t h1) {
k1 *= UINT32_C(0xcc9e2d51);
k1 = PHF_ROTL(k1, 15);
k1 *= UINT32_C(0x1b873593);
h1 ^= k1;
h1 = PHF_ROTL(h1, 13);
h1 = h1 * 5 + UINT32_C(0xe6546b64);
return h1;
} /* phf_round32() */
static inline uint32_t phf_round32(const unsigned char *p, size_t n, uint32_t h1) {
uint32_t k1;
while (n >= 4) {
k1 = (p[0] << 24)
| (p[1] << 16)
| (p[2] << 8)
| (p[3] << 0);
h1 = phf_round32(k1, h1);
p += 4;
n -= 4;
}
k1 = 0;
switch (n & 3) {
case 3:
k1 |= p[2] << 8;
/* FALLTHRU */
case 2:
k1 |= p[1] << 16;
/* FALLTHRU */
case 1:
k1 |= p[0] << 24;
h1 = phf_round32(k1, h1);
}
return h1;
} /* phf_round32() */
static inline uint32_t phf_round32(phf_string_t k, uint32_t h1) {
return phf_round32(reinterpret_cast<const unsigned char *>(k.p), k.n, h1);
} /* phf_round32() */
#if !PHF_NO_LIBCXX
static inline uint32_t phf_round32(std::string k, uint32_t h1) {
return phf_round32(reinterpret_cast<const unsigned char *>(k.c_str()), k.length(), h1);
} /* phf_round32() */
#endif
static inline uint32_t phf_mix32(uint32_t h1) {
h1 ^= h1 >> 16;
h1 *= UINT32_C(0x85ebca6b);
h1 ^= h1 >> 13;
h1 *= UINT32_C(0xc2b2ae35);
h1 ^= h1 >> 16;
return h1;
} /* phf_mix32() */
/*
* g(k) & f(d, k) S P E C I A L I Z A T I O N S
*
* For every key we first calculate g(k). Then for every group of collisions
* from g(k) we search for a displacement value d such that f(d, k) places
* each key into a unique hash slot.
*
* g() and f() are specialized for 32-bit, 64-bit, and string keys.
*
* g_mod_r() and f_mod_n() are specialized for the method of modular
* reduction--modular division or bitwise AND. bitwise AND is substantially
* faster than modular division, and more than makes up for any space
* inefficiency, particularly for small hash tables.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* 32-bit, phf_string_t, and std::string keys */
template<typename T>
static inline uint32_t phf_g(T k, uint32_t seed) {
uint32_t h1 = seed;
h1 = phf_round32(k, h1);
return phf_mix32(h1);
} /* phf_g() */
template<typename T>
static inline uint32_t phf_f(uint32_t d, T k, uint32_t seed) {
uint32_t h1 = seed;
h1 = phf_round32(d, h1);
h1 = phf_round32(k, h1);
return phf_mix32(h1);
} /* phf_f() */
/* 64-bit keys */
static inline uint32_t phf_g(uint64_t k, uint32_t seed) {
uint32_t h1 = seed;
h1 = phf_round32(static_cast<uint32_t>(k), h1);
h1 = phf_round32(static_cast<uint32_t>(k >> 32), h1);
return phf_mix32(h1);
} /* phf_g() */
static inline uint32_t phf_f(uint32_t d, uint64_t k, uint32_t seed) {
uint32_t h1 = seed;
h1 = phf_round32(d, h1);
h1 = phf_round32(static_cast<uint32_t>(k), h1);
h1 = phf_round32(static_cast<uint32_t>(k >> 32), h1);
return phf_mix32(h1);
} /* phf_f() */
/* g() and f() which parameterize modular reduction */
template<bool nodiv, typename T>
static inline uint32_t phf_g_mod_r(T k, uint32_t seed, size_t r) {
return (nodiv)? (phf_g(k, seed) & (r - 1)) : (phf_g(k, seed) % r);
} /* phf_g_mod_r() */
template<bool nodiv, typename T>
static inline uint32_t phf_f_mod_m(uint32_t d, T k, uint32_t seed, size_t m) {
return (nodiv)? (phf_f(d, k, seed) & (m - 1)) : (phf_f(d, k, seed) % m);
} /* phf_f_mod_m() */
/*
* B U C K E T S O R T I N G I N T E R F A C E S
*
* For every key [0..n) we calculate g(k) % r, where 0 < r <= n, and
* associate it with a bucket [0..r). We then sort the buckets in decreasing
* order according to the number of keys. The sorting is required for both
* optimal time complexity when calculating f(d, k) (less contention) and
* optimal space complexity (smaller d).
*
* The actual sorting is done in the core routine. The buckets are organized
* and sorted as a 1-dimensional array to minimize run-time memory (less
* data structure overhead) and improve data locality (less pointer
* indirection). The following section merely implements a templated
* bucket-key structure and the comparison routine passed to qsort(3).
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
static bool operator==(const phf_string_t &a, const phf_string_t &b) {
return a.n == b.n && 0 == memcmp(a.p, b.p, a.n);
}
template<typename T>
struct phf_key {
T k;
phf_hash_t g; /* result of g(k) % r */
size_t *n; /* number of keys in bucket g */
}; /* struct phf_key */
template<typename T>
static int phf_keycmp(const phf_key<T> *a, const phf_key<T> *b) {
if (*(a->n) > *(b->n))
return -1;
if (*(a->n) < *(b->n))
return 1;
if (a->g > b->g)
return -1;
if (a->g < b->g)
return 1;
/* duplicate key? */
if (a->k == b->k && a != b) {
assert(!(a->k == b->k));
abort(); /* if NDEBUG defined */
}
return 0;
} /* phf_keycmp() */
/*
* C O R E F U N C T I O N G E N E R A T O R
*
* The entire algorithm is contained in PHF:init. Everything else in this
* source file is either a simple utility routine used by PHF:init, or an
* interface to PHF:init or the generated function state.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
template<typename key_t, bool nodiv>
PHF_PUBLIC int PHF::init(struct phf *phf, const key_t k[], const size_t n, const size_t l, const size_t a, const phf_seed_t seed) {
size_t n1 = PHF_MAX(n, 1); /* for computations that require n > 0 */
size_t l1 = PHF_MAX(l, 1);
size_t a1 = PHF_MAX(PHF_MIN(a, 100), 1);
size_t r; /* number of buckets */
size_t m; /* size of output array */
phf_key<key_t> *B_k = NULL; /* linear bucket-slot array */
size_t *B_z = NULL; /* number of slots per bucket */
phf_key<key_t> *B_p, *B_pe;
phf_bits_t *T = NULL; /* bitmap to track index occupancy */
phf_bits_t *T_b; /* per-bucket working bitmap */
size_t T_n;
uint32_t *g = NULL; /* displacement map */
uint32_t d_max = 0; /* maximum displacement value */
int error;
phf->nodiv = nodiv;
if (phf->nodiv) {
/* round to power-of-2 so we can use bit masks instead of modulo division */
r = phf_powerup(n1 / PHF_MIN(l1, n1));
m = phf_powerup((n1 * 100) / a1);
} else {
r = phf_primeup(PHF_HOWMANY(n1, l1));
/* XXX: should we bother rounding m to prime number for small n? */
m = phf_primeup((n1 * 100) / a1);
}
if (r == 0 || m == 0)
return ERANGE;
B_k = static_cast<phf_key<key_t> *>(calloc(n1, sizeof *B_k));
if (!B_k)
goto syerr;
B_z = static_cast<size_t *>(calloc(r, sizeof *B_z));
if (!B_z)
goto syerr;
for (size_t i = 0; i < n; i++) {
phf_hash_t gt = phf_g_mod_r<nodiv>(k[i], seed, r);
B_k[i].k = k[i];
B_k[i].g = gt;
B_k[i].n = &B_z[gt];
++*B_k[i].n;
}
qsort(B_k, n1, sizeof *B_k, reinterpret_cast<int(*)(const void *, const void *)>(&phf_keycmp<key_t>));
T_n = PHF_HOWMANY(m, PHF_BITS(*T));
T = static_cast<phf_bits_t *>(calloc(T_n * 2, sizeof *T));
if (!T)
goto syerr;
T_b = &T[T_n]; /* share single allocation */
/*
* FIXME: T_b[] is unnecessary. We could clear T[] the same way we
* clear T_b[]. In fact, at the end of generation T_b[] is identical
* to T[] because we don't clear T_b[] on success.
*
* We just need to tweak the current reset logic to stop before the
* key that failed, and then we can elide the commit to T[] at the
* end of the outer loop.
*/
g = static_cast<uint32_t *>(calloc(r, sizeof *g));
if (!g)
goto syerr;
B_p = B_k;
B_pe = &B_k[n];
for (; B_p < B_pe && *B_p->n > 0; B_p += *B_p->n) {
phf_key<key_t> *Bi_p, *Bi_pe;
size_t d = 0;
uint32_t f;
retry:
d++;
Bi_p = B_p;
Bi_pe = B_p + *B_p->n;
for (; Bi_p < Bi_pe; Bi_p++) {
f = phf_f_mod_m<nodiv>((uint32_t)d, Bi_p->k, (uint32_t)seed, m);
if (phf_isset(T, f) || phf_isset(T_b, f)) {
/* reset T_b[] */
for (Bi_p = B_p; Bi_p < Bi_pe; Bi_p++) {
f = phf_f_mod_m<nodiv>((uint32_t)d, Bi_p->k, (uint32_t)seed, m);
phf_clrbit(T_b, f);
}
goto retry;
} else {
phf_setbit(T_b, f);
}
}
/* commit to T[] */
for (Bi_p = B_p; Bi_p < Bi_pe; Bi_p++) {
f = phf_f_mod_m<nodiv>((uint32_t)d, Bi_p->k, (uint32_t)seed, m);
phf_setbit(T, f);
}
/* commit to g[] */
g[B_p->g] = (uint32_t)d;
d_max = PHF_MAX((uint32_t)d, d_max);
}
phf->seed = seed;
phf->r = r;
phf->m = m;
phf->g = g;
g = NULL;
phf->d_max = d_max;
phf->g_op = (nodiv)? phf::PHF_G_UINT32_BAND_R : phf::PHF_G_UINT32_MOD_R;
phf->g_jmp = NULL;
error = 0;
goto clean;
syerr:
error = errno;
clean:
free(g);
free(T);
free(B_z);
free(B_k);
return error;
} /* PHF::init() */
/*
* D I S P L A C E M E N T M A P C O M P A C T I O N
*
* By default the displacement map is an array of uint32_t. This routine
* compacts the map by using the smallest primitive type that will fit the
* largest displacement value.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
template<typename dst_t, typename src_t>
static inline void phf_memmove(dst_t *dst, src_t *src, size_t n) {
for (size_t i = 0; i < n; i++) {
dst_t tmp = (dst_t)src[i];
dst[i] = tmp;
}
} /* phf_memmove() */
PHF_PUBLIC void PHF::compact(struct phf *phf) {
size_t size = 0;
void *tmp;
switch (phf->g_op) {
case phf::PHF_G_UINT32_MOD_R:
case phf::PHF_G_UINT32_BAND_R:
break;
default:
return; /* already compacted */
}
if (phf->d_max <= 255) {
phf_memmove(reinterpret_cast<uint8_t *>(phf->g), reinterpret_cast<uint32_t *>(phf->g), phf->r);
phf->g_op = (phf->nodiv)? phf::PHF_G_UINT8_BAND_R : phf::PHF_G_UINT8_MOD_R;
size = sizeof (uint8_t);
} else if (phf->d_max <= 65535) {
phf_memmove(reinterpret_cast<uint16_t *>(phf->g), reinterpret_cast<uint32_t *>(phf->g), phf->r);
phf->g_op = (phf->nodiv)? phf::PHF_G_UINT16_BAND_R : phf::PHF_G_UINT16_MOD_R;
size = sizeof (uint16_t);
} else {
return; /* nothing to compact */
}
/* simply keep old array if realloc fails */
tmp = realloc(phf->g, phf->r * size);
if (tmp != 0)
phf->g = static_cast<uint32_t *>(tmp);
} /* PHF::compact() */
/*
* F U N C T I O N G E N E R A T O R & S T A T E I N T E R F A C E S
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
template int PHF::init<uint32_t, true>(struct phf *, const uint32_t[], const size_t, const size_t, const size_t, const phf_seed_t);
template int PHF::init<uint64_t, true>(struct phf *, const uint64_t[], const size_t, const size_t, const size_t, const phf_seed_t);
template int PHF::init<phf_string_t, true>(struct phf *, const phf_string_t[], const size_t, const size_t, const size_t, const phf_seed_t);
#if !PHF_NO_LIBCXX
template int PHF::init<std::string, true>(struct phf *, const std::string[], const size_t, const size_t, const size_t, const phf_seed_t);
#endif
template int PHF::init<uint32_t, false>(struct phf *, const uint32_t[], const size_t, const size_t, const size_t, const phf_seed_t);
template int PHF::init<uint64_t, false>(struct phf *, const uint64_t[], const size_t, const size_t, const size_t, const phf_seed_t);
template int PHF::init<phf_string_t, false>(struct phf *, const phf_string_t[], const size_t, const size_t, const size_t, const phf_seed_t);
#if !PHF_NO_LIBCXX
template int PHF::init<std::string, false>(struct phf *, const std::string[], const size_t, const size_t, const size_t, const phf_seed_t);
#endif
template<bool nodiv, typename map_t, typename key_t>
static inline phf_hash_t phf_hash_(map_t *g, key_t k, uint32_t seed, size_t r, size_t m) {
if (nodiv) {
uint32_t d = g[phf_g(k, seed) & (r - 1)];
return phf_f(d, k, seed) & (m - 1);
} else {
uint32_t d = g[phf_g(k, seed) % r];
return phf_f(d, k, seed) % m;
}
} /* phf_hash_() */
template<typename T>
PHF_PUBLIC phf_hash_t PHF::hash(struct phf *phf, T k) {
#if PHF_HAVE_COMPUTED_GOTOS && !PHF_NO_COMPUTED_GOTOS
static const void *const jmp[] = {
NULL,
&&uint8_mod_r, &&uint8_band_r,
&&uint16_mod_r, &&uint16_band_r,
&&uint32_mod_r, &&uint32_band_r,
};
goto *((phf->g_jmp)? phf->g_jmp : (phf->g_jmp = jmp[phf->g_op]));
uint8_mod_r:
return phf_hash_<false>(reinterpret_cast<uint8_t *>(phf->g), k, phf->seed, phf->r, phf->m);
uint8_band_r:
return phf_hash_<true>(reinterpret_cast<uint8_t *>(phf->g), k, phf->seed, phf->r, phf->m);
uint16_mod_r:
return phf_hash_<false>(reinterpret_cast<uint16_t *>(phf->g), k, phf->seed, phf->r, phf->m);
uint16_band_r:
return phf_hash_<true>(reinterpret_cast<uint16_t *>(phf->g), k, phf->seed, phf->r, phf->m);
uint32_mod_r:
return phf_hash_<false>(reinterpret_cast<uint32_t *>(phf->g), k, phf->seed, phf->r, phf->m);
uint32_band_r:
return phf_hash_<true>(reinterpret_cast<uint32_t *>(phf->g), k, phf->seed, phf->r, phf->m);
#else
switch (phf->g_op) {
case phf::PHF_G_UINT8_MOD_R:
return phf_hash_<false>(reinterpret_cast<uint8_t *>(phf->g), k, phf->seed, phf->r, phf->m);
case phf::PHF_G_UINT8_BAND_R:
return phf_hash_<true>(reinterpret_cast<uint8_t *>(phf->g), k, phf->seed, phf->r, phf->m);
case phf::PHF_G_UINT16_MOD_R:
return phf_hash_<false>(reinterpret_cast<uint16_t *>(phf->g), k, phf->seed, phf->r, phf->m);
case phf::PHF_G_UINT16_BAND_R:
return phf_hash_<true>(reinterpret_cast<uint16_t *>(phf->g), k, phf->seed, phf->r, phf->m);
case phf::PHF_G_UINT32_MOD_R:
return phf_hash_<false>(reinterpret_cast<uint32_t *>(phf->g), k, phf->seed, phf->r, phf->m);
case phf::PHF_G_UINT32_BAND_R:
return phf_hash_<true>(reinterpret_cast<uint32_t *>(phf->g), k, phf->seed, phf->r, phf->m);
default:
abort();
// return 0;
}
#endif
} /* PHF::hash() */
template phf_hash_t PHF::hash<uint32_t>(struct phf *, uint32_t);
template phf_hash_t PHF::hash<uint64_t>(struct phf *, uint64_t);
template phf_hash_t PHF::hash<phf_string_t>(struct phf *, phf_string_t);
#if !PHF_NO_LIBCXX
template phf_hash_t PHF::hash<std::string>(struct phf *, std::string);
#endif
PHF_PUBLIC void PHF::destroy(struct phf *phf) {
free(phf->g);
phf->g = NULL;
} /* PHF::destroy() */
PHF_PUBLIC int phf_init_uint32(struct phf *phf, const uint32_t *k, const size_t n, const size_t lambda, const size_t alpha, const phf_seed_t seed, const bool nodiv) {
if (nodiv)
return PHF::init<uint32_t, true>(phf, k, n, lambda, alpha, seed);
else
return PHF::init<uint32_t, false>(phf, k, n, lambda, alpha, seed);
} /* phf_init_uint32() */
PHF_PUBLIC int phf_init_uint64(struct phf *phf, const uint64_t *k, const size_t n, const size_t lambda, const size_t alpha, const phf_seed_t seed, const bool nodiv) {
if (nodiv)
return PHF::init<uint64_t, true>(phf, k, n, lambda, alpha, seed);
else
return PHF::init<uint64_t, false>(phf, k, n, lambda, alpha, seed);
} /* phf_init_uint64() */
PHF_PUBLIC int phf_init_string(struct phf *phf, const phf_string_t *k, const size_t n, const size_t lambda, const size_t alpha, const phf_seed_t seed, const bool nodiv) {
if (nodiv)
return PHF::init<phf_string_t, true>(phf, k, n, lambda, alpha, seed);
else
return PHF::init<phf_string_t, false>(phf, k, n, lambda, alpha, seed);
} /* phf_init_string() */
PHF_PUBLIC void phf_compact(struct phf *phf) {
PHF::compact(phf);
} /* phf_compact() */
PHF_PUBLIC phf_hash_t phf_hash_uint32(struct phf *phf, const uint32_t k) {
return PHF::hash(phf, k);
} /* phf_hash_uint32() */
PHF_PUBLIC phf_hash_t phf_hash_uint64(struct phf *phf, const uint64_t k) {
return PHF::hash(phf, k);
} /* phf_hash_uint64() */
PHF_PUBLIC phf_hash_t phf_hash_string(struct phf *phf, const phf_string_t k) {
return PHF::hash(phf, k);
} /* phf_hash_string() */
PHF_PUBLIC void phf_destroy(struct phf *phf) {
PHF::destroy(phf);
} /* phf_destroy() */
#if PHF_LUALIB
#include <time.h> /* time(2) */
#include <lua.hpp>
#if LUA_VERSION_NUM < 502
static int lua_absindex(lua_State *L, int idx) {
return (idx > 0 || idx <= LUA_REGISTRYINDEX)? idx : lua_gettop(L) + idx + 1;
} /* lua_absindex() */
#define lua_rawlen(t, index) lua_objlen(t, index)
#endif
struct phfctx {
int (*hash)(struct phf *, lua_State *, int index);
struct phf ctx;
}; /* struct phfctx */
static int phf_hash_uint32(struct phf *phf, lua_State *L, int index) {
uint32_t k = static_cast<uint32_t>(luaL_checkinteger(L, index));
lua_pushinteger(L, static_cast<lua_Integer>(PHF::hash(phf, k) + 1));
return 1;
} /* phf_hash_uint32() */
static int phf_hash_uint64(struct phf *phf, lua_State *L, int index) {
uint64_t k = static_cast<uint64_t>(luaL_checkinteger(L, index));
lua_pushinteger(L, static_cast<lua_Integer>(PHF::hash(phf, k) + 1));
return 1;
} /* phf_hash_uint64() */
static int phf_hash_string(struct phf *phf, lua_State *L, int index) {
phf_string_t k;
k.p = const_cast<char *>(luaL_checklstring(L, index, &k.n));
lua_pushinteger(L, static_cast<lua_Integer>(PHF::hash(phf, k) + 1));
return 1;
} /* phf_hash_string() */
static phf_seed_t phf_seed(lua_State *L) {
return phf_g(static_cast<uint32_t>(reinterpret_cast<intptr_t>(L)), static_cast<uint32_t>(time(NULL)));
} /* phf_seed() */
template<typename T>
static phf_error_t phf_reallocarray(T **p, size_t count) {
T *tmp;
if (SIZE_MAX / sizeof **p < count)
return ENOMEM;
if (!(tmp = static_cast<T*>(realloc(*p, count * sizeof **p))))
return errno;
*p = tmp;
return 0;
} /* phf_reallocarray() */
static phf_error_t phf_tokey(lua_State *L, int index, uint32_t *k) {
if (LUA_TNUMBER != lua_type(L, index))
return EINVAL;
#if LUA_VERSION_NUM > 502
lua_Integer v;
v = static_cast<lua_Integer>(lua_tointeger(L, index));
if (v > UINT32_MAX)
return ERANGE;
#else
lua_Number v;
v = static_cast<lua_Number>(lua_tonumber(L, index));
if (v > UINT32_MAX)
return ERANGE;
#endif
*k = static_cast<uint32_t>(v);
return 0;
} /* phf_tokey() */
static phf_error_t phf_tokey(lua_State *L, int index, uint64_t *k) {
if (LUA_TNUMBER != lua_type(L, index))
return EINVAL;
#if LUA_VERSION_NUM > 502
lua_Integer v;
v = static_cast<lua_Integer>(lua_tointeger(L, index));
#else
lua_Number v;
v = static_cast<lua_Number>(lua_tonumber(L, index));
#endif
*k = static_cast<uint64_t>(v);
return 0;
} /* phf_tokey() */
static phf_error_t phf_tokey(lua_State *L, int index, phf_string_t *k) {
if (LUA_TSTRING != lua_type(L, index))
return EINVAL;
k->p = const_cast<char *>(lua_tolstring(L, index, &k->n));
return 0;
} /* phf_tokey() */
template<typename T>
static phf_error_t phf_addkeys(lua_State *L, int index, T **keys, int *n) {
int i, error = 0;
T *p;
*n = lua_rawlen(L, index);
if ((error = phf_reallocarray(keys, *n)))
return error;
p = *keys;
for (i = 1; i <= *n; i++) {
lua_rawgeti(L, index, i);
error = phf_tokey(L, -1, p++);
lua_pop(L, 1);
if (error)
return error;
}
*n = PHF::uniq(*keys, *n);
return 0;
} /* phf_addkeys() */
static int phf_new(lua_State *L) {
size_t l = static_cast<size_t>(luaL_optinteger(L, 2, 4));
size_t a = static_cast<size_t>(luaL_optinteger(L, 3, 80));
phf_seed_t seed = (lua_isnoneornil(L, 4))? phf_seed(L) : static_cast<phf_seed_t>(luaL_checkinteger(L, 4));
bool nodiv = static_cast<bool>(lua_toboolean(L, 5));
void *keys = NULL;
struct phfctx *phf;
int n, error;
lua_settop(L, 5);
luaL_checktype(L, 1, LUA_TTABLE);
phf = static_cast<struct phfctx *>(lua_newuserdata(L, sizeof *phf));
memset(phf, 0, sizeof *phf);
luaL_getmetatable(L, "PHF*");
lua_setmetatable(L, -2);
switch ((error = phf_addkeys(L, 1, reinterpret_cast<uint32_t **>(&keys), &n))) {
case 0:
break;
case ERANGE:
goto uint64;
case EINVAL:
goto string;
default:
goto error;
}
if (n == 0)
goto empty;
if ((error = phf_init_uint32(&phf->ctx, reinterpret_cast<uint32_t *>(keys), n, l, a, seed, nodiv)))
goto error;
phf->hash = &phf_hash_uint32;
goto done;
uint64:
switch ((error = phf_addkeys(L, 1, reinterpret_cast<uint64_t **>(&keys), &n))) {
case 0:
break;
case EINVAL:
goto string;
default:
goto error;
}
if (n == 0)
goto empty;
if ((error = phf_init_uint64(&phf->ctx, reinterpret_cast<uint64_t *>(keys), n, l, a, seed, nodiv)))
goto error;
phf->hash = &phf_hash_uint64;
goto done;
string:
if ((error = phf_addkeys(L, 1, reinterpret_cast<phf_string_t **>(&keys), &n)))
goto error;
if (n == 0)
goto empty;
if ((error = phf_init_string(&phf->ctx, reinterpret_cast<phf_string_t *>(keys), n, l, a, seed, nodiv)))
goto error;
phf->hash = &phf_hash_string;
goto done;
done:
free(keys);
PHF::compact(&phf->ctx);
return 1;
empty:
free(keys);
lua_pushstring(L, "empty key set");
return lua_error(L);
error:
free(keys);
lua_pushstring(L, strerror(error));
return lua_error(L);
} /* phf_new() */
static int phf_r(lua_State *L) {
struct phfctx *phf = static_cast<struct phfctx *>(luaL_checkudata(L, 1, "PHF*"));
lua_pushinteger(L, static_cast<lua_Integer>(phf->ctx.r));
return 1;
} /* phf_r() */
static int phf_m(lua_State *L) {
struct phfctx *phf = static_cast<struct phfctx *>(luaL_checkudata(L, 1, "PHF*"));
lua_pushinteger(L, static_cast<lua_Integer>(phf->ctx.m));
return 1;
} /* phf_m() */
static int (phf_hash)(lua_State *L) {
struct phfctx *phf = static_cast<struct phfctx *>(luaL_checkudata(L, 1, "PHF*"));
return phf->hash(&phf->ctx, L, 2);
} /* phf_hash() */
static int phf__gc(lua_State *L) {
struct phfctx *phf = (struct phfctx *)luaL_checkudata(L, 1, "PHF*");
phf_destroy(&phf->ctx);
return 0;
} /* phf__gc() */
static const luaL_Reg phf_methods[] = {
{ "hash", &(phf_hash) },
{ "r", &phf_r },
{ "m", &phf_m },
{ NULL, NULL },
}; /* phf_methods[] */
static const luaL_Reg phf_metatable[] = {
{ "__call", &phf_hash },
{ "__gc", &phf__gc },
{ NULL, NULL },
}; /* phf_metatable[] */
static const luaL_Reg phf_globals[] = {
{ "new", &phf_new },
{ NULL, NULL },
}; /* phf_globals[] */
static void phf_register(lua_State *L, const luaL_Reg *l) {
#if LUA_VERSION_NUM >= 502
luaL_setfuncs(L, l, 0);
#else
luaL_register(L, NULL, l);
#endif
} /* phf_register() */
extern "C" int luaopen_phf(lua_State *L) {
if (luaL_newmetatable(L, "PHF*")) {
phf_register(L, phf_metatable);
lua_newtable(L);
phf_register(L, phf_methods);
lua_setfield(L, -2, "__index");
}
lua_pop(L, 1);
lua_newtable(L);
phf_register(L, phf_globals);
return 1;
} /* luaopen_phf() */
#endif /* PHF_LUALIB */
#if PHF_MAIN
#include <stdlib.h> /* arc4random(3) free(3) realloc(3) */
#include <stdio.h> /* fclose(3) fopen(3) fprintf(3) fread(3) freopen(3) printf(3) */
#include <time.h> /* CLOCKS_PER_SEC clock(3) */
#include <string.h> /* strcmp(3) */
#include <sys/param.h> /* BSD */
#include <unistd.h> /* getopt(3) */
#include <strings.h> /* ffsl(3) */
#include <err.h> /* err(3) errx(3) warnx(3) */
static uint32_t randomseed(void) {
#if defined BSD /* catchall for modern BSDs, which all have arc4random */
return arc4random();
#else
FILE *fp;
uint32_t seed;
if (!(fp = fopen("/dev/urandom", "r")))
err(1, "/dev/urandom");
if (1 != fread(&seed, sizeof seed, 1, fp))
err(1, "/dev/urandom");
fclose(fp);
return seed;
#endif
} /* randomseed() */
template<typename T>
static void pushkey(T **k, size_t *n, size_t *z, T kn) {
if (!(*n < *z)) {
size_t z1 = PHF_MAX(*z, 1) * 2;
T *p;
if (z1 < *z || (SIZE_MAX / sizeof **k) < z1)
errx(1, "addkey: %s", strerror(ERANGE));
if (!(p = (T *)realloc(*k, z1 * sizeof **k)))
err(1, "realloc");
*k = p;
*z = z1;
}
(*k)[(*n)++] = kn;
} /* pushkey() */
template<typename T>
static void addkey(T **k, size_t *n, size_t *z, const char *src) {
pushkey(k, n, z, static_cast<T>(strtoull(src, NULL, 0)));
} /* addkey() */
static void addkey(phf_string_t **k, size_t *n, size_t *z, char *src, size_t len) {
phf_string_t kn = { (void *)src, len };
pushkey(k, n, z, kn);
} /* addkey() */
static void addkey(phf_string_t **k, size_t *n, size_t *z, char *src) {
addkey(k, n, z, src, strlen(src));
} /* addkey() */
#if !PHF_NO_LIBCXX
static void addkey(std::string **k, size_t *n, size_t *z, char *src, size_t len) {
pushkey(k, n, z, std::string(src, len));
} /* addkey() */
static void addkey(std::string **k, size_t *n, size_t *z, char *src) {
addkey(k, n, z, src, strlen(src));
} /* addkey() */
#endif
template<typename T>
static void addkeys(T **k, size_t *n, size_t *z, char **src, int count) {
for (int i = 0; i < count; i++)
addkey(k, n, z, src[i]);
} /* addkey() */
template<typename T>
static void addkeys(T **k, size_t *n, size_t *z, FILE *fp, char **data) {
char *ln = NULL;
size_t lz = 0;
ssize_t len;
(void)data;
while ((len = getline(&ln, &lz, fp)) > 0) {
if (--len > 0) {
if (ln[len] == '\n')
ln[len] = '\0';
addkey(k, n, z, ln);
}
}
free(ln);
} /* addkeys() */
/* slurp file into a single string and take pointers */
static void addkeys(phf_string_t **k, size_t *n, size_t *z, FILE *fp, char **data) {
size_t p = 0, pe = 0, tp;
char buf[BUFSIZ], *tmp;
size_t buflen;
while ((buflen = fread(buf, 1, sizeof buf, fp))) {
if (buflen > (pe - p)) {
if (~buflen < pe || 0 == (pe = phf_powerup(buflen + pe)))
errx(1, "realloc: %s", strerror(ERANGE));
if (!(tmp = (char *)realloc(*data, pe)))
err(1, "realloc");
*data = tmp;
}
memcpy(*data + p, buf, buflen);
p += buflen;
}
for (p = 0; p < pe; ) {
while (p < pe && (*data)[p] == '\n')
p++;
tp = p;
while (p < pe && (*data)[p] != '\n')
p++;
if (p > tp)
addkey(k, n, z, &(*data)[tp], (size_t)(p - tp));
}
} /* addkeys() */
static inline void printkey(phf_string_t &k, phf_hash_t hash) {
printf("%-32.*s : %" PHF_PRIuHASH "\n", (int)k.n, (char *)k.p, hash);
} /* printkey() */
#if !PHF_NO_LIBCXX
static inline void printkey(std::string &k, phf_hash_t hash) {
printf("%-32s : %" PHF_PRIuHASH "\n", k.c_str(), hash);
} /* printkey() */
#endif
template<typename T>
static inline void printkey(T k, phf_hash_t hash) {
printf("%llu : %" PHF_PRIuHASH "\n", (unsigned long long)k, hash);
} /* printkey() */
template<typename T, bool nodiv>
static inline void exec(int argc, char **argv, size_t lambda, size_t alpha, size_t seed, bool verbose, bool noprint) {
T *k = NULL;
size_t n = 0, z = 0;
char *data = NULL;
struct phf phf;
clock_t begin, end;
addkeys(&k, &n, &z, argv, argc);
addkeys(&k, &n, &z, stdin, &data);
size_t m = PHF::uniq(k, n);
if (verbose)
warnx("loaded %zu keys (%zu duplicates)", m, (n - m));
n = m;
begin = clock();
PHF::init<T, nodiv>(&phf, k, n, lambda, alpha, seed);
end = clock();
if (verbose) {
warnx("found perfect hash for %zu keys in %fs", n, (double)(end - begin) / CLOCKS_PER_SEC);
begin = clock();
PHF::compact(&phf);
end = clock();
warnx("compacted displacement map in %fs", (double)(end - begin) / CLOCKS_PER_SEC);
int d_bits = ffsl((long)phf_powerup(phf.d_max));
double k_bits = ((double)phf.r * d_bits) / n;
double g_load = (double)n / phf.r;
warnx("r:%zu m:%zu d_max:%zu d_bits:%d k_bits:%.2f g_load:%.2f", phf.r, phf.m, phf.d_max, d_bits, k_bits, g_load);
size_t x = 0;
begin = clock();
for (size_t i = 0; i < n; i++) {
x += PHF::hash(&phf, k[i]);
}
end = clock();
warnx("hashed %zu keys in %fs (x:%zu)", n, (double)(end - begin) / CLOCKS_PER_SEC, x);
}
if (!noprint) {
for (size_t i = 0; i < n; i++) {
printkey(k[i], PHF::hash(&phf, k[i]));
}
}
phf_destroy(&phf);
free(data);
free(k);
} /* exec() */
static void printprimes(int argc, char **argv) {
intmax_t n = 0, m = UINT32_MAX;
char *end;
if (argc > 0) {
n = strtoimax(argv[0], &end, 0);
if (end == argv[0] || *end != '\0' || n < 0 || n > UINT32_MAX)
errx(1, "%s: invalid number", argv[0]);
n = PHF_MAX(n, 2);
}
if (argc > 1) {
m = strtoimax(argv[1], &end, 0);
if (end == argv[1] || *end != '\0' || m < n || m > UINT32_MAX)
errx(1, "%s: invalid number", argv[1]);
}
for (; n <= m; n++) {
if (phf_isprime(n))
printf("%" PRIdMAX "\n", n);
}
} /* printprimes() */
int main(int argc, char **argv) {
const char *path = "/dev/null";
size_t lambda = 4;
size_t alpha = 80;
uint32_t seed = randomseed();
bool verbose = 0;
bool noprint = 0;
bool nodiv = 0;
enum {
PHF_UINT32,
PHF_UINT64,
PHF_STRING,
#if !PHF_NO_LIBCXX
PHF_STD_STRING
#endif
} type = PHF_UINT32;
bool primes = 0;
extern char *optarg;
extern int optind;
int optc;
while (-1 != (optc = getopt(argc, argv, "f:l:a:s:2t:nvph"))) {
switch (optc) {
case 'f':
path = optarg;
break;
case 'l':
lambda = strtoul(optarg, NULL, 0);
break;
case 'a':
alpha = strtoul(optarg, NULL, 0);
break;
case 's':
seed = strtoul(optarg, NULL, 0);
break;
case '2':
nodiv = 1;
break;
case 't':
if (!strcmp(optarg, "uint32")) {
type = PHF_UINT32;
} else if (!strcmp(optarg, "uint64")) {
type = PHF_UINT64;
} else if (!strcmp(optarg, "string")) {
type = PHF_STRING;
#if !PHF_NO_LIBCXX
} else if (!strcmp(optarg, "std::string")) {
type = PHF_STD_STRING;
#endif
} else {
errx(1, "%s: invalid key type", optarg);
}
break;
case 'n':
noprint = 1;
break;
case 'v':
verbose = 1;
break;
case 'p':
primes = 1;
break;
case 'h':
/* FALL THROUGH */
default:
fprintf(optc == 'h'? stdout : stderr,
"%s [-f:l:a:s:t:2nvph] [key [...]]\n"
" -f PATH read keys from PATH (- for stdin)\n"
" -l NUM number of keys per displacement map bucket (reported as g_load)\n"
" -a PCT hash table load factor (1%% - 100%%)\n"
" -s SEED random seed\n"
" -t TYPE parse and hash keys as uint32, uint64, or string\n"
" -2 avoid modular division by rounding r and m to power of 2\n"
" -n do not print key-hash pairs\n"
" -v report hashing status\n"
" -p operate like primes(3) utility\n"
" -h print usage message\n"
"\n"
"Report bugs to <william@25thandClement.com>\n",
argv[0]
);
return optc == 'h'? 0 : 1;
}
}
argc -= optind;
argv += optind;
if (primes)
return printprimes(argc, argv), 0;
if (strcmp(path, "-") && !freopen(path, "r", stdin))
err(1, "%s", path);
switch (type) {
case PHF_UINT32:
if (nodiv)
exec<uint32_t, true>(argc, argv, lambda, alpha, seed, verbose, noprint);
else
exec<uint32_t, false>(argc, argv, lambda, alpha, seed, verbose, noprint);
break;
case PHF_UINT64:
if (nodiv)
exec<uint64_t, true>(argc, argv, lambda, alpha, seed, verbose, noprint);
else
exec<uint64_t, false>(argc, argv, lambda, alpha, seed, verbose, noprint);
break;
case PHF_STRING:
if (nodiv)
exec<phf_string_t, true>(argc, argv, lambda, alpha, seed, verbose, noprint);
else
exec<phf_string_t, false>(argc, argv, lambda, alpha, seed, verbose, noprint);
break;
#if !PHF_NO_LIBCXX
case PHF_STD_STRING:
if (nodiv)
exec<std::string, true>(argc, argv, lambda, alpha, seed, verbose, noprint);
else
exec<std::string, false>(argc, argv, lambda, alpha, seed, verbose, noprint);
break;
#endif
}
return 0;
} /* main() */
#endif /* PHF_MAIN */
```
|
```powershell
function New-LWVHDX
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[Cmdletbinding()]
Param (
#Path to reference VHD
[Parameter(Mandatory = $true)]
[string]$VhdxPath,
#Size of the reference VHD
[Parameter(Mandatory = $true)]
[int]$SizeInGB,
[string]$Label,
[switch]$UseLargeFRS,
[char]$DriveLetter,
[long]$AllocationUnitSize,
[string]$PartitionStyle,
[switch]$SkipInitialize
)
Write-LogFunctionEntry
$PSBoundParameters.Add('ProgressIndicator', 1) #enables progress indicator
$VmDisk = New-VHD -Path $VhdxPath -SizeBytes ($SizeInGB * 1GB) -ErrorAction Stop
Write-ProgressIndicator
Write-PSFMessage "Created VHDX file '$($vmDisk.Path)'"
if ($SkipInitialize)
{
Write-PSFMessage -Message "Skipping the initialization of '$($vmDisk.Path)'"
Write-LogFunctionExit
return
}
$mountedVhd = $VmDisk | Mount-VHD -PassThru
Write-ProgressIndicator
if ($DriveLetter)
{
$Label += "_AL_$DriveLetter"
}
$formatParams = @{
FileSystem = 'NTFS'
NewFileSystemLabel = 'Data'
Force = $true
Confirm = $false
UseLargeFRS = $UseLargeFRS
AllocationUnitSize = $AllocationUnitSize
}
if ($Label)
{
$formatParams.NewFileSystemLabel = $Label
}
$mountedVhd | Initialize-Disk -PartitionStyle $PartitionStyle
$mountedVhd | New-Partition -UseMaximumSize -AssignDriveLetter |
Format-Volume @formatParams |
Out-Null
Write-ProgressIndicator
$VmDisk | Dismount-VHD
Write-LogFunctionExit
}
```
|
Thalavattam is a 1986 Indian Malayalam-language drama film written and directed by Priyadarshan, starring Mohanlal, Lizy, M. G. Soman and Karthika. The film is very loosely based on the 1975 movie One Flew Over the Cuckoo's Nest which was an adaptation of the 1962 novel of the same name by Ken Kesey. The film features songs composed by Raghu Kumar and C. Rajamani, and a score by Johnson. The story follows Vinod, an eccentric new patient at a mental asylum.
The film was remade in Hindi as Kyon Ki (2005) by Priyadarshan and in Tamil as Manasukkul Mathappu (1988) by Robert–Rajasekar.
Plot
Vinod becomes mentally ill after his girlfriend Anitha dies due to an electric short circuit accident during a rock concert. Vinod is admitted to a mental hospital managed by Dr. Ravindran, in Ooty. Dr Ravindran is aggressive and a sadist who has a dislike for Vinod.
With the help of Dr. Savithri, who is Dr. Ravindran's daughter, and Dr. Unnikrishnan, a very old and close acquaintance of Vinod from his childhood, he slowly regains his memory and mental equilibrium. Savithri and Vinod fall in love. Dr. Ravindran has already arranged Savithri's marriage with Hari and so he opposes the lovers.
When he finds that Savithri and Vinod are adamant, Dr. Ravindran lobotomises Vinod and puts him in a state of coma. Dr. Unnikrishnan feels that death would be preferable over a vegetative life and kills Vinod. He confronts Dr. Ravindran and confesses to the euthanasia. Savithri overhears the conversation, and loses her mental equilibrium. She is admitted into the same institution as a patient.
Cast
Mohanlal as Vinod Kumar ('Vinu') a mental patient and protagonist of film
Mukesh as Hari ('Chukkan'), Savithri's cousin
Nedumudi Venu as Dr. Unnikrishnan ('Unniettan')
M. G. Soman as Dr. Ravindran Varma, a cruel and aggressive man who has a hatred against Vinod
Karthika as Savithri, Dr. Ravindran's daughter, and Vinod's new new girlfriend
Lizy as Anitha, Vinod's Girlfriend
Jagathi Sreekumar as Narayanan
Cochin Haneefa as Antony, an Aggressive Hospital Attendant
Sukumari as Nurse Rachel
G. P. Vijayakumar as Satheesh, Vinod's brother
K. P. A. C. Sunny as Retd. Judge Melepattil Govindan Kumar, Vinod's father
KPAC Lalitha as Subhadra kunjamma, a Mental Patient
Thikkurissy Sukumaran Nair as 'Appoopan', a Mental Patient
Maniyanpilla Raju as Joseph, a Mental Patient
Sankaradi as Thirumeni, a Mental Patient
Soundtrack
Reception
In 2002, comparing the film to One Flew over the Cuckoo's Nest, S. Santosh of The Hindu wrote, "Director Priyadarsan's syrupy Malayalam adaptation of the classic, Thalavattam, saw Mohanlal in his usual mainstream self. Had he seen the film, even Jack Nicholson would have been surprised: after all, the Hollywood actor has not mastered the art of running around trees."
Thalavattam was released in Kerala in 12 centres on 10 locations. The film performed well at the box office, becoming one the highest-grossing Malayalam films of the year. It was made on a shoestring budget of ₹20 lakh. The film ran over 100 days in theatres.
Remakes
Thalavattam was remade in Hindi as Kyon Ki directed by Priyadarshan himself in 2005. The film was also remade in Tamil in 1988 by Robert–Rajasekar as Manasukkul Mathappu, with Prabhu and Saranya playing the lead also remade in Bengali Bangladesh in 2010 by F. I. Manik as Chirodin Ami Tomar, with Riaz, Purnima and Rumana.
References
External links
1986 films
1980s Malayalam-language films
Indian drama films
Films set in psychiatric hospitals
Films shot in Ooty
Malayalam films remade in other languages
Films scored by Raghu Kumar
Films scored by Rajamani
Films directed by Priyadarshan
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.