content
stringlengths
0
181M
language
stringclasses
54 values
defmodule PhoenixChat.RoomChannel do use PhoenixChat.Web, :channel alias PhoenixChat.Presence def join("room:lobby", _, socket) do send self(), :after_join {:ok, socket} end def handle_info(:after_join, socket) do Presence.track(socket, socket.assigns.user, %{ online_at: :os.system_time(:millisecond) }) push socket, "presence_state", Presence.list(socket) {:noreply, socket} end def handle_in("message:new", message, socket) do broadcast! socket, "message:new", %{ user: socket.assigns.user, body: message, timestamp: :os.system_time(:millisecond) } {:noreply, socket} end end
Elixir
require 'test_helper' class BeersControllerTest < ActionDispatch::IntegrationTest test "should get create" do get beers_create_url assert_response :success end end
Ruby
import XCTest import Nimble @testable import StravaKit final class ActivityTests: XCTestCase { func test_decode_activity() throws { let jsonData = activityWithGpsJson.data(using: .utf8)! let activity = try JSONDecoder().decode(Activity.self, from: jsonData) expect(activity.id) == 8529483 expect(activity.name) == "08/23/2013 Oakland, CA" expect(activity.distance) == 32486.1 expect(activity.movingTime) == 5241 expect(activity.elapsedTime) == 5427 expect(activity.totalElevationGain) == 566.0 expect(activity.type) == "Ride" expect(activity.startDate) == "2013-08-24T00:04:12Z" expect(activity.localStartDate) == "2013-08-23T17:04:12Z" expect(activity.localTimeZone) == "(GMT-08:00) America/Los_Angeles" expect(activity.utcOffset) == -28800 expect(activity.map?.summaryPolyline) == "cetewLja@zYcG" expect(activity.isStaticTrainer) == false expect(activity.isCommute) == false expect(activity.isManual) == false expect(activity.averageSpeed) == 3.4 expect(activity.maxSpeed) == 4.514 expect(activity.averageHeartRate) == 138.8 expect(activity.maxHeartRate) == 179.0 } func test_decode_activity_with_no_gps() throws { let jsonData = activityWithNoGpsJson.data(using: .utf8)! let activity = try JSONDecoder().decode(Activity.self, from: jsonData) expect(activity.id) == 8529483 expect(activity.name) == "08/23/2013 Oakland, CA" expect(activity.distance) == 32486.1 expect(activity.movingTime) == 5241 expect(activity.elapsedTime) == 5427 expect(activity.totalElevationGain) == 566.0 expect(activity.type) == "Ride" expect(activity.startDate) == "2013-08-24T00:04:12Z" expect(activity.localStartDate) == "2013-08-23T17:04:12Z" expect(activity.localTimeZone) == "(GMT-08:00) America/Los_Angeles" expect(activity.utcOffset) == -28800 expect(activity.map?.summaryPolyline).to(beNil()) expect(activity.isStaticTrainer) == false expect(activity.isCommute) == false expect(activity.isManual) == false expect(activity.averageSpeed) == 3.4 expect(activity.maxSpeed) == 4.514 expect(activity.averageHeartRate) == 138.8 expect(activity.maxHeartRate) == 179.0 } func test_encode_activity() throws { let jsonData = activityWithNoGpsJson.data(using: .utf8)! let activity = try JSONDecoder().decode(Activity.self, from: jsonData) let encoded = try JSONEncoder().encode(activity) let decoded = try JSONDecoder().decode(Activity.self, from: encoded) expect(decoded) == activity } func test_encode_activity_with_no_gps() throws { let jsonData = activityWithNoGpsJson.data(using: .utf8)! let activity = try JSONDecoder().decode(Activity.self, from: jsonData) let encoded = try JSONEncoder().encode(activity) let decoded = try JSONDecoder().decode(Activity.self, from: encoded) expect(decoded) == activity } } fileprivate extension ActivityTests { var activityWithGpsJson: String { return """ { "id": 8529483, "resource_state": 2, "external_id": "2013-08-23-17-04-12.fit", "upload_id": 84130503, "athlete": { "id": 227615, "resource_state": 1 }, "name": "08/23/2013 Oakland, CA", "distance": 32486.1, "moving_time": 5241, "elapsed_time": 5427, "total_elevation_gain": 566.0, "type": "Ride", "start_date": "2013-08-24T00:04:12Z", "start_date_local": "2013-08-23T17:04:12Z", "timezone": "(GMT-08:00) America/Los_Angeles", "utc_offset" : -28800, "start_latlng": [ 37.793551, -122.2686 ], "end_latlng": [ 37.792836, -122.268287 ], "location_city": "Oakland", "location_state": "CA", "location_country": "United States", "achievement_count": 8, "kudos_count": 0, "comment_count": 0, "athlete_count": 1, "photo_count": 0, "total_photo_count": 0, "map": { "id": "a77175935", "summary_polyline": "cetewLja@zYcG", "resource_state": 2 }, "trainer": false, "commute": false, "manual": false, "private": false, "flagged": false, "average_speed": 3.4, "max_speed": 4.514, "average_watts": 163.6, "weighted_average_watts": 200, "kilojoules": 857.6, "device_watts": true, "average_heartrate": 138.8, "max_heartrate": 179.0 } """ } var activityWithNoGpsJson: String { return """ { "id": 8529483, "resource_state": 2, "external_id": "2013-08-23-17-04-12.fit", "upload_id": 84130503, "athlete": { "id": 227615, "resource_state": 1 }, "name": "08/23/2013 Oakland, CA", "distance": 32486.1, "moving_time": 5241, "elapsed_time": 5427, "total_elevation_gain": 566.0, "type": "Ride", "start_date": "2013-08-24T00:04:12Z", "start_date_local": "2013-08-23T17:04:12Z", "timezone": "(GMT-08:00) America/Los_Angeles", "utc_offset" : -28800, "start_latlng": null, "end_latlng": null, "location_city": "Oakland", "location_state": "CA", "location_country": "United States", "achievement_count": 8, "kudos_count": 0, "comment_count": 0, "athlete_count": 1, "photo_count": 0, "total_photo_count": 0, "map": { "id": "a77175935", "summary_polyline": null, "resource_state": 2 }, "trainer": false, "commute": false, "manual": false, "private": false, "flagged": false, "average_speed": 3.4, "max_speed": 4.514, "average_watts": 163.6, "weighted_average_watts": 200, "kilojoules": 857.6, "device_watts": true, "average_heartrate": 138.8, "max_heartrate": 179.0 } """ } }
Swift
%@doc A minimun implementation of HiSLIP 1.0. -module(hislip_gpib). -export([open/3, close/1, send/2, read/1]). -record(hislip_state, { server, sync, async, sync_recv = <<>>, async_recv = <<>>, session, msg_cnt = 16#ffffff00, msg_acc = <<>>, data, overlap }). -define(HISLIP_VER, 16#0100). -define(HISLIP_PORT, 4880). %@doc Open raw tcp connection on Host % ServerPid is used for receiving strings from Host, if set as 'undefined', then io:format is used. -spec open(IP :: string(), Name :: string(), ServerPid :: pid() | undefined) -> {ok, pid()} | {error, Reason :: any()}. open(IP, Name, ServerPid) -> open(IP, ?HISLIP_PORT, Name, ServerPid). -define('Initialize', 0). -define('InitializeResponse', 1). -define('FatalError', 2). -define('Error', 3). -define('AsyncLock', 4). -define('AsyncLockResponse', 5). -define('Data', 6). -define('DataEnd', 7). -define('DeviceClearComplete', 8). -define('DeviceClearAcknowledge', 9). -define('AsyncRemoteLocalControl', 10). -define('AsyncRemoteLocalResponse', 11). -define('Trigger', 12). -define('Interrupted', 13). -define('AsyncInterrupted', 14). -define('AsyncMaximumMessageSize', 15). -define('AsyncMaximumMessageSizeResponse', 16). -define('AsyncInitialize', 17). -define('AsyncInitializeResponse', 18). -define('AsyncDeviceClear', 19). -define('AsyncServiceRequest', 20). -define('AsyncStatusQuery', 21). -define('AsyncStatusResponse', 22). -define('AsyncDeviceClearAcknowledge', 23). -define('AsyncLockInfo', 24). -define('AsyncLockInfoResponse', 25). open(IP, Port, Name, ServerPid) -> Ref = make_ref(), Self = self(), Pid = spawn_link(fun () -> process_flag(trap_exit, true), {ok, SSocket} = gen_tcp:connect(IP, Port, [binary]), S = length(Name), B = list_to_binary(Name), Msg = <<$H, $S, ?'Initialize', 0, ?HISLIP_VER:16, 0:16, S:64, B/binary>>, ok = gen_tcp:send(SSocket, Msg), initialize(#hislip_state{server = ServerPid, sync = SSocket}, Self, Ref) end), receive {ok, Ref} -> {ok, Pid} after 5000 -> {error, econn} end. close(Pid) -> Pid ! close. send(Pid, Msg) when is_list(Msg) -> send(Pid, list_to_binary(Msg ++ "\n")); send(Pid, Msg) when is_binary(Msg) -> Pid ! {send, Msg}. read(_Pid) -> ok. initialize(#hislip_state{sync = SSocket, async = ASocket, sync_recv = SRecv, async_recv = ARecv} = State, Pid, Ref) -> receive {tcp, SSocket, Data} -> %dbg(Data), {ok, SRecv10} = handle_message(<<SRecv/binary, Data/binary>>, self(), SSocket), initialize(State#hislip_state{sync_recv = SRecv10}, Pid, Ref); {tcp, ASocket, Data} -> {ok, ARecv10} = handle_message(<<ARecv/binary, Data/binary>>, self(), ASocket), initialize(State#hislip_state{async_recv = ARecv10}, Pid, Ref); {msg, SSocket, <<?'InitializeResponse', Overlap, _ServerVer:16, SessionID:16>>, <<>>} -> Msg2 = <<$H, $S, ?'AsyncInitialize', 0, SessionID:32, 0:64>>, {ok, {Address, Port}} = inet:peername(SSocket), {ok, ASocket10} = gen_tcp:connect(Address, Port, [binary]), ok = gen_tcp:send(ASocket10, Msg2), initialize(State#hislip_state{async = ASocket10, session = SessionID, overlap = Overlap}, Pid, Ref); {msg, ASocket, <<?'AsyncInitializeResponse', 0, _VendorID:32>>, <<>>} -> %dbg("connected"), Pid ! {ok, Ref}, loop(State); {msg, _Socket, <<?'FatalError', Code, 0:32>>, ErrMsg} -> exit({hislip_fatal, {Code, ErrMsg}}) end. loop(#hislip_state{server = ServerPid, sync = SSocket, async = ASocket, sync_recv = SRecv, async_recv = ARecv, msg_cnt = Counter} = State) -> receive {send, L} -> S = size(L), B = <<$H, $S, ?'DataEnd', 1, Counter:32, S:64, L/binary>>, ok = gen_tcp:send(SSocket, B), loop(State#hislip_state{msg_cnt = (Counter + 2) band 16#FFFFFFFF}); stop -> ok = gen_tcp:close(ASocket), ok = gen_tcp:close(SSocket); {tcp, SSocket, Data} -> {ok, SRecv10} = handle_message(<<SRecv/binary, Data/binary>>, self(), SSocket), loop(State#hislip_state{sync_recv = SRecv10}); {tcp, ASocket, Data} -> {ok, ARecv10} = handle_message(<<ARecv/binary, Data/binary>>, self(), ASocket), loop(State#hislip_state{async_recv = ARecv10}); {msg, SSocket, <<?'Data', 0, _MsgCnt:32>>, Msg} -> Old = State#hislip_state.msg_acc, MsgAcc = <<Old/binary, Msg/binary>>, loop(State#hislip_state{msg_acc = MsgAcc}); {msg, SSocket, <<?'DataEnd', 0, _MsgCnt:32>>, Msg} -> Old = State#hislip_state.msg_acc, MsgAcc = binary_to_list(<<Old/binary, Msg/binary>>), case is_pid(ServerPid) of true -> gen_server:cast(ServerPid, {gpib_read, self(), MsgAcc}); _ -> io:format("~p~n", [MsgAcc]) end, loop(State#hislip_state{msg_acc = <<>>}); {msg, _Socket, <<?'FatalError', Code, 0:32>>, ErrMsg} -> throw({fatal, {Code, ErrMsg}}); {msg, _Socket, MsgHeader, Msg} -> throw({unknown, MsgHeader, Msg}); {tcp_closed, SSocket} -> gen_tcp:close(ASocket), exit(tcp_closed); {tcp_closed, ASocket} -> gen_tcp:close(SSocket), exit(tcp_closed); {tcp_error, _Socket, _Reason} -> gen_tcp:close(SSocket), gen_tcp:close(ASocket), exit(tcp_error) end. handle_message(<<$H, $S, MessageId, Ctrl, Param:32, Len:64, Bin/binary>> = Data, Pid, Socket) -> case Bin of <<X:Len/binary, B/binary>> -> Pid ! {msg, Socket, <<MessageId, Ctrl, Param:32>>, X}, handle_message(B, Pid, Socket); _ -> {ok, Data} end; handle_message(<<>>, _Pid, _Socket) -> {ok, <<>>}; handle_message(<<X, _Bin/binary>> = _Data, _Pid, _Socket) when X /= $H -> error. dbg(Term) -> io:format("~p~n", [Term]).
Erlang
module Generator where import Data.Word (Word64) import Core (permutate) import Hash (hash64U) data Generator a = Generator { card :: Word64 , unrank :: Word64 -> a , runGen :: Word64 -> Word64 -> a } instance Functor Generator where fmap f (Generator c u rg) = Generator c (f . u) (\s n -> f $ rg s n) instance Applicative Generator where pure x = Generator 1 (const x) (const $ const x) Generator cl ul rgl <*> Generator cr ur rgr = Generator c u rg where c = cl * cr u n = ul n (ur n) rg s n = rgl s n (rgr s n) instance Monad Generator where Generator c u rg >>= f = Generator c ub rgb where Generator cb ub rgb = f (u c) -- COMBINATORS -- | Generate value v, where lb <= v <= ub range :: Enum a => a -> a -> Generator a range lb ub = Generator c u rg where c = fromIntegral $ fromEnum ub - fromEnum lb + 1 u = toEnum . (+) (fromEnum lb) . (\n -> n `mod` fromIntegral c) . fromIntegral rg seed value = u $ fromIntegral $ seed + value -- nullable :: Eq a => Generator a -> Generator (Maybe a) -- nullable (Generator c u rg) = Generator c' u' rg' -- where -- c' = c + 1 -- u' n = if n `mod` c' == 0 then Nothing else Just $ u (n - 1) -- -- u' n = Just $ u (n - 1) -- rg' s n = if n `mod` c' == 0 then Nothing else Just $ rg s (n - 1) random :: Generator a -> Generator a random gen = gen {runGen = (\k v -> unrank gen $ hash64U (k + v))} unique :: Generator a -> Generator a unique (Generator c u rg) = Generator c u rg' where rg' seed value | value < c = u $ case permutate seed c c value of (v, s', c') -> v | otherwise = error "To large" generate :: Word64 -> Generator a -> [a] generate seed gen = map (runGen gen seed) [0..]
Haskell
using AntShares.Core; using AntShares.Cryptography.ECC; using AntShares.Properties; using System.IO; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace AntShares.Cryptography { internal static class CertificateQueryService { public static CertificateQueryResult Query(ECPoint pubkey) { if (pubkey.Equals(Blockchain.AntShare.Issuer) || pubkey.Equals(Blockchain.AntCoin.Issuer)) return new CertificateQueryResult { Type = CertificateQueryResultType.System }; Directory.CreateDirectory(Settings.Default.CertCachePath); string path = Path.Combine(Settings.Default.CertCachePath, $"{pubkey}.cer"); if (!File.Exists(path)) { //TODO: 本地缓存中找不到证书的情况下,去公共服务器上查询 } if (!File.Exists(path)) return new CertificateQueryResult { Type = CertificateQueryResultType.Missing }; X509Certificate2 cert; try { cert = new X509Certificate2(path); } catch (CryptographicException) { return new CertificateQueryResult { Type = CertificateQueryResultType.Missing }; } if (cert.PublicKey.Oid.Value != "1.2.840.10045.2.1") return new CertificateQueryResult { Type = CertificateQueryResultType.Missing }; if (!pubkey.Equals(ECPoint.DecodePoint(cert.PublicKey.EncodedKeyValue.RawData, ECCurve.Secp256r1))) return new CertificateQueryResult { Type = CertificateQueryResultType.Missing }; using (X509Chain chain = new X509Chain()) { CertificateQueryResult result = new CertificateQueryResult { Certificate = cert }; if (chain.Build(cert)) { result.Type = CertificateQueryResultType.Good; } else if (chain.ChainStatus.Length == 1 && chain.ChainStatus[0].Status == X509ChainStatusFlags.NotTimeValid) { result.Type = CertificateQueryResultType.Expired; } else { result.Type = CertificateQueryResultType.Invalid; } return result; } } } }
C#
`timescale 100ps/1ps module slice_vliw_tb; // Sigma delta parameters parameter input_bitwidth = 24; parameter full_neg = {1'b1, {(input_bitwidth-1){1'b0}}}; parameter full_pos = {1'b0, {(input_bitwidth-1){1'b1}}}; reg read_back; reg [3:0] read_back_adr; reg clock_200, reset; reg [8:0] coefficient_write_adr; reg [35:0] coefficient_write_data; reg coefficient_write_en; wire [3:0] state_write_adr, state_read_adr; wire overflow_stage_1, overflow_stage_2; wire signed [23:0] log_value_out, sigma_delta_out; // For sigma delta reg clock_20; reg signed [23:0] input_signal_A, input_signal_B; wire sigdel_output_A, sigdel_output_B; // For VLIW reg write_enable, vliw_start; reg [8:0] write_address; reg [71:0] write_data; wire slice_enable; wire [8:0] coefficient_read_address_1, coefficient_read_address_2; wire [3:0] state_read_address_1, state_read_address_2; wire [3:0] state_write_address_1, state_write_address_2; wire logging_trigger_1, logging_trigger_2; wire sigma_delta_storage_trigger_1, sigma_delta_storage_trigger_2; wire [3:0] sigma_delta_write_address_1, sigma_delta_write_address_2; wire [3:0] sigma_delta_read_address_1, sigma_delta_read_address_2; // The GSR and PUR are needed for the flip flop primitives from Lattice GSR GSR_INST(~reset); // Global Set/Reset signal (active low) PUR PUR_INST(~reset); // Power up reset signal (active low) VLIW_sim vliw( .clock_200(clock_200), .reset(reset), .write_enable(write_enable), .vliw_start(vliw_start), .slice_enable(slice_enable), .write_address(write_address), .write_data(write_data), .coefficient_read_address_1(coefficient_read_address_1), .coefficient_read_address_2(coefficient_read_address_2), .state_read_address_1(state_read_address_1), .state_read_address_2(state_read_address_2), .state_write_address_1(state_write_address_1), .state_write_address_2(state_write_address_2), .sigma_delta_read_address_1(sigma_delta_read_address_1), .sigma_delta_read_address_2(sigma_delta_read_address_2), .sigma_delta_write_address_1(sigma_delta_write_address_1), .sigma_delta_write_address_2(sigma_delta_write_address_2), .logging_trigger_1(logging_trigger_1), .logging_trigger_2(logging_trigger_2), .sigma_delta_storage_trigger_1(sigma_delta_storage_trigger_1), .sigma_delta_storage_trigger_2(sigma_delta_storage_trigger_2) ); slice_sim slice1( .read_back(read_back), .read_back_adr(read_back_adr), .clock_200(clock_200), .reset(reset), .slice_enable(slice_enable), .coefficient_read_adr(coefficient_read_address_1), .coefficient_write_adr(coefficient_write_adr), .coefficient_write_data(coefficient_write_data), .coefficient_write_en(coefficient_write_en), .state_write_adr(state_write_address_1), .state_read_adr(state_read_address_1), .sigma_delta_stream_A(sigdel_output_A), .sigma_delta_stream_B(sigdel_output_B), .log_trigger(logging_trigger_1), .sigma_delta_out_trigger(sigma_delta_storage_trigger_1), .overflow_stage_1(overflow_stage_1), .overflow_stage_2(overflow_stage_2), .log_value_out(log_value_out), .sigma_delta_out(sigma_delta_out) ); // Feed forward modulator stream generator first_order_sigdel sigdel1( .mod_clock(clock_20), .input_sig(input_signal_A), .output_sig(sigdel_output_A) ); // Feedback modulator stream generator first_order_sigdel sigdel2( .mod_clock(clock_20), .input_sig(input_signal_B), .output_sig(sigdel_output_B) ); integer counter; initial begin /* Initial Conditions */ // VLIW vliw_start = 0; write_enable = 0; write_address = 9'b0; write_data = 72'b0; // Slice read_back = 0; read_back_adr = 0; clock_200 = 0; reset = 1; coefficient_write_adr = 0; coefficient_write_data = 0; coefficient_write_en = 0; //sigma_delta_stream_A = 0; //sigma_delta_stream_B = 0; // Address counter counter = 0; // Sigma deltas clock_20 = 1; input_signal_A = 0; input_signal_B = 0; // Initial reset #100 reset = 0; // Write program to VLIW #100 write_enable = 1; //{Store SD, LOG, SD write adr, SD read adr, State write adr, State read adr, Coeff read adr} write_data[26:0] = {1'b1, 1'b1, 4'd0, 4'd0, 4'd0, 4'd0, 9'd0}; write_address = 0; #50 write_data[26:0] = {1'b0, 1'b0, 4'd0, 4'd1, 4'd0, 4'd1, 9'd1}; write_address = 1; #50 write_data[26:0] = {1'b1, 1'b0, 4'd1, 4'd2, 4'd1, 4'd2, 9'd2}; write_address = 2; #50 write_data[26:0] = {1'b0, 1'b0, 4'd2, 4'd3, 4'd2, 4'd3, 9'd3}; write_address = 3; #50 write_data[26:0] = {1'b0, 1'b1, 4'd3, 4'd4, 4'd3, 4'd4, 9'd4}; write_address = 4; #50 write_data[26:0] = {1'b1, 1'b0, 4'd4, 4'd5, 4'd4, 4'd5, 9'd5}; write_address = 5; #50 write_data[26:0] = {1'b1, 1'b1, 4'd5, 4'd6, 4'd5, 4'd6, 9'd6}; write_address = 6; #50 write_data[26:0] = {1'b0, 1'b0, 4'd6, 4'd7, 4'd6, 4'd7, 9'd7}; write_address = 7; #50 write_data[26:0] = {1'b0, 1'b0, 4'd7, 4'd8, 4'd7, 4'd8, 9'd8}; write_address = 8; #50 write_data[26:0] = {1'b0, 1'b1, 4'd8, 4'd9, 4'd8, 4'd9, 9'd9}; write_address = 9; #50 write_enable = 0; // Write 10 sets of coefficients to coeffcient RAM #25 coefficient_write_en = 1; #25 coefficient_write_adr = 0; coefficient_write_data = {18'sd100, 18'sd100}; #50 coefficient_write_adr = 1; coefficient_write_data = {18'sd200, 18'sd200}; #50 coefficient_write_adr = 2; coefficient_write_data = {18'sd300, 18'd300}; #50 coefficient_write_adr = 3; coefficient_write_data = {18'sd400, 18'sd400}; #50 coefficient_write_adr = 4; coefficient_write_data = {18'sd500, 18'sd500}; #50 coefficient_write_adr = 5; coefficient_write_data = {18'sd600, 18'sd600}; #50 coefficient_write_adr = 6; coefficient_write_data = {18'sd700, 18'sd700}; #50 coefficient_write_adr = 7; coefficient_write_data = {18'sd800, 18'sd800}; #50 coefficient_write_adr = 8; coefficient_write_data = {18'sd900, 18'sd900}; #50 coefficient_write_adr = 9; coefficient_write_data = {18'sd1000, 18'sd1000}; #50 coefficient_write_en = 0; #100 vliw_start = 1;//slice_enable = 1; #500 vliw_start = 0;//slice_enable = 0; #500 read_back = 1; repeat (9) begin #50 read_back_adr = read_back_adr + 1; end end always #25 clock_200 = ~clock_200; // 200MHz - for slice always #250 clock_20 = ~clock_20; // 20MHz - for modulator endmodule
Coq
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- This manual is for FFTW (version 3.3.5, 30 July 2016). Copyright (C) 2003 Matteo Frigo. Copyright (C) 2003 Massachusetts Institute of Technology. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Free Software Foundation. --> <!-- Created by GNU Texinfo 5.2, http://www.gnu.org/software/texinfo/ --> <head> <title>FFTW 3.3.5: Data Types and Files</title> <meta name="description" content="FFTW 3.3.5: Data Types and Files"> <meta name="keywords" content="FFTW 3.3.5: Data Types and Files"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="makeinfo"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link href="index.html#Top" rel="start" title="Top"> <link href="Concept-Index.html#Concept-Index" rel="index" title="Concept Index"> <link href="index.html#SEC_Contents" rel="contents" title="Table of Contents"> <link href="FFTW-Reference.html#FFTW-Reference" rel="up" title="FFTW Reference"> <link href="Complex-numbers.html#Complex-numbers" rel="next" title="Complex numbers"> <link href="FFTW-Reference.html#FFTW-Reference" rel="prev" title="FFTW Reference"> <style type="text/css"> <!-- a.summary-letter {text-decoration: none} blockquote.smallquotation {font-size: smaller} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} div.indentedblock {margin-left: 3.2em} div.lisp {margin-left: 3.2em} div.smalldisplay {margin-left: 3.2em} div.smallexample {margin-left: 3.2em} div.smallindentedblock {margin-left: 3.2em; font-size: smaller} div.smalllisp {margin-left: 3.2em} kbd {font-style:oblique} pre.display {font-family: inherit} pre.format {font-family: inherit} pre.menu-comment {font-family: serif} pre.menu-preformatted {font-family: serif} pre.smalldisplay {font-family: inherit; font-size: smaller} pre.smallexample {font-size: smaller} pre.smallformat {font-family: inherit; font-size: smaller} pre.smalllisp {font-size: smaller} span.nocodebreak {white-space:nowrap} span.nolinebreak {white-space:nowrap} span.roman {font-family:serif; font-weight:normal} span.sansserif {font-family:sans-serif; font-weight:normal} ul.no-bullet {list-style: none} --> </style> </head> <body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000"> <a name="Data-Types-and-Files"></a> <div class="header"> <p> Next: <a href="Using-Plans.html#Using-Plans" accesskey="n" rel="next">Using Plans</a>, Previous: <a href="FFTW-Reference.html#FFTW-Reference" accesskey="p" rel="prev">FFTW Reference</a>, Up: <a href="FFTW-Reference.html#FFTW-Reference" accesskey="u" rel="up">FFTW Reference</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html#Concept-Index" title="Index" rel="index">Index</a>]</p> </div> <hr> <a name="Data-Types-and-Files-1"></a> <h3 class="section">4.1 Data Types and Files</h3> <p>All programs using FFTW should include its header file: </p> <div class="example"> <pre class="example">#include &lt;fftw3.h&gt; </pre></div> <p>You must also link to the FFTW library. On Unix, this means adding <code>-lfftw3 -lm</code> at the <em>end</em> of the link command. </p> <table class="menu" border="0" cellspacing="0"> <tr><td align="left" valign="top">&bull; <a href="Complex-numbers.html#Complex-numbers" accesskey="1">Complex numbers</a>:</td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> </td></tr> <tr><td align="left" valign="top">&bull; <a href="Precision.html#Precision" accesskey="2">Precision</a>:</td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> </td></tr> <tr><td align="left" valign="top">&bull; <a href="Memory-Allocation.html#Memory-Allocation" accesskey="3">Memory Allocation</a>:</td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> </td></tr> </table> </body> </html>
HTML
defmodule Explorer.Repo.Migrations.AddOpOutputRootsTable do use Ecto.Migration def change do create table(:op_output_roots, primary_key: false) do add(:l2_output_index, :bigint, null: false, primary_key: true) add(:l2_block_number, :bigint, null: false) add(:l1_tx_hash, :bytea, null: false) add(:l1_timestamp, :"timestamp without time zone", null: false) add(:l1_block_number, :bigint, null: false) add(:output_root, :bytea, null: false) timestamps(null: false, type: :utc_datetime_usec) end end end
Elixir
object Form1: TForm1 Left = 0 Top = 0 Caption = 'Form1' ClientHeight = 465 ClientWidth = 595 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] Menu = MainMenu1 OldCreateOrder = False PixelsPerInch = 96 TextHeight = 13 object MainMenu1: TMainMenu Left = 568 Top = 65520 object Menu1: TMenuItem Caption = 'Inicio' object Mascotas1: TMenuItem Caption = 'Mascotas' object Ingresar1: TMenuItem Caption = 'Ingresar' end object Eliminar1: TMenuItem Caption = 'Eliminar' end object Consultar1: TMenuItem Caption = 'Consultar' end end object Propietarios1: TMenuItem Caption = 'Propietarios' object Ingresar2: TMenuItem Caption = 'Ingresar' end object Eliminar2: TMenuItem Caption = 'Eliminar' end object Consultar2: TMenuItem Caption = 'Consultar' end end object Campeonatos1: TMenuItem Caption = 'Campeonatos' object ingresar3: TMenuItem Caption = 'Ingresar' end object Eliminar3: TMenuItem Caption = 'Eliminar' end object Consultar3: TMenuItem Caption = 'Consultar' end end object N1: TMenuItem Caption = '-' end object Salir1: TMenuItem Caption = 'Salir' OnClick = Salir1Click end end end end
Pascal
cmd_/home/diya/sdvt2017/src/linuxcan/pcican2/memQ.o := gcc -Wp,-MD,/home/diya/sdvt2017/src/linuxcan/pcican2/.memQ.o.d -nostdinc -isystem /usr/lib/gcc/x86_64-linux-gnu/4.8/include -I./arch/x86/include -Iarch/x86/include/generated/uapi -Iarch/x86/include/generated -Iinclude -I./arch/x86/include/uapi -Iarch/x86/include/generated/uapi -I./include/uapi -Iinclude/generated/uapi -include ./include/linux/kconfig.h -Iubuntu/include -D__KERNEL__ -fno-pie -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs -fno-strict-aliasing -fno-common -Werror-implicit-function-declaration -Wno-format-security -std=gnu89 -fno-pie -mno-sse -mno-mmx -mno-sse2 -mno-3dnow -mno-avx -m64 -falign-jumps=1 -falign-loops=1 -mno-80387 -mno-fp-ret-in-387 -mpreferred-stack-boundary=3 -mtune=generic -mno-red-zone -mcmodel=kernel -funit-at-a-time -maccumulate-outgoing-args -DCONFIG_X86_X32_ABI -DCONFIG_AS_CFI=1 -DCONFIG_AS_CFI_SIGNAL_FRAME=1 -DCONFIG_AS_CFI_SECTIONS=1 -DCONFIG_AS_FXSAVEQ=1 -DCONFIG_AS_SSSE3=1 -DCONFIG_AS_CRC32=1 -DCONFIG_AS_AVX=1 -DCONFIG_AS_AVX2=1 -DCONFIG_AS_SHA1_NI=1 -DCONFIG_AS_SHA256_NI=1 -pipe -Wno-sign-compare -fno-asynchronous-unwind-tables -fno-delete-null-pointer-checks -Wno-maybe-uninitialized -O2 --param=allow-store-data-races=0 -Wframe-larger-than=1024 -fstack-protector -Wno-unused-but-set-variable -fno-omit-frame-pointer -fno-optimize-sibling-calls -fno-var-tracking-assignments -pg -mfentry -DCC_USING_FENTRY -Wdeclaration-after-statement -Wno-pointer-sign -fno-strict-overflow -fconserve-stack -Werror=implicit-int -Werror=strict-prototypes -DCC_HAVE_ASM_GOTO -DLINUX=1 -I/home/diya/sdvt2017/src/linuxcan/pcican2/../include/ -Werror -Wno-date-time -Wall -Wclobbered -Wempty-body -Wignored-qualifiers -Wmissing-parameter-type -Wold-style-declaration -Woverride-init -Wtype-limits -Wuninitialized -D_DEBUG=0 -DDEBUG=0 -DWIN32=0 -DMODULE -D"KBUILD_STR(s)=\#s" -D"KBUILD_BASENAME=KBUILD_STR(memQ)" -D"KBUILD_MODNAME=KBUILD_STR(kvpcicanII)" -c -o /home/diya/sdvt2017/src/linuxcan/pcican2/.tmp_memQ.o /home/diya/sdvt2017/src/linuxcan/pcican2/memQ.c source_/home/diya/sdvt2017/src/linuxcan/pcican2/memQ.o := /home/diya/sdvt2017/src/linuxcan/pcican2/memQ.c deps_/home/diya/sdvt2017/src/linuxcan/pcican2/memQ.o := \ /home/diya/sdvt2017/src/linuxcan/pcican2/../include/module_versioning.h \ $(wildcard include/config/.h) \ $(wildcard include/config/modversions.h) \ include/generated/uapi/linux/version.h \ include/config/modversions.h \ include/linux/module.h \ $(wildcard include/config/modules.h) \ $(wildcard include/config/sysfs.h) \ $(wildcard include/config/module/sig.h) \ $(wildcard include/config/modules/tree/lookup.h) \ $(wildcard include/config/unused/symbols.h) \ $(wildcard include/config/generic/bug.h) \ $(wildcard include/config/kallsyms.h) \ $(wildcard include/config/smp.h) \ $(wildcard include/config/tracepoints.h) \ $(wildcard include/config/tracing.h) \ $(wildcard include/config/event/tracing.h) \ $(wildcard include/config/ftrace/mcount/record.h) \ $(wildcard include/config/livepatch.h) \ $(wildcard include/config/module/unload.h) \ $(wildcard include/config/constructors.h) \ $(wildcard include/config/debug/set/module/ronx.h) \ include/linux/list.h \ $(wildcard include/config/debug/list.h) \ include/linux/types.h \ $(wildcard include/config/have/uid16.h) \ $(wildcard include/config/uid16.h) \ $(wildcard include/config/lbdaf.h) \ $(wildcard include/config/arch/dma/addr/t/64bit.h) \ $(wildcard include/config/phys/addr/t/64bit.h) \ $(wildcard include/config/64bit.h) \ include/uapi/linux/types.h \ arch/x86/include/uapi/asm/types.h \ include/uapi/asm-generic/types.h \ include/asm-generic/int-ll64.h \ include/uapi/asm-generic/int-ll64.h \ arch/x86/include/uapi/asm/bitsperlong.h \ include/asm-generic/bitsperlong.h \ include/uapi/asm-generic/bitsperlong.h \ include/uapi/linux/posix_types.h \ include/linux/stddef.h \ include/uapi/linux/stddef.h \ include/linux/compiler.h \ $(wildcard include/config/sparse/rcu/pointer.h) \ $(wildcard include/config/trace/branch/profiling.h) \ $(wildcard include/config/profile/all/branches.h) \ $(wildcard include/config/kasan.h) \ $(wildcard include/config/enable/must/check.h) \ $(wildcard include/config/enable/warn/deprecated.h) \ $(wildcard include/config/kprobes.h) \ include/linux/compiler-gcc.h \ $(wildcard include/config/arch/supports/optimized/inlining.h) \ $(wildcard include/config/optimize/inlining.h) \ $(wildcard include/config/gcov/kernel.h) \ $(wildcard include/config/arch/use/builtin/bswap.h) \ arch/x86/include/asm/posix_types.h \ $(wildcard include/config/x86/32.h) \ arch/x86/include/uapi/asm/posix_types_64.h \ include/uapi/asm-generic/posix_types.h \ include/linux/poison.h \ $(wildcard include/config/illegal/pointer/value.h) \ include/uapi/linux/const.h \ include/linux/kernel.h \ $(wildcard include/config/preempt/voluntary.h) \ $(wildcard include/config/debug/atomic/sleep.h) \ $(wildcard include/config/mmu.h) \ $(wildcard include/config/prove/locking.h) \ $(wildcard include/config/panic/timeout.h) \ /usr/lib/gcc/x86_64-linux-gnu/4.8/include/stdarg.h \ include/linux/linkage.h \ include/linux/stringify.h \ include/linux/export.h \ $(wildcard include/config/have/underscore/symbol/prefix.h) \ arch/x86/include/asm/linkage.h \ $(wildcard include/config/x86/64.h) \ $(wildcard include/config/x86/alignment/16.h) \ include/linux/bitops.h \ arch/x86/include/asm/bitops.h \ $(wildcard include/config/x86/cmov.h) \ arch/x86/include/asm/alternative.h \ $(wildcard include/config/paravirt.h) \ arch/x86/include/asm/asm.h \ arch/x86/include/asm/ptrace.h \ $(wildcard include/config/x86/debugctlmsr.h) \ arch/x86/include/asm/segment.h \ $(wildcard include/config/cc/stackprotector.h) \ $(wildcard include/config/x86/32/lazy/gs.h) \ arch/x86/include/asm/cache.h \ $(wildcard include/config/x86/l1/cache/shift.h) \ $(wildcard include/config/x86/internode/cache/shift.h) \ $(wildcard include/config/x86/vsmp.h) \ arch/x86/include/asm/page_types.h \ $(wildcard include/config/physical/start.h) \ $(wildcard include/config/physical/align.h) \ arch/x86/include/asm/page_64_types.h \ $(wildcard include/config/randomize/base.h) \ $(wildcard include/config/randomize/base/max/offset.h) \ arch/x86/include/uapi/asm/ptrace.h \ arch/x86/include/uapi/asm/ptrace-abi.h \ arch/x86/include/asm/processor-flags.h \ $(wildcard include/config/vm86.h) \ arch/x86/include/uapi/asm/processor-flags.h \ arch/x86/include/asm/paravirt_types.h \ $(wildcard include/config/x86/local/apic.h) \ $(wildcard include/config/pgtable/levels.h) \ $(wildcard include/config/x86/pae.h) \ $(wildcard include/config/queued/spinlocks.h) \ $(wildcard include/config/paravirt/debug.h) \ arch/x86/include/asm/desc_defs.h \ arch/x86/include/asm/kmap_types.h \ $(wildcard include/config/debug/highmem.h) \ include/asm-generic/kmap_types.h \ arch/x86/include/asm/pgtable_types.h \ $(wildcard include/config/kmemcheck.h) \ $(wildcard include/config/mem/soft/dirty.h) \ $(wildcard include/config/proc/fs.h) \ arch/x86/include/asm/pgtable_64_types.h \ arch/x86/include/asm/sparsemem.h \ $(wildcard include/config/sparsemem.h) \ arch/x86/include/asm/spinlock_types.h \ $(wildcard include/config/paravirt/spinlocks.h) \ $(wildcard include/config/nr/cpus.h) \ include/asm-generic/qspinlock_types.h \ include/asm-generic/qrwlock_types.h \ include/asm-generic/ptrace.h \ arch/x86/include/asm/rmwcc.h \ arch/x86/include/asm/barrier.h \ $(wildcard include/config/x86/ppro/fence.h) \ arch/x86/include/asm/nops.h \ $(wildcard include/config/mk7.h) \ $(wildcard include/config/x86/p6/nop.h) \ include/asm-generic/barrier.h \ include/asm-generic/bitops/find.h \ $(wildcard include/config/generic/find/first/bit.h) \ include/asm-generic/bitops/sched.h \ arch/x86/include/asm/arch_hweight.h \ arch/x86/include/asm/cpufeatures.h \ arch/x86/include/asm/required-features.h \ $(wildcard include/config/x86/minimum/cpu/family.h) \ $(wildcard include/config/math/emulation.h) \ $(wildcard include/config/x86/cmpxchg64.h) \ $(wildcard include/config/x86/use/3dnow.h) \ $(wildcard include/config/matom.h) \ arch/x86/include/asm/disabled-features.h \ $(wildcard include/config/x86/intel/mpx.h) \ include/asm-generic/bitops/const_hweight.h \ include/asm-generic/bitops/le.h \ arch/x86/include/uapi/asm/byteorder.h \ include/linux/byteorder/little_endian.h \ include/uapi/linux/byteorder/little_endian.h \ include/linux/swab.h \ include/uapi/linux/swab.h \ arch/x86/include/uapi/asm/swab.h \ include/linux/byteorder/generic.h \ include/asm-generic/bitops/ext2-atomic-setbit.h \ include/linux/log2.h \ $(wildcard include/config/arch/has/ilog2/u32.h) \ $(wildcard include/config/arch/has/ilog2/u64.h) \ include/linux/typecheck.h \ include/linux/printk.h \ $(wildcard include/config/message/loglevel/default.h) \ $(wildcard include/config/early/printk.h) \ $(wildcard include/config/printk.h) \ $(wildcard include/config/dynamic/debug.h) \ include/linux/init.h \ $(wildcard include/config/broken/rodata.h) \ $(wildcard include/config/lto.h) \ include/linux/kern_levels.h \ include/linux/cache.h \ $(wildcard include/config/arch/has/cache/line/size.h) \ include/uapi/linux/kernel.h \ include/uapi/linux/sysinfo.h \ include/linux/dynamic_debug.h \ include/linux/stat.h \ arch/x86/include/uapi/asm/stat.h \ include/uapi/linux/stat.h \ include/linux/time.h \ $(wildcard include/config/arch/uses/gettimeoffset.h) \ include/linux/seqlock.h \ $(wildcard include/config/debug/lock/alloc.h) \ include/linux/spinlock.h \ $(wildcard include/config/debug/spinlock.h) \ $(wildcard include/config/generic/lockbreak.h) \ $(wildcard include/config/preempt.h) \ include/linux/preempt.h \ $(wildcard include/config/preempt/count.h) \ $(wildcard include/config/debug/preempt.h) \ $(wildcard include/config/preempt/tracer.h) \ $(wildcard include/config/preempt/notifiers.h) \ arch/x86/include/asm/preempt.h \ arch/x86/include/asm/percpu.h \ $(wildcard include/config/x86/64/smp.h) \ include/asm-generic/percpu.h \ $(wildcard include/config/have/setup/per/cpu/area.h) \ include/linux/threads.h \ $(wildcard include/config/base/small.h) \ include/linux/percpu-defs.h \ $(wildcard include/config/debug/force/weak/per/cpu.h) \ include/linux/thread_info.h \ $(wildcard include/config/compat.h) \ $(wildcard include/config/debug/stack/usage.h) \ include/linux/bug.h \ arch/x86/include/asm/bug.h \ $(wildcard include/config/debug/bugverbose.h) \ include/asm-generic/bug.h \ $(wildcard include/config/bug.h) \ $(wildcard include/config/generic/bug/relative/pointers.h) \ arch/x86/include/asm/thread_info.h \ $(wildcard include/config/ia32/emulation.h) \ arch/x86/include/asm/page.h \ arch/x86/include/asm/page_64.h \ $(wildcard include/config/debug/virtual.h) \ $(wildcard include/config/flatmem.h) \ $(wildcard include/config/x86/vsyscall/emulation.h) \ include/linux/range.h \ include/asm-generic/memory_model.h \ $(wildcard include/config/discontigmem.h) \ $(wildcard include/config/sparsemem/vmemmap.h) \ include/asm-generic/getorder.h \ arch/x86/include/asm/cpufeature.h \ $(wildcard include/config/x86/feature/names.h) \ $(wildcard include/config/x86/debug/static/cpu/has.h) \ arch/x86/include/asm/processor.h \ $(wildcard include/config/m486.h) \ $(wildcard include/config/xen.h) \ arch/x86/include/asm/math_emu.h \ arch/x86/include/uapi/asm/sigcontext.h \ arch/x86/include/asm/current.h \ arch/x86/include/asm/msr.h \ arch/x86/include/asm/msr-index.h \ $(wildcard include/config/tdp/nominal.h) \ $(wildcard include/config/tdp/level/1.h) \ $(wildcard include/config/tdp/level/2.h) \ $(wildcard include/config/tdp/control.h) \ $(wildcard include/config/tdp/level1.h) \ $(wildcard include/config/tdp/level2.h) \ arch/x86/include/uapi/asm/errno.h \ include/uapi/asm-generic/errno.h \ include/uapi/asm-generic/errno-base.h \ arch/x86/include/asm/cpumask.h \ include/linux/cpumask.h \ $(wildcard include/config/cpumask/offstack.h) \ $(wildcard include/config/hotplug/cpu.h) \ $(wildcard include/config/debug/per/cpu/maps.h) \ include/linux/bitmap.h \ include/linux/string.h \ $(wildcard include/config/binary/printf.h) \ include/uapi/linux/string.h \ arch/x86/include/asm/string.h \ arch/x86/include/asm/string_64.h \ arch/x86/include/uapi/asm/msr.h \ include/uapi/linux/ioctl.h \ arch/x86/include/uapi/asm/ioctl.h \ include/asm-generic/ioctl.h \ include/uapi/asm-generic/ioctl.h \ arch/x86/include/asm/paravirt.h \ arch/x86/include/asm/special_insns.h \ arch/x86/include/asm/fpu/types.h \ include/linux/personality.h \ include/uapi/linux/personality.h \ include/linux/math64.h \ $(wildcard include/config/arch/supports/int128.h) \ arch/x86/include/asm/div64.h \ include/asm-generic/div64.h \ include/linux/err.h \ include/linux/irqflags.h \ $(wildcard include/config/trace/irqflags.h) \ $(wildcard include/config/irqsoff/tracer.h) \ $(wildcard include/config/trace/irqflags/support.h) \ arch/x86/include/asm/irqflags.h \ include/linux/atomic.h \ $(wildcard include/config/generic/atomic64.h) \ arch/x86/include/asm/atomic.h \ arch/x86/include/asm/cmpxchg.h \ arch/x86/include/asm/cmpxchg_64.h \ arch/x86/include/asm/atomic64_64.h \ include/asm-generic/atomic-long.h \ include/linux/bottom_half.h \ include/linux/spinlock_types.h \ include/linux/lockdep.h \ $(wildcard include/config/lockdep.h) \ $(wildcard include/config/lock/stat.h) \ include/linux/rwlock_types.h \ arch/x86/include/asm/spinlock.h \ include/linux/jump_label.h \ $(wildcard include/config/jump/label.h) \ arch/x86/include/asm/jump_label.h \ arch/x86/include/asm/qspinlock.h \ include/asm-generic/qspinlock.h \ arch/x86/include/asm/qrwlock.h \ include/asm-generic/qrwlock.h \ include/linux/rwlock.h \ include/linux/spinlock_api_smp.h \ $(wildcard include/config/inline/spin/lock.h) \ $(wildcard include/config/inline/spin/lock/bh.h) \ $(wildcard include/config/inline/spin/lock/irq.h) \ $(wildcard include/config/inline/spin/lock/irqsave.h) \ $(wildcard include/config/inline/spin/trylock.h) \ $(wildcard include/config/inline/spin/trylock/bh.h) \ $(wildcard include/config/uninline/spin/unlock.h) \ $(wildcard include/config/inline/spin/unlock/bh.h) \ $(wildcard include/config/inline/spin/unlock/irq.h) \ $(wildcard include/config/inline/spin/unlock/irqrestore.h) \ include/linux/rwlock_api_smp.h \ $(wildcard include/config/inline/read/lock.h) \ $(wildcard include/config/inline/write/lock.h) \ $(wildcard include/config/inline/read/lock/bh.h) \ $(wildcard include/config/inline/write/lock/bh.h) \ $(wildcard include/config/inline/read/lock/irq.h) \ $(wildcard include/config/inline/write/lock/irq.h) \ $(wildcard include/config/inline/read/lock/irqsave.h) \ $(wildcard include/config/inline/write/lock/irqsave.h) \ $(wildcard include/config/inline/read/trylock.h) \ $(wildcard include/config/inline/write/trylock.h) \ $(wildcard include/config/inline/read/unlock.h) \ $(wildcard include/config/inline/write/unlock.h) \ $(wildcard include/config/inline/read/unlock/bh.h) \ $(wildcard include/config/inline/write/unlock/bh.h) \ $(wildcard include/config/inline/read/unlock/irq.h) \ $(wildcard include/config/inline/write/unlock/irq.h) \ $(wildcard include/config/inline/read/unlock/irqrestore.h) \ $(wildcard include/config/inline/write/unlock/irqrestore.h) \ include/linux/time64.h \ include/uapi/linux/time.h \ include/linux/uidgid.h \ $(wildcard include/config/multiuser.h) \ $(wildcard include/config/user/ns.h) \ include/linux/highuid.h \ include/linux/kmod.h \ include/linux/gfp.h \ $(wildcard include/config/highmem.h) \ $(wildcard include/config/zone/dma.h) \ $(wildcard include/config/zone/dma32.h) \ $(wildcard include/config/zone/device.h) \ $(wildcard include/config/numa.h) \ $(wildcard include/config/deferred/struct/page/init.h) \ $(wildcard include/config/pm/sleep.h) \ $(wildcard include/config/cma.h) \ include/linux/mmdebug.h \ $(wildcard include/config/debug/vm.h) \ include/linux/mmzone.h \ $(wildcard include/config/force/max/zoneorder.h) \ $(wildcard include/config/memory/isolation.h) \ $(wildcard include/config/memcg.h) \ $(wildcard include/config/memory/hotplug.h) \ $(wildcard include/config/compaction.h) \ $(wildcard include/config/flat/node/mem/map.h) \ $(wildcard include/config/page/extension.h) \ $(wildcard include/config/no/bootmem.h) \ $(wildcard include/config/numa/balancing.h) \ $(wildcard include/config/have/memory/present.h) \ $(wildcard include/config/have/memoryless/nodes.h) \ $(wildcard include/config/need/node/memmap/size.h) \ $(wildcard include/config/have/memblock/node/map.h) \ $(wildcard include/config/need/multiple/nodes.h) \ $(wildcard include/config/have/arch/early/pfn/to/nid.h) \ $(wildcard include/config/sparsemem/extreme.h) \ $(wildcard include/config/have/arch/pfn/valid.h) \ $(wildcard include/config/holes/in/zone.h) \ $(wildcard include/config/arch/has/holes/memorymodel.h) \ include/linux/wait.h \ include/uapi/linux/wait.h \ include/linux/numa.h \ $(wildcard include/config/nodes/shift.h) \ include/linux/nodemask.h \ $(wildcard include/config/movable/node.h) \ include/linux/pageblock-flags.h \ $(wildcard include/config/hugetlb/page.h) \ $(wildcard include/config/hugetlb/page/size/variable.h) \ include/linux/page-flags-layout.h \ include/generated/bounds.h \ include/linux/memory_hotplug.h \ $(wildcard include/config/memory/hotremove.h) \ $(wildcard include/config/have/arch/nodedata/extension.h) \ $(wildcard include/config/have/bootmem/info/node.h) \ include/linux/notifier.h \ include/linux/errno.h \ include/uapi/linux/errno.h \ include/linux/mutex.h \ $(wildcard include/config/debug/mutexes.h) \ $(wildcard include/config/mutex/spin/on/owner.h) \ include/linux/osq_lock.h \ include/linux/rwsem.h \ $(wildcard include/config/rwsem/spin/on/owner.h) \ $(wildcard include/config/rwsem/generic/spinlock.h) \ arch/x86/include/asm/rwsem.h \ include/linux/srcu.h \ include/linux/rcupdate.h \ $(wildcard include/config/tiny/rcu.h) \ $(wildcard include/config/tree/rcu.h) \ $(wildcard include/config/preempt/rcu.h) \ $(wildcard include/config/rcu/trace.h) \ $(wildcard include/config/rcu/stall/common.h) \ $(wildcard include/config/no/hz/full.h) \ $(wildcard include/config/rcu/nocb/cpu.h) \ $(wildcard include/config/tasks/rcu.h) \ $(wildcard include/config/debug/objects/rcu/head.h) \ $(wildcard include/config/prove/rcu.h) \ $(wildcard include/config/rcu/boost.h) \ $(wildcard include/config/rcu/nocb/cpu/all.h) \ $(wildcard include/config/no/hz/full/sysidle.h) \ include/linux/completion.h \ include/linux/debugobjects.h \ $(wildcard include/config/debug/objects.h) \ $(wildcard include/config/debug/objects/free.h) \ include/linux/ktime.h \ include/linux/jiffies.h \ include/linux/timex.h \ include/uapi/linux/timex.h \ include/uapi/linux/param.h \ arch/x86/include/uapi/asm/param.h \ include/asm-generic/param.h \ $(wildcard include/config/hz.h) \ include/uapi/asm-generic/param.h \ arch/x86/include/asm/timex.h \ arch/x86/include/asm/tsc.h \ $(wildcard include/config/x86/tsc.h) \ include/generated/timeconst.h \ include/linux/timekeeping.h \ include/linux/rcutree.h \ include/linux/workqueue.h \ $(wildcard include/config/debug/objects/work.h) \ $(wildcard include/config/freezer.h) \ include/linux/timer.h \ $(wildcard include/config/timer/stats.h) \ $(wildcard include/config/debug/objects/timers.h) \ $(wildcard include/config/no/hz/common.h) \ include/linux/sysctl.h \ $(wildcard include/config/sysctl.h) \ include/linux/rbtree.h \ include/uapi/linux/sysctl.h \ arch/x86/include/asm/mmzone.h \ arch/x86/include/asm/mmzone_64.h \ arch/x86/include/asm/smp.h \ $(wildcard include/config/x86/io/apic.h) \ $(wildcard include/config/x86/32/smp.h) \ $(wildcard include/config/debug/nmi/selftest.h) \ arch/x86/include/asm/mpspec.h \ $(wildcard include/config/eisa.h) \ $(wildcard include/config/x86/mpparse.h) \ arch/x86/include/asm/mpspec_def.h \ arch/x86/include/asm/x86_init.h \ arch/x86/include/uapi/asm/bootparam.h \ include/linux/screen_info.h \ include/uapi/linux/screen_info.h \ include/linux/apm_bios.h \ include/uapi/linux/apm_bios.h \ include/linux/edd.h \ include/uapi/linux/edd.h \ arch/x86/include/asm/e820.h \ $(wildcard include/config/efi.h) \ $(wildcard include/config/hibernation.h) \ arch/x86/include/uapi/asm/e820.h \ $(wildcard include/config/x86/pmem/legacy.h) \ $(wildcard include/config/intel/txt.h) \ include/linux/ioport.h \ arch/x86/include/asm/ist.h \ arch/x86/include/uapi/asm/ist.h \ include/video/edid.h \ $(wildcard include/config/x86.h) \ include/uapi/video/edid.h \ arch/x86/include/asm/apicdef.h \ arch/x86/include/asm/apic.h \ $(wildcard include/config/x86/x2apic.h) \ include/linux/pm.h \ $(wildcard include/config/vt/console/sleep.h) \ $(wildcard include/config/pm.h) \ $(wildcard include/config/pm/clk.h) \ $(wildcard include/config/pm/generic/domains.h) \ arch/x86/include/asm/fixmap.h \ $(wildcard include/config/paravirt/clock.h) \ $(wildcard include/config/provide/ohci1394/dma/init.h) \ $(wildcard include/config/pci/mmconfig.h) \ $(wildcard include/config/x86/intel/mid.h) \ arch/x86/include/asm/acpi.h \ $(wildcard include/config/acpi/apei.h) \ $(wildcard include/config/acpi.h) \ $(wildcard include/config/acpi/numa.h) \ include/acpi/pdc_intel.h \ arch/x86/include/asm/numa.h \ $(wildcard include/config/numa/emu.h) \ arch/x86/include/asm/topology.h \ include/asm-generic/topology.h \ arch/x86/include/asm/mmu.h \ $(wildcard include/config/modify/ldt/syscall.h) \ arch/x86/include/asm/realmode.h \ $(wildcard include/config/acpi/sleep.h) \ arch/x86/include/asm/io.h \ $(wildcard include/config/mtrr.h) \ arch/x86/include/generated/asm/early_ioremap.h \ include/asm-generic/early_ioremap.h \ $(wildcard include/config/generic/early/ioremap.h) \ include/asm-generic/iomap.h \ $(wildcard include/config/has/ioport/map.h) \ $(wildcard include/config/pci.h) \ $(wildcard include/config/generic/iomap.h) \ include/asm-generic/pci_iomap.h \ $(wildcard include/config/no/generic/pci/ioport/map.h) \ $(wildcard include/config/generic/pci/iomap.h) \ include/xen/xen.h \ $(wildcard include/config/xen/dom0.h) \ $(wildcard include/config/xen/pvh.h) \ include/xen/interface/xen.h \ arch/x86/include/asm/xen/interface.h \ arch/x86/include/asm/xen/interface_64.h \ arch/x86/include/asm/pvclock-abi.h \ arch/x86/include/asm/xen/hypervisor.h \ include/xen/features.h \ include/xen/interface/features.h \ arch/x86/include/asm/pvclock.h \ include/linux/clocksource.h \ $(wildcard include/config/arch/clocksource/data.h) \ $(wildcard include/config/clocksource/watchdog.h) \ $(wildcard include/config/clksrc/probe.h) \ arch/x86/include/asm/clocksource.h \ arch/x86/include/uapi/asm/vsyscall.h \ include/asm-generic/fixmap.h \ arch/x86/include/asm/idle.h \ arch/x86/include/asm/io_apic.h \ arch/x86/include/asm/irq_vectors.h \ $(wildcard include/config/have/kvm.h) \ $(wildcard include/config/pci/msi.h) \ include/linux/topology.h \ $(wildcard include/config/use/percpu/numa/node/id.h) \ $(wildcard include/config/sched/smt.h) \ include/linux/smp.h \ $(wildcard include/config/up/late/init.h) \ include/linux/llist.h \ $(wildcard include/config/arch/have/nmi/safe/cmpxchg.h) \ include/linux/percpu.h \ $(wildcard include/config/need/per/cpu/embed/first/chunk.h) \ $(wildcard include/config/need/per/cpu/page/first/chunk.h) \ include/linux/pfn.h \ include/linux/elf.h \ arch/x86/include/asm/elf.h \ $(wildcard include/config/x86/x32/abi.h) \ arch/x86/include/asm/user.h \ arch/x86/include/asm/user_64.h \ arch/x86/include/uapi/asm/auxvec.h \ arch/x86/include/asm/vdso.h \ $(wildcard include/config/x86/x32.h) \ include/linux/mm_types.h \ $(wildcard include/config/split/ptlock/cpus.h) \ $(wildcard include/config/arch/enable/split/pmd/ptlock.h) \ $(wildcard include/config/have/cmpxchg/double.h) \ $(wildcard include/config/have/aligned/struct/page.h) \ $(wildcard include/config/transparent/hugepage.h) \ $(wildcard include/config/userfaultfd.h) \ $(wildcard include/config/aio.h) \ $(wildcard include/config/mmu/notifier.h) \ include/linux/auxvec.h \ include/uapi/linux/auxvec.h \ include/linux/uprobes.h \ $(wildcard include/config/uprobes.h) \ arch/x86/include/asm/uprobes.h \ include/uapi/linux/elf.h \ include/uapi/linux/elf-em.h \ include/linux/kobject.h \ $(wildcard include/config/uevent/helper.h) \ $(wildcard include/config/debug/kobject/release.h) \ include/linux/sysfs.h \ include/linux/kernfs.h \ $(wildcard include/config/kernfs.h) \ include/linux/idr.h \ include/linux/kobject_ns.h \ include/linux/kref.h \ include/linux/moduleparam.h \ $(wildcard include/config/alpha.h) \ $(wildcard include/config/ia64.h) \ $(wildcard include/config/ppc64.h) \ include/linux/rbtree_latch.h \ arch/x86/include/asm/module.h \ $(wildcard include/config/m586.h) \ $(wildcard include/config/m586tsc.h) \ $(wildcard include/config/m586mmx.h) \ $(wildcard include/config/mcore2.h) \ $(wildcard include/config/m686.h) \ $(wildcard include/config/mpentiumii.h) \ $(wildcard include/config/mpentiumiii.h) \ $(wildcard include/config/mpentiumm.h) \ $(wildcard include/config/mpentium4.h) \ $(wildcard include/config/mk6.h) \ $(wildcard include/config/mk8.h) \ $(wildcard include/config/melan.h) \ $(wildcard include/config/mcrusoe.h) \ $(wildcard include/config/mefficeon.h) \ $(wildcard include/config/mwinchipc6.h) \ $(wildcard include/config/mwinchip3d.h) \ $(wildcard include/config/mcyrixiii.h) \ $(wildcard include/config/mviac3/2.h) \ $(wildcard include/config/mviac7.h) \ $(wildcard include/config/mgeodegx1.h) \ $(wildcard include/config/mgeode/lx.h) \ include/asm-generic/module.h \ $(wildcard include/config/have/mod/arch/specific.h) \ $(wildcard include/config/modules/use/elf/rel.h) \ $(wildcard include/config/modules/use/elf/rela.h) \ /home/diya/sdvt2017/src/linuxcan/pcican2/../include/osif_functions_kernel.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/../include/osif_kernel.h \ include/linux/tty.h \ $(wildcard include/config/tty.h) \ $(wildcard include/config/audit.h) \ include/linux/fs.h \ $(wildcard include/config/fs/posix/acl.h) \ $(wildcard include/config/security.h) \ $(wildcard include/config/cgroup/writeback.h) \ $(wildcard include/config/ima.h) \ $(wildcard include/config/fsnotify.h) \ $(wildcard include/config/epoll.h) \ $(wildcard include/config/file/locking.h) \ $(wildcard include/config/quota.h) \ $(wildcard include/config/blk/dev/loop.h) \ $(wildcard include/config/fs/dax.h) \ $(wildcard include/config/block.h) \ $(wildcard include/config/migration.h) \ include/linux/kdev_t.h \ include/uapi/linux/kdev_t.h \ include/linux/dcache.h \ include/linux/rculist.h \ include/linux/rculist_bl.h \ include/linux/list_bl.h \ include/linux/bit_spinlock.h \ include/linux/lockref.h \ $(wildcard include/config/arch/use/cmpxchg/lockref.h) \ include/linux/path.h \ include/linux/list_lru.h \ $(wildcard include/config/memcg/kmem.h) \ include/linux/shrinker.h \ include/linux/radix-tree.h \ include/linux/pid.h \ include/linux/capability.h \ include/uapi/linux/capability.h \ include/linux/semaphore.h \ include/uapi/linux/fiemap.h \ include/linux/migrate_mode.h \ include/linux/percpu-rwsem.h \ include/linux/rcu_sync.h \ include/linux/blk_types.h \ $(wildcard include/config/blk/cgroup.h) \ $(wildcard include/config/blk/dev/integrity.h) \ include/uapi/linux/fs.h \ include/uapi/linux/limits.h \ include/linux/quota.h \ $(wildcard include/config/quota/netlink/interface.h) \ include/linux/percpu_counter.h \ include/uapi/linux/dqblk_xfs.h \ include/linux/dqblk_v1.h \ include/linux/dqblk_v2.h \ include/linux/dqblk_qtree.h \ include/linux/projid.h \ include/uapi/linux/quota.h \ include/linux/nfs_fs_i.h \ include/linux/fcntl.h \ include/uapi/linux/fcntl.h \ arch/x86/include/uapi/asm/fcntl.h \ include/uapi/asm-generic/fcntl.h \ include/uapi/linux/major.h \ include/uapi/linux/termios.h \ arch/x86/include/uapi/asm/termios.h \ include/asm-generic/termios.h \ arch/x86/include/asm/uaccess.h \ $(wildcard include/config/x86/intel/usercopy.h) \ $(wildcard include/config/debug/strict/user/copy/checks.h) \ arch/x86/include/asm/smap.h \ $(wildcard include/config/x86/smap.h) \ arch/x86/include/asm/uaccess_64.h \ include/uapi/asm-generic/termios.h \ arch/x86/include/uapi/asm/termbits.h \ include/uapi/asm-generic/termbits.h \ arch/x86/include/uapi/asm/ioctls.h \ include/uapi/asm-generic/ioctls.h \ include/linux/tty_driver.h \ $(wildcard include/config/console/poll.h) \ include/linux/cdev.h \ include/linux/tty_ldisc.h \ include/uapi/linux/tty_flags.h \ include/uapi/linux/tty.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/../include/helios_cmds.h \ $(wildcard include/config/req.h) \ $(wildcard include/config/resp.h) \ $(wildcard include/config/mode/req.h) \ $(wildcard include/config/mode/resp.h) \ $(wildcard include/config/data/chunk.h) \ $(wildcard include/config/subcmd/set/interval.h) \ $(wildcard include/config/subcmd/get/interval.h) \ $(wildcard include/config/subcmd/update/timeout.h) \ $(wildcard include/config/mode.h) \ /home/diya/sdvt2017/src/linuxcan/pcican2/../include/debug.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/../include/pshpack1.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/../include/poppack.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/memq.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/PciCan2HwIf.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/../include/VCanOsIf.h \ include/linux/poll.h \ include/uapi/linux/poll.h \ arch/x86/include/uapi/asm/poll.h \ include/uapi/asm-generic/poll.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/../include/canIfData.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/../include/vcanevt.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/../include/objbuf.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/../include/osif_common.h \ include/linux/irqreturn.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/../include/queue.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/../include/osif_functions_kernel.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/../include/softsync.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/../include/ticks.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/../include/osif_kernel.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/helios_dpram.h \ /home/diya/sdvt2017/src/linuxcan/pcican2/memQ.o: $(deps_/home/diya/sdvt2017/src/linuxcan/pcican2/memQ.o) $(deps_/home/diya/sdvt2017/src/linuxcan/pcican2/memQ.o):
Batchfile
module testbench; reg clk = 0; always #1 clk <= ~clk; vga v1(clk, r, g, b, hs, vs); initial begin $dumpvars; #2000000; $finish; end endmodule
Coq
package Arch_utils; use Exporter; @ISA = ('Exporter'); @EXPORT = (gen_archive); #========== Archive data to local or remote machine ============= # # gen_archive - General data archiver. This script was built # from the 2.5.4 subroutine "conv_archive" (Conv_utils.pm) # which archived the unpack and repack files to mass storage # at the end of the conventional data processing. While # "conv_archive" was tailored to work only with conventional # processing, this subroutine is general and can handle any # type of data. It will be archived to the standard directory # hierarchy used by the DAO for observational data. (CR #226). # That hierarchy is: # # /base/<job-type>/<source>/<format>/[subtype]/year/month/file # i.e., /u2/dao_ops/flk/wssmi_wind/ods/Y1999/M06/... # [ <subtype> is optional ] # # INPUTS: # environment (ops,val,test) # prep-id (flk, llk) # observation-type (wssmi_wind, nssmi_tpw, conv) # format of data to archive (ODS, native, ON29) # valid date of data (YYYYMMDD) # archive_location & base dir (dao_ops@gatun:/u2/dao_ops) # filename(s) (tpw.t19990602,/scratch1/lucchesi/ssmi.t19990704) # # OPTIONAL INPUT: # HASH table options argument: # delete => 0 (Default) Do not delete local files # delete => 1 Delete local files after archiving # direct => 1 (Default) Direct transfers - No ATM/NREN hopping # direct => 0 Use ATM/NREN when available # remdel => 0 (Default) Do not delete remote file before transfer # remdel => 1 Delete remote file before transfer (avoid dmget on overwrites) # remote_name => "string" remote name (default is local name). # subtype => "string" For file formats with a "subtype". # verbose => 1 Print diagnostic information # y4only => 0 (Default) Date must be 8 characters long # y4only => 1 date for subdir contains only year - no month # run_config => "string" Run_config file path and name (default = DEFAULT) # # RETURNS: # number of files transferred # # NOTES: Currently, filename(s) must either be fully-qualified # or the gen_archive working directory must be the same # directory that contains the file(s) to archive. Thus, a # PERL program calling gen_archive with relative pathnames # should CD to the directory with the data files first. # # USES: # File:Copy File:Path modules (standard) # Remote_utils module (DAO) # # EXAMPLE CALL: # # gen_archive ('ops','llk','wentz_ssmi','ods','19990701', # 'lucchesi@gatun:/silo1/stage2/lucchesi', # file1,file2,file3,{ 'subtype' => "wind", # 'verbose' => 1 } ); # # AUTHOR/REVISIONS: Rob Lucchesi # Initial 06/14/99 RL # Added 'delete' option 06/15/99 RL # Added 'subtype' option, new dir structure 06/17/99 RL # Added 'environment' parameter, verbose 07/20/99 RL # Added 'direct','remdel','remote_name' options 02/27/01 TO # Added 'run_config' option 04/03/01 TO # Added 'exp_path' option 04/20/07 TO # # HISTORY: # Evolved from Dave Lamich's "conv_archive" subroutine. # #======================================================================= sub gen_archive { # This module contains the copy() subroutine. use File::Copy; # This module contains the basename(), dirname() use File::Basename; # This module contains the mkpath() subroutine. use File::Path; # Any arithmetic done in this subroutine is done as integer. use integer; # Contains rput(), chmod_remote() and mkdir_remote() subroutines. use Remote_utils; # Get options (from last argument, if it is a hash reference). if ( ref( $_[$#_] ) eq "HASH" ) { %options = %{ pop( @_ ) }; } # Load arguments to local variables. my $environment = shift; # i.e., ops my $prep_id = shift; # i.e., llk my $obs_type = shift; # i.e., wentz_ssmi my $format = shift; # i.e., ods my $date = shift; # i.e., 19990615 or 1999061512 or 1999 my $archive_loc = shift; # i.e., dao_ops@gatun:/silo1/dao_ops @archived_files = @_; # filenames to archive # PROCESS THE OPTIONS FROM THE HASH TABLE # Option to specify a Run_Config file location if ( defined( %options ) && exists( $options{'run_config'} ) ) { $run_config = $options{'run_config'}; } else { $run_config = DEFAULT; } # Option indicating that prep ID is not included on the file names. if ( defined( %options ) && exists( $options{"no_prep_id"} ) ) { $no_prep_id = $options{"no_prep_id"}; } else { $no_prep_id = 0; } # Option to delete local file(s) after archive step. if ( defined( %options ) && exists( $options{"delete"} ) ) { $delete = $options{"delete"}; } else { $delete = 0; } # Verbose option if ( defined( %options ) && exists( $options{"verbose"} ) ) { $verbose = $options{"verbose"}; } else { $verbose = 0; } # Option to include subtype in the file path. if ( defined( %options ) && exists( $options{"subtype"} ) ) { $subtype = $options{"subtype"}; } else { $subtype = $obs_type; } # Option to specify different remote file name if ( defined( %options ) && exists( $options{"remote_name"} ) ) { if (! $#archived_files ) { $remote_name = $options{"remote_name"}; $use_remote = 1; } else{ warn "Can't specify remote name for multiple file transfers.\n"; $use_remote = 0; } } else { $use_remote = 0; } # Option to specify deletion of remote file before transfer if ( defined( %options ) && exists( $options{"remdel"} ) ) { $remote_delete = $options{"remdel"}; } else { $remote_delete = 0; } # Option to specify file permissions if ( defined( %options ) && exists( $options{"filemode"} ) ) { $filemode = $options{"filemode"}; } else { $filemode = '0644'; } # Option to specify directory permissions if ( defined( %options ) && exists( $options{"dirmode"} ) ) { $dirmode = $options{"dirmode"}; } else { $dirmode = '0755'; } # Option to specify y4only date if ( defined( %options ) && exists( $options{"y4only"} ) ) { $y4only = $options{"y4only"}; } else { $y4only = 0; } # Option to specify no ATM/NREN hopping if ( defined( %options ) && exists( $options{"direct"} ) ) { $direct = $options{"direct"}; } else { $direct = 1; } # Option to specify explicit archive path if ( defined( %options ) && exists( $options{"exp_path"} ) ) { $explicit_path = $options{"exp_path"}; } else { $explicit_path = 0; } # DETERMINE ARCHIVE LOCATION if ( $archive_loc =~ /@/ && $archive_loc !~ /:/ ) { $archive_loc = "$archive_loc:"; } # If the archive location does not end with a ":" or a "/", then assume # some path has been given, and put a "/" there to allow later appending # of the subdirectory. if ( $archive_loc !~ m'[:/]$' ) { $archive_loc = "$archive_loc/"; } $files_trans = 0; # Parse date information. if ((length($date) != 8)&&( ! $y4only )) { print "gen_archive: Date must be 8 characters (YYYYMMDD)\n"; return -1; } $year = substr ($date, 0, 4); if (! $y4only) { $month = substr ($date, 4, 2); } # Process each file. foreach $sfile ( @archived_files ) { if ($y4only) { $subdir = join("/",$environment,$prep_id,$obs_type,$format, $subtype,"Y$year"); }else{ $subdir = join("/",$environment,$prep_id,$obs_type,$format, $subtype,"Y$year","M$month"); } if ($explicit_path){ $subdir =""; } if (! $use_remote ) { $remote_name = basename($sfile); } if ($verbose) { print "Will put $sfile as $archive_loc$subdir\/$remote_name\n"; } # Check if the location to archive to is a remote location. If so, use the # remote put function. Otherwise, just do a copy. Make the directory first. # File and directory permission modes are also explicitly set. Note that mkpath # interacts with the umask, so even though it defaults to 0777, it must be reset # to what we want. $err_trans = 0; if ( $archive_loc =~ /:/ ) { if ($remote_delete) { %options = ( 'exist' => 1, 'debug' => $verbose, 'run_config' => $run_config ); @rc=rflist("$archive_loc$subdir/$remote_name",\%options); if ($rc[0]) { %options = ( 'debug' => $verbose, 'run_config' => $run_config ); $rc=rm_remote_file("$archive_loc$subdir/$remote_name", \%options); if ($verbose) { print "rm_remote_file returned $rc\n"; } } } %options = ( 'exist' => 1, 'debug' => $verbose, 'run_config' => $run_config ); @rc=rflist("$archive_loc$subdir",\%options); if (! $rc[0]) { print "Creating remote directory: $archive_loc$subdir .\n"; %options = ( 'debug' => $verbose, 'run_config' => $run_config ); mkdir_remote( "$archive_loc$subdir", \%options ) or $err_trans = 1; print "err_trans = $err_trans\n"; %options = ( 'recursive' => 1, 'verbose' => $verbose, 'run_config' => $run_config ); chmod_remote( "$archive_loc$subdir", $dirmode, \%options) or $err_trans = 2; print "err_trans = $err_trans\n"; } print "run_config = $run_config\n"; %options = ( 'direct' => $direct, 'mode' => $filemode, 'run_config' => $run_config, 'debug' => $verbose ); rput("$sfile", "$archive_loc$subdir/$remote_name", \%options) or $err_trans = 3; print "err_trans = $err_trans\n"; } else { if ( ! -d "$archive_loc$subdir" ) { mkpath( "$archive_loc$subdir" ) or $err_trans = 4; chmod( oct($dirmode), "$archive_loc$subdir" ) or $err_trans = 5; } if ( ($remote_delete) && ( -e "$archive_loc$subdir/$remote_name") ){ unlink ("$archive_loc$subdir/$remote_name") or $err_trans = 6; } copy( "$sfile", "$archive_loc$subdir/$remote_name" ) or $err_trans = 7; chmod( oct($filemode), "$archive_loc$subdir/$remote_name" ) or $err_trans = 8; } if ( $err_trans ) { print STDERR "(gen_archive) ERROR $err_trans - Could not transfer $sfile to $archive_loc$subdir/$remote_name","\n"; } else { ++ $files_trans; if ($delete) { unlink "$sfile"; } } } return( $files_trans ); } #================= Stage the repack data ====================== sub gen_stage { # This module contains the copy() subroutine. use File::Copy; # This module contains the mkpath() subroutine. use File::Path; # This module contains the rput(), chmod_remote() and mkdir_remote() subroutines. use Remote_utils; }
Perl
## This will take the results file that was created using the combineMAF code and create 2 mutation files setwd('./') results = read.csv("mucinous_ovarian_cancer_results_for_fig.csv", header=T, stringsAsFactors = F, sep="\t") # If you are doing a sample set where there are multiple components you can use this to set the overall samples to get individual plots # Otherwise this is just set to make all samples from one patient to make one plot. results$Patient = "A" #substr(results$NORMAL_SAMPLE, 1, nchar(results$NORMAL_SAMPLE)-1) patients = unique(results$Patient) samples = unique(results$TUMOR_SAMPLE) #### If not all of the samples have mutations then this won't add those samples into the figure. # Alternative method of getting sample list: # files = list.files(pattern = "\\cncf.txt$") # samples = c(as.data.frame(strsplit(files, "_"))[1,]) # samples = as.vector(unname(samples)) # samples = as.character(unlist(samples)) b=1 #for (b in 1:length(patients)){ muts = results[results$Patient == patients[b],] muts = muts[!is.na(muts$Cancer_Cell_Fraction),] plot_file = paste('Mutation_Heatmap', patients[b], ".pdf", sep="") plot_file_CCF = paste('CCF_Heatmap', patients[b], ".pdf", sep="") ######################################################## muts$CCF_group = "0" for (i in 1:nrow(muts)){ if(muts$Cancer_Cell_Fraction[i] <= 1 & muts$Cancer_Cell_Fraction[i] > 0.8){muts$CCF_group[i] = 5} if(muts$Cancer_Cell_Fraction[i] <= 0.8 & muts$Cancer_Cell_Fraction[i] > 0.6){muts$CCF_group[i] = 4} if(muts$Cancer_Cell_Fraction[i] <= 0.6 & muts$Cancer_Cell_Fraction[i] > 0.4){muts$CCF_group[i] = 3} if(muts$Cancer_Cell_Fraction[i] <= 0.4 & muts$Cancer_Cell_Fraction[i] > 0.2){muts$CCF_group[i] = 2} if(muts$Cancer_Cell_Fraction[i] <= 0.2 & muts$Cancer_Cell_Fraction[i] > 0.05){muts$CCF_group[i] = 1} } muts = muts[order(muts$SYMBOL, decreasing=F),] muts = muts[!is.na(muts$Cancer_Cell_Fraction),] muts = muts[order(muts$CCF_group, decreasing=T),] muts = muts[order(muts$TUMOR_SAMPLE, decreasing=F),] ###### Do any necessary filtering of mutation dataframe ######## #muts = subset(muts, subset = muts$patient == "RG6T") #| muts$TUMOR_SAMPLE == "AM2" | muts$TUMOR_SAMPLE == "AM3" | muts$TUMOR_SAMPLE == "AM4" | muts$TUMOR_SAMPLE == "AM5 - Primary_AME" | muts$TUMOR_SAMPLE == "AM6" | muts$TUMOR_SAMPLE == "AM7" | muts$TUMOR_SAMPLE == "AM32AME1")# & muts$TUMOR_SAMPLE != "AM8-Ips-Breast-Rec-Carc" & muts$TUMOR_SAMPLE != "AM5 - Axillary_Lymph_Node_Metastasis" & muts$TUMOR_SAMPLE != "AM46T2" & muts$TUMOR_SAMPLE != "AM5 - Primary_Carcarcinoma" & muts$TUMOR_SAMPLE != "AM8-LNE" & muts$TUMOR_SAMPLE != "AM8-LNM") muts = subset(muts, subset = muts$Variant_Classification != "synonymous_variant")# & muts$ANN....EFFECT != "splice_region_variant&synonymous_variant" & muts$ANN....EFFECT != "downstream_ANN....GENE_variant" # & muts$ANN....EFFECT != "intron_variant" & muts$ANN....EFFECT != "frameshift_variant&splice_donor_variant&splice_region_variant&splice_region_variant&intron_variant" #& muts$ANN....EFFECT != "non_coding_exon_variant|synonymous_variant" & muts$ANN....EFFECT != "SYNONYMOUS_CODING" & muts$ANN....EFFECT != "splice_acceptor_variant&splice_region_variant&intron_variant" & muts$ANN....EFFECT != "Silent") #muts = subset(muts, subset = muts$ANN....EFFECT != "downstream_gene_variant|synonymous_variant" & muts$ANN....EFFECT != "upstream_gene_variant|5_prime_UTR_variant") #muts = subset(muts, subset = muts$lawrence=="TRUE" | muts$kandoth =="TRUE" | muts$cancer_gene_census == "TRUE") sample_names = as.list(sort(unique(muts$TUMOR_SAMPLE))) if(length(sample_names) == 1){ sample_names = c(sample_names, "Spacer")} mutation_genes = unique(muts$SYMBOL) if(length(mutation_genes) == 1){ mutation_genes = c(mutation_genes, "Spacer")} rownames(muts) = 1:nrow(muts) ########################################################################### #impact410_list = read.csv('/Users/selenicp/Documents/Code/IMPACT410_genes.csv', header = T, stringsAsFactors = F) # impact341 = read.csv('/Users/burkek/Documents/Code/IMPACT341_genes.csv', header =T, stringsAsFactors = F) #impact410_list = unique(c(impact410_list$Approved.Symbol, impact410_list$HGNC.symbol)) #mutation_genes = unique(c(intersect(mutation_genes,impact410_list))) #muts = muts[muts$ANN....GENE %in% mutation_genes,] ########################################################################### return_gene_order = T sort_samples = T sort_genes = T show_sample_names = T TCGA = F remove_genes_with_no_mutation = F width = NULL height = NULL include_percentages = T sample_name_col = "TUMOR_SAMPLE" #### Make a matrix of "blank" values the with nrow= #mutations and ncol=#samples mutation_heatmap <- matrix(9, nrow=sum(unlist(lapply(sample_names, length))), ncol=sum(unlist(lapply(mutation_genes, length)))) rownames(mutation_heatmap) <- unlist(sample_names) colnames(mutation_heatmap) <- paste(mutation_genes) #### Make sure the sample and mutations are both in the list of gene mutations and gene samples if (!TCGA) { smallmaf <- muts[which(muts$SYMBOL %in% unlist(mutation_genes) & muts$TUMOR_SAMPLE %in% unlist(sample_names)),] }else { muts$id <- unlist(lapply(muts$TUMOR_SAMPLE, function(x){substr(x, 1, 12)})) print(head(muts$id)) print(head(unlist(sample_names))) smallmaf <- muts[which(muts$Hugo_Symbol %in% unlist(mutation_genes) & muts$id %in% unlist(sample_names)),] } ### Define categories for different Effects cat1 <- c('missense_variant_hotspot', 'stop_gained_hotspot','missense_variant&splice_region_variant_hotspot') cat2 <- c("STOP_GAINED", "Nonsense_Mutation", "stop_gained&splice_region_variant", "stop_gained", "stop_gained&inframe_insertion", "stop_gained&disruptive_inframe_insertion", "stop_gained&disruptive_inframe_insertion&splice_region_variant", "stop_gained&inframe_insertion|stop_gained&inframe_insertion", "stop_gained&inframe_insertion&splice_region_variant", "stop_gained|stop_gained" ) cat3 <- c("frameshift_indel","FRAME_SHIFT", "FRAME_SHIFT", "frameshift_variant&stop_lost", "frameshift_variant&stop_lost|frameshift_variant&stop_lost", "frameshift_variant&start_lost","frameshift_variant&splice_acceptor_variant&splice_region_variant&intron_variant", "Frame_Shift_Del", "Frame_Shift_Ins", "frameshift_variant", "frameshift_variant|frameshift_variant", "frameshift_variant&stop_gained", "frameshift_variant&splice_region_variant", "frameshift_variant&splice_acceptor_variant&splice_region_variant&splice_region_variant&intron_variant", "frameshift_variant&splice_donor_variant&splice_region_variant&intron_variant", "frameshift_variant&stop_gained&splice_region_variant", "frameshift_variant&stop_gained|frameshift_variant&stop_gained","frameshift_variant&splice_acceptor_variant&splice_donor_variant&splice_region_variant&splice_region_variant&splice_region_variant&intron_variant" ) cat4 <- c("missense_snv_recurrent","missense_snv","NON_SYNONYMOUS_CODING", "Missense_Mutation", "missense_variant", "missense_variant&splice_region_variant", "missense_variant|missense_variant", "missense_variant|missense_variant|missense_variant|missense_variant|missense_variant|missense_variant|missense_variant|missense_variant|missense_variant", "missense_variant|missense_variant|missense_variant", "missense_variant&splice_region_variant|missense_variant&splice_region_variant","missense_variant|protein_protein_contact|protein_protein_contact|protein_protein_contact|protein_protein_contact|protein_protein_contact|protein_protein_contact|protein_protein_contact") cat5 <- c("inframe_indel_recurrent","inframe_indel","CODON_CHANGE_PLUS_CODON_DELETION", "CODON_DELETION", "CODON_INSERTION", "In_Frame_Ins", "In_Frame_Del", "inframe_deletion|inframe_deletion", "disruptive_inframe_deletion", "disruptive_inframe_insertion", "inframe_deletion", "inframe_insertion", "disruptive_inframe_deletion&splice_region_variant", "inframe_deletion&splice_region_variant", "inframe_insertion&splice_region_variant", "disruptive_inframe_insertion|disruptive_inframe_insertion", "disruptive_inframe_insertion&splice_region_variant", "inframe_insertion|inframe_insertion", "disruptive_inframe_deletion|disruptive_inframe_deletion" ) cat6 <- c("splice_donor_variant&intron_variant|splice_donor_variant&intron_variant","splice_acceptor_variant&intron_variant|splice_acceptor_variant&intron_variant","splice_acceptor_variant&splice_donor_variant&intron_variant","splice_mut","SPLICE_SITE_DONOR", "SPLICE_SITE_ACCEPTOR", "SPLICE_SITE_REGION", "Splice_Site", "splice_donor_variant&intron_variant", "splice_acceptor_variant&intron_variant", "splicing", "splice_donor_variant&splice_region_variant&intron_variant", "splice_donor_variant&disruptive_inframe_deletion&splice_region_variant&splice_region_variant&intron_variant", "splice_donor_variant&inframe_deletion&splice_region_variant&splice_region_variant&intron_variant", "splice_acceptor_variant&inframe_deletion&splice_region_variant&splice_region_variant&intron_variant", "Splice_Region", "splice_acceptor_variant&5_prime_UTR_truncation&exon_loss_variant&splice_region_variant&intron_variant|start_lost&inframe_deletion&splice_region_variant", "splice_acceptor_variant&disruptive_inframe_deletion&splice_region_variant&intron_variant","splice_acceptor_variant&splice_region_variant&intron_variant&non_coding_exon_variant", "splice_acceptor_variant&splice_region_variant&intron_variant") cat7 <- c("STOP_LOST", "START_LOST", "START_GAINED", "UTR_5_PRIME", "start_lost", "stop_lost", "start_lost&inframe_deletion", "stop_lost&splice_region_variant", "stop_lost&disruptive_inframe_insertion") cat8 <- c("upstream_gene_variant","downstream_gene_variant|synonymous_variant", "upstream_gene_variant|5_prime_UTR_variant","upstream_gene_variant|synonymous_variant") cat9 <- c("nonsense_snv","synonymous_variant","Silent", "splice_region_variant&synonymous_variant", "downstream_gene_variant", "intron_variant", "frameshift_variant&splice_donor_variant&splice_region_variant&splice_region_variant&intron_variant", "non_coding_exon_variant|synonymous_variant", "SYNONYMOUS_CODING", "synonymous_variant|synonymous_variant", "splice_region_variant&synonymous_variant|splice_region_variant&non_coding_exon_variant", "intergenic_region", "intron_variant","intron_variant|downstream_gene_variant","intron_variant|intron_variant","intergenic_region|downstream_gene_variant","intron_variant|upstream_gene_variant") #### For each row read the Effect and create the type based on which category it fits in #### If there is an error because the mutation type is unknow just add it to the correct category above smallmaf$mut_type = '0' smallmaf$types = '0' for (i in 1:nrow(smallmaf)) { if(!TCGA) { type = smallmaf$Variant_Classification[i] } else { type = smallmaf$Variant_Classification[i] } if (smallmaf$HOTSPOT[i] == "TRUE" || type %in% cat1) { type = 1; smallmaf$mut_type[i] = 'A'; smallmaf$types[i] = 1 } else if (type %in% cat2) { type = 2; smallmaf$mut_type[i] = 'B'; smallmaf$types[i] = 2 } else if (type %in% cat3) { type = 3; smallmaf$mut_type[i] = 'C'; smallmaf$types[i] = 3 } else if (type %in% cat4) { type = 4; smallmaf$mut_type[i] = 'D'; smallmaf$types[i] = 4 } else if (type %in% cat5) { type = 5; smallmaf$mut_type[i] = 'E'; smallmaf$types[i] = 5 } else if (type %in% cat6) { type = 6; smallmaf$mut_type[i] = 'F'; smallmaf$types[i] = 6 } else if (type %in% cat7) { type = 7; smallmaf$mut_type[i] = 'G'; smallmaf$types[i] = 7 } else if (type %in% cat8) { type = 8; smallmaf$mut_type[i] = 'H'; smallmaf$types[i] = 8 } else if (type %in% cat9) { type = 9; smallmaf$mut_type[i] = 'I'; smallmaf$types[i] = 9 } else {print(paste(i,type,sep="_")) stop("Mutation type not found")} print(paste(i,type,sep="_")) if (!TCGA) { if (mutation_heatmap[which(rownames(mutation_heatmap)==smallmaf$TUMOR_SAMPLE[i],), which(colnames(mutation_heatmap)==smallmaf$SYMBOL[i])] > type) { mutation_heatmap[which(rownames(mutation_heatmap)==smallmaf$TUMOR_SAMPLE[i],), which(colnames(mutation_heatmap)==smallmaf$SYMBOL[i])] <- type }else { mutation_heatmap[which(rownames(mutation_heatmap)==smallmaf$TUMOR_SAMPLE[i]), which(colnames(mutation_heatmap)==smallmaf$Hugo[i])] <- type } } } ############################### # Order CCF-Group CCFgroup_heatmap <-matrix(0, nrow=sum(unlist(lapply(sample_names, length))), ncol=sum(unlist(lapply(mutation_genes, length)))) rownames(CCFgroup_heatmap) <- unlist(sample_names) colnames(CCFgroup_heatmap) <- mutation_genes for (i in 1:nrow(smallmaf)) { type = smallmaf$CCF_group[i] if (CCFgroup_heatmap[which(rownames(CCFgroup_heatmap)==smallmaf$TUMOR_SAMPLE[i],), which(colnames(CCFgroup_heatmap)==smallmaf$SYMBOL[i])] < type) { CCFgroup_heatmap[which(rownames(CCFgroup_heatmap)==smallmaf$TUMOR_SAMPLE[i],), which(colnames(CCFgroup_heatmap)==smallmaf$SYMBOL[i])] <- type} } i=1 for (i in 1 :nrow(mutation_heatmap)){ mutation_heatmap = mutation_heatmap[, order(CCFgroup_heatmap[nrow(CCFgroup_heatmap)-(i-1),], decreasing = T) ] CCFgroup_heatmap = CCFgroup_heatmap[, order(CCFgroup_heatmap[nrow(CCFgroup_heatmap)-(i-1),], decreasing = T) ] } ####################################### if (sort_samples) { mutation_heatmap <- do.call(rbind, lapply(sample_names, function(x) { m <- mutation_heatmap[which(rownames(mutation_heatmap) %in% x),, drop=F]; m[do.call(order, transform(m)),]})) } rownames(mutation_heatmap) <- unlist(sample_names) #### Sort genes by the number of mutations that do not equal the blank category if(sort_genes) { print("Sorting genes") oo <- unlist(apply(mutation_heatmap,2, function(x){length(which(x!=9))})) print(oo) oo <- oo[which(!duplicated(names(oo)))] oo <- names(sort(oo, decr=T)) mutation_heatmap <- mutation_heatmap[,match(unlist(oo), colnames(mutation_heatmap))] } if(remove_genes_with_no_mutation) { mutation_heatmap <- mutation_heatmap[,which(unlist(apply(mutation_heatmap,2, function(x){length(which(x!=10))}))!=0)] } #order_heatmap = ifelse(mutation_heatmap==9, 2, 1) i=1 #for (i in 1 :ncol(mutation_heatmap)){ # mutation_heatmap = mutation_heatmap[ order(order_heatmap[,ncol(mutation_heatmap)-(i-1)]) , ] # order_heatmap = order_heatmap[ order(order_heatmap[,ncol(mutation_heatmap)-(i-1)]) , ] #} ## mutation_heatmap = t(mutation_heatmap) #### Choose color palette for table - set to colkey library(RColorBrewer) colkey <- cbind(1:9, c(brewer.pal(8, "Set1"), "white")) colkey[1,2]="#CD1719" colkey[2,2]="#984EA3" colkey[3,2]="#377EB8" colkey[4,2]="#4DAF4A" colkey[5,2]="#FF7F00" colkey[6,2]="#FFFF33" colkey[7,2]="#A65628" colkey[8,2]="#808080" colkey[9,2]="gray85" width=height=NULL if (is.null(width)) { width = 1+(length(unlist(mutation_genes))/1.5) } if (width<4){width=4} if (is.null(height)) { height = 1+(length(unlist(sample_names)))/2 } if (height<4){height=4} mutation_heatmap <- t(mutation_heatmap) #### Create empty pdf height = height+1 pdf(plot_file, width=height, height=width) if (show_sample_names) { top=8 } else {top = 2} if (include_percentages) { right= 4 } else { right=1 } #### Plot figure par(oma=c(2,8,1,1), mar=c(2,5,top,right)) image(mutation_heatmap, xaxt='n', yaxt='n', col=colkey[,2], zlim=c(1,9), xlab="", ylab="") axis(2, at=seq(0, 1, 1/(ncol(mutation_heatmap)-1)), labels=colnames(mutation_heatmap), las=2, tick=F, cex.axis=2, font = 3, family = 'sans') axis(3, at=seq(0, 1, 1/(nrow(mutation_heatmap)-1)), labels=rownames(mutation_heatmap), las=2, tick=F, cex.axis=2, font = 1, family = 'sans') abline(v=(0:nrow(mutation_heatmap)/(nrow(mutation_heatmap)-1)+(1/(2*(nrow(mutation_heatmap)-1)))), col = "white") abline(h=(0:ncol(mutation_heatmap)/(ncol(mutation_heatmap)-1)+(1/(2*(ncol(mutation_heatmap)-1)))), col = "white") dev.off() mutation_heatmap <- t(mutation_heatmap) ########################## ## Mutation type ggplot ## ########################## library(ggplot2) df11 <-as.data.frame(cbind(smallmaf$TUMOR_SAMPLE, smallmaf$SYMBOL, smallmaf$Cancer_Cell_Fraction, smallmaf$Clonal_Status, smallmaf$loh, smallmaf$mut_type, smallmaf$types)) colnames(df11) <- c("samples", "genes", "ccf", "clone", "loh", "mut_type", "types") df11 <- df11[order(df11$samples, df11$types, decreasing=TRUE),] df11 <- as.data.frame(lapply(df11, function(x) {sub("DL-moc-0", "MOC", x)})) ## Modify samples names (if required) df11 <- as.data.frame(lapply(df11, function(x) {sub("DL-moc-00", "MOC", x)})) ## Modify samples names (if required) df11$genes <- factor(df11$genes, levels = dput(rev(rownames(mutation_heatmap)))) cols <- c('A'="#CD1719",'B'="#984EA3",'C'="#377EB8",'D'="#4DAF4A",'E'="#FF7F00",'F'="#FFFF33",'G'="#A65628", 'H' = "#808080", 'I' = "gray85") comb<-expand.grid(samples = unique(df11$samples), genes = unique(df11$genes), ccf=".", clone = ".", loh=".", mut_type="I", types = 9) df33 <- as.data.frame(rbind(comb, df11)) df22<-subset(df11,clone=="Clonal") pdf("Mut_type_ggplot.pdf", width=12, height=89) #p <- ggplot(df33, aes(x=samples,y=genes,fill=mut_type,group=loh)) + geom_tile(width=0.8,height=0.8) + geom_tile(data=df22,aes(samples, genes),size=1,fill=NA,width=0.8,height=0.8,color="gold3") + scale_fill_manual(values = cols, name="CCF",guide = FALSE); p + geom_segment( aes(x=xmin,xend=xmax,y=ymin,yend=ymax), subset(ggplot_build(p)$data[[1]],group==2), inherit.aes=F,color="white",size=0.5) + theme(axis.text.x=element_text(size=20, family = "sans", angle = 90, hjust=0, vjust=0)) + theme(axis.text.y=element_text(size=20, face="italic", family = "sans")) + scale_x_discrete(name="",position="top",drop=FALSE) + scale_y_discrete(name="",drop=FALSE) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), panel.border = element_blank()) + theme(legend.position="none") + theme(axis.ticks = element_blank()) + theme(axis.text=element_text(colour = "black")) p <- ggplot(df33, aes(x=samples,y=genes,fill=mut_type,group=loh)) + geom_tile(width=0.8,height=0.8) + scale_fill_manual(values = cols, name="CCF",guide = FALSE); p + geom_segment( aes(x=xmin,xend=xmax,y=ymin,yend=ymax), subset(ggplot_build(p)$data[[1]],group==2), inherit.aes=F,color="white",size=1) + theme(axis.text.x=element_text(size=20, family = "sans", angle = 90, hjust=0, vjust=0)) + theme(axis.text.y=element_text(size=20, face="italic", family = "sans")) + scale_x_discrete(name="",position="top",drop=FALSE) + scale_y_discrete(name="",drop=FALSE) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), panel.border = element_blank()) + theme(legend.position="none") + theme(axis.ticks = element_blank()) + theme(axis.text=element_text(colour = "black")) dev.off() ########################### gene_order = rownames(mutation_heatmap)#[length(rownames(mutation_heatmap)):1] samp_order = colnames(mutation_heatmap) if(return_gene_order) { list(rev(colnames(mutation_heatmap))) } return_gene_order = F sort_samples = T sort_genes = T show_sample_names = T TCGA = F remove_genes_with_no_mutation = F # width = NULL # height = NULL include_percentages = F sample_name_col = "TUMOR_SAMPLE" mutation_genes=unique(muts$SYMBOL) #### Make a matrix of "blank" values the with nrow= #mutations and ncol=#samples mutation_heatmap <- matrix(1, nrow=sum(unlist(lapply(samp_order, length))), ncol=sum(unlist(lapply(gene_order, length)))) rownames(mutation_heatmap) <- samp_order colnames(mutation_heatmap) <- gene_order #### Make sure the sample and mutations are both in the list of gene mutations and gene samples #if (!TCGA) { smallmaf <- muts[which(muts$ANN....GENE %in% unlist(mutation_genes) & muts$TUMOR_SAMPLE %in% unlist(sample_names)),] #}else { # muts$id <- unlist(lapply(muts$TUMOR_SAMPLE, function(x){substr(x, 1, 12)})) # print(head(muts$id)) # print(head(unlist(sample_names))) # smallmaf <- muts[which(muts$Hugo_Symbol %in% unlist(mutation_genes) & muts$id %in% unlist(sample_names)),] #} #### For each row read the Effect and create the type based on which category it fits in for (i in 1:nrow(smallmaf)) { if(!TCGA) { type = smallmaf$Cancer_Cell_Fraction[i] } else { type = smallmaf$Variant_Classification[i] } if (type == 0) { type = 1 } else if (type >0 & type<=0.05) { type = 2 } else if (type >0.05 & type<=0.2) { type = 3 } else if (type >0.2 & type<=0.4) { type = 4 } else if (type >0.4 & type<=0.6) { type = 5 } else if (type >0.6 & type<=0.8) { type = 6 } else if (type >0.8 & type<=1) { type = 7 } else { print("Mutation type not found") } print(paste(i,type,sep="_")) if (mutation_heatmap[which(rownames(mutation_heatmap)==smallmaf$TUMOR_SAMPLE[i],), which(colnames(mutation_heatmap)==smallmaf$SYMBOL[i])] < type) { mutation_heatmap[which(rownames(mutation_heatmap)==smallmaf$TUMOR_SAMPLE[i],), which(colnames(mutation_heatmap)==smallmaf$SYMBOL[i])] <- type} } if(remove_genes_with_no_mutation) { mutation_heatmap <- mutation_heatmap[,which(unlist(apply(mutation_heatmap,2, function(x){length(which(x!=10))}))!=0)] } df=data.frame(matrix(ncol = 0, nrow = nrow(mutation_heatmap))) for (i in 1:length(gene_order)){ print(i) df = cbind.data.frame(df, mutation_heatmap[ , colnames(mutation_heatmap)== gene_order[i]]) colnames(df)[i]=gene_order[i] } rownames(df)=rownames(mutation_heatmap) newdf=data.frame(matrix(ncol = 0, nrow = ncol(mutation_heatmap))) for (i in 1:length(samp_order)){ print(i) newdf= rbind.data.frame(newdf, df[rownames(mutation_heatmap) == samp_order[i],]) rownames(newdf)[i]=samp_order[i] } colnames(newdf)=colnames(df) mutation_heatmap <- as.matrix(newdf) #### Choose color palette for table - set to colkey library(RColorBrewer) colkey <- cbind(1:7, c("grey90", "#C6DBEF", "#9ECAE1", "#6BAED6", "#2171B5", "#08519C", "#08306B")) mutation_heatmap = t(mutation_heatmap) ################### #### Make a matrix of "blank" values the with nrow= #mutations and ncol=#samples LOH_heatmap <- matrix(0, ncol=sum(unlist(lapply(gene_order, length))), nrow=sum(unlist(lapply(samp_order, length)))) colnames(LOH_heatmap) <- gene_order rownames(LOH_heatmap) <- samp_order for (i in 1:nrow(smallmaf)) { type = smallmaf$loh[i] if (type == "loh") { type = 1 # } else if (type >0 & type<=0.05) { type = 2 } else { type = 0 } print(paste(i,type,sep="_")) if (LOH_heatmap[which(rownames(LOH_heatmap)==smallmaf$TUMOR_SAMPLE[i]), which(colnames(LOH_heatmap)==smallmaf$SYMBOL[i],)] < type) { LOH_heatmap[which(rownames(LOH_heatmap)==smallmaf$TUMOR_SAMPLE[i]), which(colnames(LOH_heatmap)==smallmaf$SYMBOL[i],)] <- type} } ########################################################################################################################## ########################################################################################################################## #### Make a matrix of "blank" values the with nrow= #mutations and ncol=#samples Clonal_heatmap <- matrix(0, ncol=sum(unlist(lapply(gene_order, length))), nrow=sum(unlist(lapply(samp_order, length)))) colnames(Clonal_heatmap) <- gene_order rownames(Clonal_heatmap) <- samp_order for (i in 1:nrow(smallmaf)) { # type = smallmaf$clonality[i] # if (type == "clonal") { type = 1 type = smallmaf$Clonal_Status[i] if (type == "Clonal") { type = 1 # } else if (type >0 & type<=0.05) { type = 2 } else { type = 0 } print(paste(i,type,sep="_")) if (Clonal_heatmap[which(rownames(Clonal_heatmap)==smallmaf$TUMOR_SAMPLE[i]), which(colnames(Clonal_heatmap)==smallmaf$SYMBOL[i],)] < type) { Clonal_heatmap[which(rownames(Clonal_heatmap)==smallmaf$TUMOR_SAMPLE[i]), which(colnames(Clonal_heatmap)==smallmaf$SYMBOL[i],)] <- type} } ########################################################################################################################## ########################################################################################################################## #### Create empty pdf pdf(plot_file_CCF, height = height, width=width) if (show_sample_names) { top=8 } else {top = 2} if (include_percentages) { right= 4 } else { right=1 } #Clonal_heatmap <- Clonal_heatmap[,rowSums(mutation_heatmap != 1) > 1] #LOH_heatmap <- LOH_heatmap[,rowSums(mutation_heatmap != 1) > 1] #mutation_heatmap <- mutation_heatmap[rowSums(mutation_heatmap != 1) > 1,] ########################################################################################################################## ########################################################################################################################## #### Create empty pdf #width=height=NULL #if (is.null(width)) { width = 1+nrow(mutation_heatmap)/1.5 } #if (width<4){width=4} #if (is.null(height)) { height = 1+(length(unlist(sample_names)))/2 } #if (height<4){height=4} #pdf(plot_file_CCF, height = height, width=width) #if (show_sample_names) { top=8 } else {top = 2} #if (include_percentages) { right= 4 } else { right=1 } #### Plot figure par(oma=c(2,8,1,1), mar=c(2,5,top,right)) #par(mar=c(2,4,2,2)) image(mutation_heatmap, xaxt='n', yaxt='n', col=colkey[,2], zlim=c(1,7), xlab="", ylab="") #axis(1, at=seq(0, 1, 1/(ncol(mutation_heatmap)-1)), labels=colnames(mutation_heatmap), las=2, tick=F) axis(2, at=seq(0, 1, 1/(ncol(mutation_heatmap)-1)), labels=colnames(mutation_heatmap), las=2, tick=F, cex.axis=2, font = 3, family = 'sans') axis(3, at=seq(0, 1, 1/(nrow(mutation_heatmap)-1)), labels=rownames(mutation_heatmap), las=2, tick=F, cex.axis=1.2, font = 2, family = 'sans') if(include_percentages) { axis(4, at=seq(0, 1, 1/(ncol(mutation_heatmap)-1)), labels=unlist(apply(mutation_heatmap, 2, function(x) { paste(round(100*length(which(x!=1))/length(x), 0), "%")})), las=2, tick=F)} # abline(v=(0:nrow(mutation_heatmap)/(nrow(mutation_heatmap)-1)+(1/(2*(nrow(mutation_heatmap)-1)))), col = "white") # abline(h=(0:ncol(mutation_heatmap)/(ncol(mutation_heatmap)-1)+(1/(2*(ncol(mutation_heatmap)-1)))), col = "white") row_pos = 0:nrow(mutation_heatmap)/(nrow(mutation_heatmap)-1) row_pos = row_pos[!row_pos>1] col_pos = 0:ncol(mutation_heatmap)/(ncol(mutation_heatmap)-1) col_pos = col_pos[!col_pos>1] # LOH_heatmap = LOH_heatmap[,ncol(LOH_heatmap):1] # LOH_heatmap= t(LOH_heatmap) LOH_heatmap = LOH_heatmap[nrow(LOH_heatmap):1,] for (i in 1:nrow(LOH_heatmap)){ row_plot = row_pos[as.vector(LOH_heatmap[i,]==1)] points( row_plot, rep(col_pos[(length(samp_order)+1)-i],length(row_plot)), pch="/", col="white", cex = 3) } Clonal_heatmap = Clonal_heatmap[nrow(Clonal_heatmap):1,] for (i in 1:nrow(Clonal_heatmap)){ row_plot = row_pos[as.vector(Clonal_heatmap[i,]==1)] points( row_plot, rep(col_pos[(length(samp_order)+1)-i],length(row_plot)), pch=16, col="yellow", cex = 2) } dev.off() ########################## ## CCF heatmap (ggplot) ## ########################## library(ggplot2) df1 <-as.data.frame(cbind(smallmaf$TUMOR_SAMPLE, smallmaf$SYMBOL, smallmaf$Cancer_Cell_Fraction, smallmaf$Clonal_Status, smallmaf$loh, smallmaf$CCF_group, smallmaf$types)) colnames(df1) <- c("samples", "genes", "ccf", "clone", "loh", "ccf_groupA", "types") df1 <- df1[order(df1$samples, df1$types, decreasing=TRUE),] df1$ccf_groupB = "0" for (i in 1:nrow(df1)){ if(df1$ccf_groupA[i] == 5){df1$ccf_groupB[i]= 'A'} if(df1$ccf_groupA[i] == 4){df1$ccf_groupB[i]= 'B'} if(df1$ccf_groupA[i] == 3){df1$ccf_groupB[i]= 'C'} if(df1$ccf_groupA[i] == 2){df1$ccf_groupB[i]= 'D'} if(df1$ccf_groupA[i] == 1){df1$ccf_groupB[i]= 'E'} } df1 <- as.data.frame(lapply(df1, function(x) {sub("DL-moc-0", "MOC", x)})) ## Modify samples names (if required) df1 <- as.data.frame(lapply(df1, function(x) {sub("DL-moc-00", "MOC", x)})) ## Modify samples names (if required) cols <- c('A'="#08306B",'B'="#08519C",'C'="#2171B5",'D'="#6BAED6",'E'="#9ECAE1",'F'="#C6DBEF",'G'="gray85") df2<-subset(df1,clone=="Clonal") df1$genes <- factor(df1$genes, levels = dput(rev(rownames(mutation_heatmap)))) comb<-expand.grid(samples = unique(df1$samples), genes = unique(df1$genes), ccf=".", clone = ".", loh=".", ccf_groupA = ".", types = ".", ccf_groupB="G") df3 <- as.data.frame(rbind(comb, df1)) height=height+2 print (width) print (height) pdf("CCF_Heatmap_ggplot.pdf", width=height, height=width) ## Change size of the plot #label_color <- c("black","red","black","black","black","black","black","black","black","black","black","black","black","black","black","black","black","black","black","black","black","black","black","black","black","black","black","black","black","black") p <- ggplot(df3, aes(x=samples,y=genes,fill=ccf_groupB, group=loh)) + geom_tile(width=0.8,height=0.8) + geom_tile(data=df2,aes(samples, genes),size=1,fill=NA,width=0.8,height=0.8,color="gold3") + scale_fill_manual(values = cols, name="CCF",guide = FALSE); p + geom_segment( aes(x=xmin,xend=xmax,y=ymin,yend=ymax), subset(ggplot_build(p)$data[[1]],group==2), inherit.aes=F,color="white",size=1) + theme(axis.text.x=element_text(size=20, family = "sans", angle = 90, hjust=0, vjust=0)) + theme(axis.text.y=element_text(size=20, face="italic", family = "sans")) + scale_x_discrete(name="",position="top",drop=FALSE) + scale_y_discrete(name="",drop=FALSE) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), panel.border = element_blank()) + theme(legend.position="none") + theme(axis.ticks = element_blank()) + theme(axis.text=element_text(colour = "black")) dev.off()
R
{-# LANGUAGE NoMonomorphismRestriction #-} import Control.Monad import Control.Monad.Distribution.Rational -- or import Control.Monad.Distribution.Rational if you want exact answers import Data.List data Coin = Heads | Tails deriving (Eq, Ord, Show) toss = uniform [Heads, Tails] tosses n = sequence (replicate n toss) unorderedTosses n = liftM sort (tosses n) tossesWithAtLeastOneHead n = do result <- tosses n guard (Heads `elem` result) return result {- Using Control.Monad.Probability: *Main> ddist (unorderedTosses 2) [MV 0.25 [Heads,Heads],MV 0.5 [Heads,Tails],MV 0.25 [Tails,Tails]] Using Control.Monad.Probability.Rational: *Main> ddist (unorderedTosses 2) [MV 1%4 [Heads,Heads],MV 1%2 [Heads,Tails],MV 1%4 [Tails,Tails]] Using either: *Main> sampleIO (unorderedTosses 2) 10 [[Heads,Heads],[Heads,Heads],[Heads,Heads],[Tails,Tails],[Heads,Heads],[Heads,Heads],[Heads,Tails],[Heads,Tails],[Tails,Tails],[Heads,Tails]] -}
Haskell
import Web3 from 'web3' import $ from 'jquery' import { props } from 'eth-net-props' export const connectSelector = '[connect-wallet]' export const disconnectSelector = '[disconnect-wallet]' const connectToSelector = '[connect-to]' const connectedToSelector = '[connected-to]' export function getContractABI ($form) { const implementationAbi = $form.data('implementation-abi') const parentAbi = $form.data('contract-abi') const $parent = $('[data-smart-contract-functions]') const contractType = $parent.data('type') const contractAbi = contractType === 'proxy' ? implementationAbi : parentAbi return contractAbi } export function getMethodInputs (contractAbi, functionName) { const functionAbi = contractAbi.find(abi => abi.name === functionName ) return functionAbi && functionAbi.inputs } export function prepareMethodArgs ($functionInputs, inputs) { return $.map($functionInputs, (element, ind) => { const inputValue = $(element).val() const inputType = inputs[ind] && inputs[ind].type const inputComponents = inputs[ind] && inputs[ind].components let sanitizedInputValue sanitizedInputValue = replaceDoubleQuotes(inputValue, inputType, inputComponents) sanitizedInputValue = replaceSpaces(sanitizedInputValue, inputType, inputComponents) if (isArrayInputType(inputType) || isTupleInputType(inputType)) { if (sanitizedInputValue === '' || sanitizedInputValue === '[]') { return [[]] } else { if (isArrayOfTuple(inputType)) { const sanitizedInputValueElements = JSON.parse(sanitizedInputValue).map((elementValue, index) => { return sanitizeMutipleInputValues(elementValue, inputType, inputComponents) }) return [sanitizedInputValueElements] } else { if (sanitizedInputValue.startsWith('[') && sanitizedInputValue.endsWith(']')) { sanitizedInputValue = sanitizedInputValue.substring(1, sanitizedInputValue.length - 1) } const inputValueElements = sanitizedInputValue.split(',') const sanitizedInputValueElements = sanitizeMutipleInputValues(inputValueElements, inputType, inputComponents) return [sanitizedInputValueElements] } } } else { return convertToBool(sanitizedInputValue, inputType) } }) } function sanitizeMutipleInputValues (inputValueElements, inputType, inputComponents) { return inputValueElements.map((elementValue, index) => { let elementInputType if (inputType.includes('tuple')) { elementInputType = inputComponents[index].type } else { elementInputType = inputType.split('[')[0] } let sanitizedElementValue = replaceDoubleQuotes(elementValue, elementInputType) sanitizedElementValue = replaceSpaces(sanitizedElementValue, elementInputType) sanitizedElementValue = convertToBool(sanitizedElementValue, elementInputType) return sanitizedElementValue }) } export function compareChainIDs (explorerChainId, walletChainIdHex) { if (explorerChainId !== parseInt(walletChainIdHex)) { const networkDisplayNameFromWallet = props.getNetworkDisplayName(walletChainIdHex) const networkDisplayName = props.getNetworkDisplayName(explorerChainId) const errorMsg = `You connected to ${networkDisplayNameFromWallet} chain in the wallet, but the current instance of Blockscout is for ${networkDisplayName} chain` return Promise.reject(new Error(errorMsg)) } else { return Promise.resolve() } } export const formatError = (error) => { let { message } = error message = message && message.split('Error: ').length > 1 ? message.split('Error: ')[1] : message return message } export const formatTitleAndError = (error) => { let { message } = error let title = message && message.split('Error: ').length > 1 ? message.split('Error: ')[1] : message title = title && title.split('{').length > 1 ? title.split('{')[0].replace(':', '') : title let txHash = '' let errorMap = '' try { errorMap = message && message.indexOf('{') >= 0 ? JSON.parse(message && message.slice(message.indexOf('{'))) : '' message = errorMap.error || '' txHash = errorMap.transactionHash || '' } catch (exception) { message = '' } return { title, message, txHash } } export const getCurrentAccountPromise = (provider) => { return new Promise((resolve, reject) => { if (provider && provider.wc) { getCurrentAccountFromWCPromise(provider) .then(account => resolve(account)) .catch(err => { reject(err) }) } else { getCurrentAccountFromMMPromise() .then(account => resolve(account)) .catch(err => { reject(err) }) } }) } export const getCurrentAccountFromWCPromise = (provider) => { return new Promise((resolve, reject) => { // Get a Web3 instance for the wallet const web3 = new Web3(provider) // Get list of accounts of the connected wallet web3.eth.getAccounts() .then(accounts => { // MetaMask does not give you all accounts, only the selected account resolve(accounts[0]) }) .catch(err => { reject(err) }) }) } export const getCurrentAccountFromMMPromise = () => { return new Promise((resolve, reject) => { window.ethereum.request({ method: 'eth_accounts' }) .then(accounts => { const account = accounts[0] ? accounts[0].toLowerCase() : null resolve(account) }) .catch(err => { reject(err) }) }) } function hideConnectedToContainer () { document.querySelector(connectedToSelector) && document.querySelector(connectedToSelector).classList.add('hidden') } function showConnectedToContainer () { document.querySelector(connectedToSelector) && document.querySelector(connectedToSelector).classList.remove('hidden') } function hideConnectContainer () { document.querySelector(connectSelector) && document.querySelector(connectSelector).classList.add('hidden') } function showConnectContainer () { document.querySelector(connectSelector) && document.querySelector(connectSelector).classList.remove('hidden') } function hideConnectToContainer () { document.querySelector(connectToSelector) && document.querySelector(connectToSelector).classList.add('hidden') } function showConnectToContainer () { document.querySelector(connectToSelector) && document.querySelector(connectToSelector).classList.remove('hidden') } export function showHideDisconnectButton () { // Show disconnect button only in case of Wallet Connect if (window.web3 && window.web3.currentProvider && window.web3.currentProvider.wc) { document.querySelector(disconnectSelector) && document.querySelector(disconnectSelector).classList.remove('hidden') } else { document.querySelector(disconnectSelector) && document.querySelector(disconnectSelector).classList.add('hidden') } } export function showConnectedToElements (account) { hideConnectToContainer() showConnectContainer() showConnectedToContainer() showHideDisconnectButton() setConnectToAddress(account) } export function showConnectElements () { showConnectToContainer() showConnectContainer() hideConnectedToContainer() } export function hideConnectButton () { showConnectToContainer() hideConnectContainer() hideConnectedToContainer() } function setConnectToAddress (account) { if (document.querySelector('[connected-to-address]')) { document.querySelector('[connected-to-address]').innerHTML = `<a href='/address/${account}'>${trimmedAddressHash(account)}</a>` } } function trimmedAddressHash (account) { if ($(window).width() < 544) { return `${account.slice(0, 7)}–${account.slice(-6)}` } else { return account } } function convertToBool (value, type) { if (isBoolInputType(type)) { const boolVal = (value === 'true' || value === '1' || value === 1) return boolVal } else { return value } } function isArrayInputType (inputType) { return inputType && inputType.includes('[') && inputType.includes(']') } function isTupleInputType (inputType) { return inputType && inputType.includes('tuple') && !isArrayInputType(inputType) } function isArrayOfTuple (inputType) { return inputType && inputType.includes('tuple') && isArrayInputType(inputType) } function isAddressInputType (inputType) { return inputType && inputType.includes('address') && !isArrayInputType(inputType) } function isUintInputType (inputType) { return inputType && inputType.includes('int') && !isArrayInputType(inputType) } function isStringInputType (inputType) { return inputType && inputType.includes('string') && !isArrayInputType(inputType) } function isBytesInputType (inputType) { return inputType && inputType.includes('bytes') && !isArrayInputType(inputType) } function isBoolInputType (inputType) { return inputType && inputType.includes('bool') && !isArrayInputType(inputType) } function isNonSpaceInputType (inputType) { return isAddressInputType(inputType) || isBytesInputType(inputType) || inputType.includes('int') || inputType.includes('bool') } function replaceSpaces (value, type, components) { if (isNonSpaceInputType(type) && isFunction(value.replace)) { return value.replace(/\s/g, '') } else if (isTupleInputType(type) && isFunction(value.split)) { return value .split(',') .map((itemValue, itemIndex) => { const itemType = components && components[itemIndex] && components[itemIndex].type return replaceSpaces(itemValue, itemType) }) .join(',') } else { if (typeof value.trim === 'function') { return value.trim() } return value } } function replaceDoubleQuotes (value, type, components) { if (isAddressInputType(type) || isUintInputType(type) || isStringInputType(type) || isBytesInputType(type)) { if (isFunction(value.replaceAll)) { return value.replaceAll('"', '') } else if (isFunction(value.replace)) { return value.replace(/"/g, '') } return value } else if (isTupleInputType(type) && isFunction(value.split)) { return value .split(',') .map((itemValue, itemIndex) => { const itemType = components && components[itemIndex] && components[itemIndex].type return replaceDoubleQuotes(itemValue, itemType) }) .join(',') } else { return value } } function isFunction (param) { return typeof param === 'function' }
JavaScript
module Instruction_Fetch ( input clk, input reset, output wire [31:0] Instruction ); wire [63:0] PCOut; wire [63:0] sum; Adder add ( .a(PCOut), .b(64'd4), .out(sum) ); Program_Counter PC ( .clk(clk), .reset(reset), .PC_In(sum), .PC_Out(PCOut) ); Instruction_Memory Im ( .Inst_Address(PCOut), .Instruction(Instruction) ); endmodule
Coq
Public Class Main Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load If My.Computer.FileSystem.DirectoryExists(settingsFolder) = False Then My.Computer.FileSystem.CreateDirectory(settingsFolder) End If End Sub Private Sub Steam_Click(sender As Object, e As EventArgs) Handles Steam.Click Steam_Scanner.Show() End Sub Private Sub Emulators_Click(sender As Object, e As EventArgs) Handles Emulators.Click Emulation.Show() End Sub Private Sub Blizzard_Click(sender As Object, e As EventArgs) Handles Blizzard.Click Dim BattlenetPath As String = BlizzardFinder() If BattlenetPath IsNot Nothing Then Process.Start(BattlenetPath) End If End Sub End Class
VBA
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.6"/> <title>NICAS: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">NICAS </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.6 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li class="current"><a href="annotated.html"><span>Data&#160;Types&#160;List</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Data&#160;Types&#160;List</span></a></li> <li><a href="classes.html"><span>Data&#160;Types</span></a></li> <li><a href="functions.html"><span>Data&#160;Fields</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&#160;</span>Pages</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="classtype__timer.html">type_timer</a></li><li class="navelem"><a class="el" href="structtype__timer_1_1timertype.html">timertype</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">type_timer::timertype Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="structtype__timer_1_1timertype.html">type_timer::timertype</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html#ad23d7481744e8e04944197613fd3a200">count_max</a></td><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html">type_timer::timertype</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html#aab4de3c3662b4a2a69063c7d15912718">count_rate</a></td><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html">type_timer::timertype</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html#a286f371506fe0c1b44ce63cf32968852">cpu</a></td><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html">type_timer::timertype</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html#a2d03f7aafa181f5ff7d005649b79a034">cpu_time_end</a></td><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html">type_timer::timertype</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html#aed3cc46e04178466a94ad0b1600bd17a">cpu_time_start</a></td><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html">type_timer::timertype</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html#a64cf0a8b27aad1aeb443aa3ed8c539d2">elapsed</a></td><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html">type_timer::timertype</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html#a70509ea1b406e0569c01424ffc7fec88">rchar</a></td><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html">type_timer::timertype</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html#a106587042476e68688fa723636ace9d3">system_clock_end</a></td><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html">type_timer::timertype</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html#abf2d11c050658c7f363f65e1612aaeee">system_clock_start</a></td><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html">type_timer::timertype</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html#add39b9f0d7fb71785fee4fbb2794edfc">vmhwm</a></td><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html">type_timer::timertype</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html#ab15766af9a11fdfa4e5359dd3add0eb8">vmpeak</a></td><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html">type_timer::timertype</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html#a9f1e50f2c2d805678eeb6adfc37f6f8a">wchar</a></td><td class="entry"><a class="el" href="structtype__timer_1_1timertype.html">type_timer::timertype</a></td><td class="entry"></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Mon Jul 31 2017 15:14:39 for NICAS by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.6 </small></address> </body> </html>
HTML
using UnityEngine; using System.Collections; using UnityEngine.UI; [RequireComponent (typeof (CircleCollider2D))] public class Shop : InRangeActive { public Text priceText; public Text itemText; public bool canHaveComponents = false; public bool canHaveHealth = true; public bool canHaveCharges = true; public float componentPrice; public float fullHealPrice; public float fullChargePrice; delegate void GiveItem(); GiveItem giveItem; float price; bool roomSet = false; public AudioSource notEnoughGold; public AudioSource purchase; void Update() { if(transform.hasChanged && transform.parent != null && !roomSet) { roomSet = true; transform.parent.gameObject.GetComponent<Room>().RoomEntered += PickItem; } if (playerInside && Input.GetKeyDown(KeyCode.E)) { CoinHolder holder = player.gameObject.GetComponent<CoinHolder>(); if(holder.GetCoinCount() >= price) { holder.RemoveCoin((int)price); purchase.Play(); giveItem(); gameObject.SetActive(false); } else { notEnoughGold.Play(); } } } void Start () { } void OnTriggerStay2D(Collider2D other) { if (other.gameObject.tag == "Player") { CoinHolder holder = player.gameObject.GetComponent<CoinHolder>(); outLineColor = holder.GetCoinCount() >= price ? new Color(0, 1, 0) : new Color(1, 0, 0); SetOutline(other); } } void PickItem(Room r) { if( canHaveComponents || canHaveHealth || canHaveCharges) { bool haveItem = false; while(!haveItem) { int itemType = Random.Range (0,3); switch(itemType) { case 0: if (!canHaveComponents) { continue; } price = componentPrice; giveItem = GiveSpellComponent; spellComponent = PlayerInventory.instance.AddComponentToStore(); ISpellComponent component = ComponentLoader.GetInstance().LoadComponent(new ComponentLoader.UnLoadedSpellComponent(spellComponent, PlayerInventory.instance.componentsInStore[spellComponent])); itemText.text = component.GetTitle() + "\n" + component.GetToolTip(); haveItem = true; break; case 1: if (!canHaveHealth) { continue; } price = fullHealPrice; giveItem = Heal; itemText.text = "Full Healh"; haveItem = true; break; case 2: if (!canHaveCharges) { continue; } price = fullChargePrice; giveItem = RechargeSpells; itemText.text = "Recharge Spells"; haveItem = true; break; default: break; } } priceText.text = price.ToString(); } } string spellComponent; void GiveSpellComponent() { PlayerInventory.instance.AddComponent (spellComponent, true); } void RechargeSpells() { Shoot playerShoot = player.gameObject.transform.GetChild(1).GetChild(0).GetComponent<Shoot>(); playerShoot.RechargeSpells(); return; } void Heal() { player.GetComponent<Health> ().Heal (1000); } }
C#
module Definitions = struct open Common [%%template [@@@mode.default m = (global, local)] (** Type of reader functions for the binary protocol. They take a buffer and a reference to a read position, and return the unmarshalled value. The next buffer position after reading in the value will be stored in the position reference. *) type 'a reader = buf -> pos_ref:pos_ref -> 'a type ('a, 'b) reader1 = ('a reader[@mode m]) -> ('b reader[@mode m]) type ('a, 'b, 'c) reader2 = ('a reader[@mode m]) -> (('b, 'c) reader1[@mode m]) type ('a, 'b, 'c, 'd) reader3 = ('a reader[@mode m]) -> (('b, 'c, 'd) reader2[@mode m])] (** Type of reader functions for polymorphic variant readers, after reading their tag. Used for definitions such as [__bin_read_t__]. The [int] argument is a numerical representation of the variant tag, such as [`a]. *) type 'a vtag_reader = buf -> pos_ref:pos_ref -> int -> 'a type ('a, 'b) vtag_reader1 = 'a reader -> 'b vtag_reader type ('a, 'b, 'c) vtag_reader2 = 'a reader -> ('b, 'c) vtag_reader1 type ('a, 'b, 'c, 'd) vtag_reader3 = 'a reader -> ('b, 'c, 'd) vtag_reader2 end module type Read = sig (** Reading values from the binary protocol using (mostly) OCaml. *) open Common include module type of struct include Definitions end [%%template: [@@@mode m = (global, local)] type 'a global_reader := ('a reader[@mode global]) type 'a reader := ('a reader[@mode m]) type ('a, 'b) reader1 := (('a, 'b) reader1[@mode m]) type ('a, 'b, 'c) reader2 := (('a, 'b, 'c) reader2[@mode m]) type ('a, 'b, 'c, 'd) reader3 := (('a, 'b, 'c, 'd) reader3[@mode m]) [@@@mode.default m] val bin_read_unit : unit reader [@@zero_alloc arity 2] val bin_read_bool : bool reader [@@zero_alloc arity 2] val bin_read_string : string reader [@@zero_alloc_if_local m opt arity 2] val bin_read_bytes : bytes reader [@@zero_alloc_if_local m opt arity 2] val bin_read_char : char reader [@@zero_alloc arity 2] val bin_read_int : int reader [@@zero_alloc arity 2] val bin_read_nat0 : Nat0.t reader [@@zero_alloc opt arity 2] val bin_read_float : float reader [@@zero_alloc_if_local m arity 2] val bin_read_int32 : int32 reader [@@zero_alloc_if_local m arity 2] val bin_read_int64 : int64 reader [@@zero_alloc_if_local m arity 2] val bin_read_nativeint : nativeint reader [@@zero_alloc_if_local m opt arity 2] (* Note: since the contents of a [ref] must always be global, this takes a global reader rather than a local one *) val bin_read_ref : 'a global_reader -> 'a ref reader val bin_read_option : ('a, 'a option) reader1 val bin_read_pair : ('a, 'b, 'a * 'b) reader2 val bin_read_triple : ('a, 'b, 'c, 'a * 'b * 'c) reader3 val bin_read_list : ('a, 'a list) reader1 (* Note: since the contents of an [array] must always be global, this takes a global reader rather than a local one *) val bin_read_array : 'a global_reader -> 'a array reader val bin_read_float32_vec : vec32 reader val bin_read_float64_vec : vec64 reader val bin_read_vec : vec reader val bin_read_float32_mat : mat32 reader val bin_read_float64_mat : mat64 reader val bin_read_mat : mat reader val bin_read_bigstring : buf reader val bin_read_variant_int : int reader [@@zero_alloc arity 2] val bin_read_int_8bit : int reader [@@zero_alloc arity 2] val bin_read_int_16bit : int reader [@@zero_alloc arity 2] val bin_read_int_32bit : int reader [@@zero_alloc arity 2] val bin_read_int_64bit : int reader [@@zero_alloc arity 2] val bin_read_int32_bits : int32 reader [@@zero_alloc_if_local m arity 2] val bin_read_int64_bits : int64 reader [@@zero_alloc_if_local m arity 2] val bin_read_network16_int : int reader [@@zero_alloc arity 2] val bin_read_network32_int : int reader [@@zero_alloc arity 2] val bin_read_network32_int32 : int32 reader [@@zero_alloc_if_local m arity 2] val bin_read_network64_int : int reader [@@zero_alloc arity 2] val bin_read_network64_int64 : int64 reader [@@zero_alloc_if_local m arity 2] val bin_read_md5 : Md5_lib.t reader [@@zero_alloc_if_local m opt arity 2] (** Fail early if the list is larger than [max_len]. *) val bin_read_list_with_max_len : max_len:int -> ('a, 'a list) reader1] val bin_read_lazy : ('a, 'a lazy_t) reader1 val bin_read_bigarray1 : kind:('a, 'k) Stdlib.Bigarray.kind -> layout:'layout Stdlib.Bigarray.layout -> ('a, 'k, 'layout) Stdlib.Bigarray.Array1.t reader val bin_read_bigarray2 : kind:('a, 'k) Stdlib.Bigarray.kind -> layout:'layout Stdlib.Bigarray.layout -> ('a, 'k, 'layout) Stdlib.Bigarray.Array2.t reader val bin_read_floatarray : floatarray reader end
OCaml
@echo off rem rem Licensed to the Apache Software Foundation (ASF) under one or more rem contributor license agreements. See the NOTICE file distributed with rem this work for additional information regarding copyright ownership. rem The ASF licenses this file to You under the Apache License, Version 2.0 rem (the "License"); you may not use this file except in compliance with rem the License. You may obtain a copy of the License at rem rem http://www.apache.org/licenses/LICENSE-2.0 rem rem Unless required by applicable law or agreed to in writing, software rem distributed under the License is distributed on an "AS IS" BASIS, rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. rem See the License for the specific language governing permissions and rem limitations under the License. rem rem This is the entry point for running a Spark class. To avoid polluting rem the environment, it just launches a new cmd to do the real work. cmd /V /E /C %~dp0spark-class2.cmd %*
Batchfile
\subsection{Operation Model for maxHandlingDelayPassed} \label{OM-maxHandlingDelayPassed} The \msrcode{maxHandlingDelayPassed} operation has the following properties: \begin{operationmodel} \addheading{Operation} \adddoublerow{maxHandlingDelayPassed}{used to determine if the crisis stood too longly in a pending status since its creation.} \addrowheading{Return type} \addsinglerow{ptBoolean} \addrowheading{Post-Condition (functional)} \addnumberedsinglerow{PostF}{ true iff the crisis is in pending status and if the duration between the current ctState clock information and the crisis instant is greater than the maximum reminder period duration.} \end{operationmodel} % ------------------------------------------ % MCL Listing % ------------------------------------------ \vspace{1cm} The listing~\ref{OM-ctCrisis-maxHandlingDelayPassed-MCL-LST} provides the \msrmessir (MCL-oriented) specification of the operation. \scriptsize \vspace{0.5cm} \begin{lstlisting}[style=MessirStyle,firstnumber=auto,captionpos=b,caption={\msrmessir (MCL-oriented) specification of the operation \emph{maxHandlingDelayPassed}.},label=OM-ctCrisis-maxHandlingDelayPassed-MCL-LST] /* Post Functional:*/ postF{let TheSystem:ctState in let CurrentClockSecondsQty:dtInteger in let CrisisInstantSecondsQty:dtInteger in let MaxCrisisReminderPeriod:dtSecond in if ( /* Post F01 */ self.rnSystem = TheSystem and self.status = pending and TheSystem.clock.toSecondsQty() = CurrentClockSecondsQty and Self.instant.toSecondsQty() = CrisisInstantSecondsQty and TheSystem.maxCrisisReminderPeriod = MaxCrisisReminderPeriod and CurrentClockSecondsQty.sub(CrisisInstantSecondsQty) .gt(MaxCrisisReminderPeriod) ) then (result = true) else (result = false) endif} \end{lstlisting} \normalsize % ------------------------------------------ % PROLOG Listing % ------------------------------------------ \vspace{1cm} The listing~\ref{OM-ctCrisis-maxHandlingDelayPassed-PROLOG-LST} provides the \msrmessir (Prolog-oriented) implementation of the operation. \scriptsize \vspace{0.5cm} \lstinputlisting[style=MessirPrologStyle,firstnumber=auto,captionpos=b,caption={\msrmessir (Prolog-oriented) implementation of the operation \emph{maxHandlingDelayPassed}.},label=OM-ctCrisis-maxHandlingDelayPassed-PROLOG-LST]{../lu.uni.lassy.excalibur.examples.icrash.simulation/src/Operations/Concepts/PrimaryTypesClasses/PrimaryTypesClasses-ctCrisis-maxHandlingDelayPassed.pl} \normalsize
TeX
# This file is auto-generated by the Perl DateTime Suite time zone # code generator (0.07) This code generator comes with the # DateTime::TimeZone module distribution in the tools/ directory # # Generated from /tmp/6Pwc8w6J1M/asia. Olson data version 2013d # # Do not edit this file directly. # package DateTime::TimeZone::Asia::Aqtobe; { $DateTime::TimeZone::Asia::Aqtobe::VERSION = '1.60'; } BEGIN { $DateTime::TimeZone::Asia::Aqtobe::AUTHORITY = 'cpan:DROLSKY'; } use strict; use Class::Singleton 1.03; use DateTime::TimeZone; use DateTime::TimeZone::OlsonDB; @DateTime::TimeZone::Asia::Aqtobe::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' ); my $spans = [ [ DateTime::TimeZone::NEG_INFINITY, # utc_start 60694517480, # utc_end 1924-05-01 20:11:20 (Thu) DateTime::TimeZone::NEG_INFINITY, # local_start 60694531200, # local_end 1924-05-02 00:00:00 (Fri) 13720, 0, 'LMT', ], [ 60694517480, # utc_start 1924-05-01 20:11:20 (Thu) 60888139200, # utc_end 1930-06-20 20:00:00 (Fri) 60694531880, # local_start 1924-05-02 00:11:20 (Fri) 60888153600, # local_end 1930-06-21 00:00:00 (Sat) 14400, 0, 'AKTT', ], [ 60888139200, # utc_start 1930-06-20 20:00:00 (Fri) 62490596400, # utc_end 1981-03-31 19:00:00 (Tue) 60888157200, # local_start 1930-06-21 01:00:00 (Sat) 62490614400, # local_end 1981-04-01 00:00:00 (Wed) 18000, 0, 'AKTT', ], [ 62490596400, # utc_start 1981-03-31 19:00:00 (Tue) 62506404000, # utc_end 1981-09-30 18:00:00 (Wed) 62490618000, # local_start 1981-04-01 01:00:00 (Wed) 62506425600, # local_end 1981-10-01 00:00:00 (Thu) 21600, 1, 'AKTST', ], [ 62506404000, # utc_start 1981-09-30 18:00:00 (Wed) 62522128800, # utc_end 1982-03-31 18:00:00 (Wed) 62506425600, # local_start 1981-10-01 00:00:00 (Thu) 62522150400, # local_end 1982-04-01 00:00:00 (Thu) 21600, 0, 'AKTT', ], [ 62522128800, # utc_start 1982-03-31 18:00:00 (Wed) 62537940000, # utc_end 1982-09-30 18:00:00 (Thu) 62522150400, # local_start 1982-04-01 00:00:00 (Thu) 62537961600, # local_end 1982-10-01 00:00:00 (Fri) 21600, 1, 'AKTST', ], [ 62537940000, # utc_start 1982-09-30 18:00:00 (Thu) 62553668400, # utc_end 1983-03-31 19:00:00 (Thu) 62537958000, # local_start 1982-09-30 23:00:00 (Thu) 62553686400, # local_end 1983-04-01 00:00:00 (Fri) 18000, 0, 'AKTT', ], [ 62553668400, # utc_start 1983-03-31 19:00:00 (Thu) 62569476000, # utc_end 1983-09-30 18:00:00 (Fri) 62553690000, # local_start 1983-04-01 01:00:00 (Fri) 62569497600, # local_end 1983-10-01 00:00:00 (Sat) 21600, 1, 'AKTST', ], [ 62569476000, # utc_start 1983-09-30 18:00:00 (Fri) 62585290800, # utc_end 1984-03-31 19:00:00 (Sat) 62569494000, # local_start 1983-09-30 23:00:00 (Fri) 62585308800, # local_end 1984-04-01 00:00:00 (Sun) 18000, 0, 'AKTT', ], [ 62585290800, # utc_start 1984-03-31 19:00:00 (Sat) 62601022800, # utc_end 1984-09-29 21:00:00 (Sat) 62585312400, # local_start 1984-04-01 01:00:00 (Sun) 62601044400, # local_end 1984-09-30 03:00:00 (Sun) 21600, 1, 'AKTST', ], [ 62601022800, # utc_start 1984-09-29 21:00:00 (Sat) 62616747600, # utc_end 1985-03-30 21:00:00 (Sat) 62601040800, # local_start 1984-09-30 02:00:00 (Sun) 62616765600, # local_end 1985-03-31 02:00:00 (Sun) 18000, 0, 'AKTT', ], [ 62616747600, # utc_start 1985-03-30 21:00:00 (Sat) 62632472400, # utc_end 1985-09-28 21:00:00 (Sat) 62616769200, # local_start 1985-03-31 03:00:00 (Sun) 62632494000, # local_end 1985-09-29 03:00:00 (Sun) 21600, 1, 'AKTST', ], [ 62632472400, # utc_start 1985-09-28 21:00:00 (Sat) 62648197200, # utc_end 1986-03-29 21:00:00 (Sat) 62632490400, # local_start 1985-09-29 02:00:00 (Sun) 62648215200, # local_end 1986-03-30 02:00:00 (Sun) 18000, 0, 'AKTT', ], [ 62648197200, # utc_start 1986-03-29 21:00:00 (Sat) 62663922000, # utc_end 1986-09-27 21:00:00 (Sat) 62648218800, # local_start 1986-03-30 03:00:00 (Sun) 62663943600, # local_end 1986-09-28 03:00:00 (Sun) 21600, 1, 'AKTST', ], [ 62663922000, # utc_start 1986-09-27 21:00:00 (Sat) 62679646800, # utc_end 1987-03-28 21:00:00 (Sat) 62663940000, # local_start 1986-09-28 02:00:00 (Sun) 62679664800, # local_end 1987-03-29 02:00:00 (Sun) 18000, 0, 'AKTT', ], [ 62679646800, # utc_start 1987-03-28 21:00:00 (Sat) 62695371600, # utc_end 1987-09-26 21:00:00 (Sat) 62679668400, # local_start 1987-03-29 03:00:00 (Sun) 62695393200, # local_end 1987-09-27 03:00:00 (Sun) 21600, 1, 'AKTST', ], [ 62695371600, # utc_start 1987-09-26 21:00:00 (Sat) 62711096400, # utc_end 1988-03-26 21:00:00 (Sat) 62695389600, # local_start 1987-09-27 02:00:00 (Sun) 62711114400, # local_end 1988-03-27 02:00:00 (Sun) 18000, 0, 'AKTT', ], [ 62711096400, # utc_start 1988-03-26 21:00:00 (Sat) 62726821200, # utc_end 1988-09-24 21:00:00 (Sat) 62711118000, # local_start 1988-03-27 03:00:00 (Sun) 62726842800, # local_end 1988-09-25 03:00:00 (Sun) 21600, 1, 'AKTST', ], [ 62726821200, # utc_start 1988-09-24 21:00:00 (Sat) 62742546000, # utc_end 1989-03-25 21:00:00 (Sat) 62726839200, # local_start 1988-09-25 02:00:00 (Sun) 62742564000, # local_end 1989-03-26 02:00:00 (Sun) 18000, 0, 'AKTT', ], [ 62742546000, # utc_start 1989-03-25 21:00:00 (Sat) 62758270800, # utc_end 1989-09-23 21:00:00 (Sat) 62742567600, # local_start 1989-03-26 03:00:00 (Sun) 62758292400, # local_end 1989-09-24 03:00:00 (Sun) 21600, 1, 'AKTST', ], [ 62758270800, # utc_start 1989-09-23 21:00:00 (Sat) 62773995600, # utc_end 1990-03-24 21:00:00 (Sat) 62758288800, # local_start 1989-09-24 02:00:00 (Sun) 62774013600, # local_end 1990-03-25 02:00:00 (Sun) 18000, 0, 'AKTT', ], [ 62773995600, # utc_start 1990-03-24 21:00:00 (Sat) 62790325200, # utc_end 1990-09-29 21:00:00 (Sat) 62774017200, # local_start 1990-03-25 03:00:00 (Sun) 62790346800, # local_end 1990-09-30 03:00:00 (Sun) 21600, 1, 'AKTST', ], [ 62790325200, # utc_start 1990-09-29 21:00:00 (Sat) 62798353200, # utc_end 1990-12-31 19:00:00 (Mon) 62790343200, # local_start 1990-09-30 02:00:00 (Sun) 62798371200, # local_end 1991-01-01 00:00:00 (Tue) 18000, 0, 'AKTT', ], [ 62798353200, # utc_start 1990-12-31 19:00:00 (Mon) 62828506800, # utc_end 1991-12-15 19:00:00 (Sun) 62798371200, # local_start 1991-01-01 00:00:00 (Tue) 62828524800, # local_end 1991-12-16 00:00:00 (Mon) 18000, 0, 'AKTT', ], [ 62828506800, # utc_start 1991-12-15 19:00:00 (Sun) 62837488800, # utc_end 1992-03-28 18:00:00 (Sat) 62828524800, # local_start 1991-12-16 00:00:00 (Mon) 62837506800, # local_end 1992-03-28 23:00:00 (Sat) 18000, 0, 'AQTT', ], [ 62837488800, # utc_start 1992-03-28 18:00:00 (Sat) 62853210000, # utc_end 1992-09-26 17:00:00 (Sat) 62837510400, # local_start 1992-03-29 00:00:00 (Sun) 62853231600, # local_end 1992-09-26 23:00:00 (Sat) 21600, 1, 'AQTST', ], [ 62853210000, # utc_start 1992-09-26 17:00:00 (Sat) 62868949200, # utc_end 1993-03-27 21:00:00 (Sat) 62853228000, # local_start 1992-09-26 22:00:00 (Sat) 62868967200, # local_end 1993-03-28 02:00:00 (Sun) 18000, 0, 'AQTT', ], [ 62868949200, # utc_start 1993-03-27 21:00:00 (Sat) 62884674000, # utc_end 1993-09-25 21:00:00 (Sat) 62868970800, # local_start 1993-03-28 03:00:00 (Sun) 62884695600, # local_end 1993-09-26 03:00:00 (Sun) 21600, 1, 'AQTST', ], [ 62884674000, # utc_start 1993-09-25 21:00:00 (Sat) 62900398800, # utc_end 1994-03-26 21:00:00 (Sat) 62884692000, # local_start 1993-09-26 02:00:00 (Sun) 62900416800, # local_end 1994-03-27 02:00:00 (Sun) 18000, 0, 'AQTT', ], [ 62900398800, # utc_start 1994-03-26 21:00:00 (Sat) 62916123600, # utc_end 1994-09-24 21:00:00 (Sat) 62900420400, # local_start 1994-03-27 03:00:00 (Sun) 62916145200, # local_end 1994-09-25 03:00:00 (Sun) 21600, 1, 'AQTST', ], [ 62916123600, # utc_start 1994-09-24 21:00:00 (Sat) 62931848400, # utc_end 1995-03-25 21:00:00 (Sat) 62916141600, # local_start 1994-09-25 02:00:00 (Sun) 62931866400, # local_end 1995-03-26 02:00:00 (Sun) 18000, 0, 'AQTT', ], [ 62931848400, # utc_start 1995-03-25 21:00:00 (Sat) 62947573200, # utc_end 1995-09-23 21:00:00 (Sat) 62931870000, # local_start 1995-03-26 03:00:00 (Sun) 62947594800, # local_end 1995-09-24 03:00:00 (Sun) 21600, 1, 'AQTST', ], [ 62947573200, # utc_start 1995-09-23 21:00:00 (Sat) 62963902800, # utc_end 1996-03-30 21:00:00 (Sat) 62947591200, # local_start 1995-09-24 02:00:00 (Sun) 62963920800, # local_end 1996-03-31 02:00:00 (Sun) 18000, 0, 'AQTT', ], [ 62963902800, # utc_start 1996-03-30 21:00:00 (Sat) 62982046800, # utc_end 1996-10-26 21:00:00 (Sat) 62963924400, # local_start 1996-03-31 03:00:00 (Sun) 62982068400, # local_end 1996-10-27 03:00:00 (Sun) 21600, 1, 'AQTST', ], [ 62982046800, # utc_start 1996-10-26 21:00:00 (Sat) 62995352400, # utc_end 1997-03-29 21:00:00 (Sat) 62982064800, # local_start 1996-10-27 02:00:00 (Sun) 62995370400, # local_end 1997-03-30 02:00:00 (Sun) 18000, 0, 'AQTT', ], [ 62995352400, # utc_start 1997-03-29 21:00:00 (Sat) 63013496400, # utc_end 1997-10-25 21:00:00 (Sat) 62995374000, # local_start 1997-03-30 03:00:00 (Sun) 63013518000, # local_end 1997-10-26 03:00:00 (Sun) 21600, 1, 'AQTST', ], [ 63013496400, # utc_start 1997-10-25 21:00:00 (Sat) 63026802000, # utc_end 1998-03-28 21:00:00 (Sat) 63013514400, # local_start 1997-10-26 02:00:00 (Sun) 63026820000, # local_end 1998-03-29 02:00:00 (Sun) 18000, 0, 'AQTT', ], [ 63026802000, # utc_start 1998-03-28 21:00:00 (Sat) 63044946000, # utc_end 1998-10-24 21:00:00 (Sat) 63026823600, # local_start 1998-03-29 03:00:00 (Sun) 63044967600, # local_end 1998-10-25 03:00:00 (Sun) 21600, 1, 'AQTST', ], [ 63044946000, # utc_start 1998-10-24 21:00:00 (Sat) 63058251600, # utc_end 1999-03-27 21:00:00 (Sat) 63044964000, # local_start 1998-10-25 02:00:00 (Sun) 63058269600, # local_end 1999-03-28 02:00:00 (Sun) 18000, 0, 'AQTT', ], [ 63058251600, # utc_start 1999-03-27 21:00:00 (Sat) 63077000400, # utc_end 1999-10-30 21:00:00 (Sat) 63058273200, # local_start 1999-03-28 03:00:00 (Sun) 63077022000, # local_end 1999-10-31 03:00:00 (Sun) 21600, 1, 'AQTST', ], [ 63077000400, # utc_start 1999-10-30 21:00:00 (Sat) 63089701200, # utc_end 2000-03-25 21:00:00 (Sat) 63077018400, # local_start 1999-10-31 02:00:00 (Sun) 63089719200, # local_end 2000-03-26 02:00:00 (Sun) 18000, 0, 'AQTT', ], [ 63089701200, # utc_start 2000-03-25 21:00:00 (Sat) 63108450000, # utc_end 2000-10-28 21:00:00 (Sat) 63089722800, # local_start 2000-03-26 03:00:00 (Sun) 63108471600, # local_end 2000-10-29 03:00:00 (Sun) 21600, 1, 'AQTST', ], [ 63108450000, # utc_start 2000-10-28 21:00:00 (Sat) 63121150800, # utc_end 2001-03-24 21:00:00 (Sat) 63108468000, # local_start 2000-10-29 02:00:00 (Sun) 63121168800, # local_end 2001-03-25 02:00:00 (Sun) 18000, 0, 'AQTT', ], [ 63121150800, # utc_start 2001-03-24 21:00:00 (Sat) 63139899600, # utc_end 2001-10-27 21:00:00 (Sat) 63121172400, # local_start 2001-03-25 03:00:00 (Sun) 63139921200, # local_end 2001-10-28 03:00:00 (Sun) 21600, 1, 'AQTST', ], [ 63139899600, # utc_start 2001-10-27 21:00:00 (Sat) 63153205200, # utc_end 2002-03-30 21:00:00 (Sat) 63139917600, # local_start 2001-10-28 02:00:00 (Sun) 63153223200, # local_end 2002-03-31 02:00:00 (Sun) 18000, 0, 'AQTT', ], [ 63153205200, # utc_start 2002-03-30 21:00:00 (Sat) 63171349200, # utc_end 2002-10-26 21:00:00 (Sat) 63153226800, # local_start 2002-03-31 03:00:00 (Sun) 63171370800, # local_end 2002-10-27 03:00:00 (Sun) 21600, 1, 'AQTST', ], [ 63171349200, # utc_start 2002-10-26 21:00:00 (Sat) 63184654800, # utc_end 2003-03-29 21:00:00 (Sat) 63171367200, # local_start 2002-10-27 02:00:00 (Sun) 63184672800, # local_end 2003-03-30 02:00:00 (Sun) 18000, 0, 'AQTT', ], [ 63184654800, # utc_start 2003-03-29 21:00:00 (Sat) 63202798800, # utc_end 2003-10-25 21:00:00 (Sat) 63184676400, # local_start 2003-03-30 03:00:00 (Sun) 63202820400, # local_end 2003-10-26 03:00:00 (Sun) 21600, 1, 'AQTST', ], [ 63202798800, # utc_start 2003-10-25 21:00:00 (Sat) 63216104400, # utc_end 2004-03-27 21:00:00 (Sat) 63202816800, # local_start 2003-10-26 02:00:00 (Sun) 63216122400, # local_end 2004-03-28 02:00:00 (Sun) 18000, 0, 'AQTT', ], [ 63216104400, # utc_start 2004-03-27 21:00:00 (Sat) 63234853200, # utc_end 2004-10-30 21:00:00 (Sat) 63216126000, # local_start 2004-03-28 03:00:00 (Sun) 63234874800, # local_end 2004-10-31 03:00:00 (Sun) 21600, 1, 'AQTST', ], [ 63234853200, # utc_start 2004-10-30 21:00:00 (Sat) 63246510000, # utc_end 2005-03-14 19:00:00 (Mon) 63234871200, # local_start 2004-10-31 02:00:00 (Sun) 63246528000, # local_end 2005-03-15 00:00:00 (Tue) 18000, 0, 'AQTT', ], [ 63246510000, # utc_start 2005-03-14 19:00:00 (Mon) DateTime::TimeZone::INFINITY, # utc_end 63246528000, # local_start 2005-03-15 00:00:00 (Tue) DateTime::TimeZone::INFINITY, # local_end 18000, 0, 'AQTT', ], ]; sub olson_version { '2013d' } sub has_dst_changes { 23 } sub _max_year { 2023 } sub _new_instance { return shift->_init( @_, spans => $spans ); } 1;
Perl
# DEBUGGING # module.exports.log = log = -> console.log.apply this, arguments if DEBUG module.exports.DEBUG = DEBUG = true # LANGUAGE FUNCTIONS # module.exports.REGEX = REGEX = /[a-zA-Z_][a-zA-Z0-9_]*|'(?:\\.|[^'])*'?|"(?:\\.|[^"])*"?|-?[0-9]+|#[^\n\r]*|./gm #' module.exports.parse = parse = (code) -> code.match REGEX module.exports.typeOf = typeOf = (x) -> switch Object.prototype.toString.call x when '[object Number]' then 'int' when '[object String]' then 'string' when '[object Function]' then 'block' when '[object Array]' then 'array' else throw "Unknown type for #{x}" module.exports.toString = toString = (x) -> switch typeOf x when 'int' then x.toString() when 'string' then '"' + x.toString() + '"' when 'block' then '{' + x.code + '}' when 'array' then '[' + (toString e for e in x).join(' ') + ']' else throw "Unknown string representation for #{x}" module.exports.coerce = coerce = (a, b) -> switch typeOf a when 'block' then return [a, makeBlock b] when 'string' then return [a, '' + b] if typeOf(b) != 'block' when 'array' then switch typeOf b when 'array' then return [a, b] when 'int' then return [a, [b]] when 'int' then return [a, b] if typeOf(b) == 'int' coerce(b, a).reverse() module.exports.makeBlock = makeBlock = (code) -> parsed = parse switch typeOf code when 'int' then code.toString() when 'string' then code when 'array' then code when 'block' then code.code else throw "Cannot parse #{code}" # Return the block block = (stack, variables) -> state = variables: variables stack: stack lb: [] log 'PARSED:', parsed[..] while parsed[0]? token = parsed.shift() log 'TOKEN:', token # Tokens built in syntax if token == '{' end = parsed.indexOf '}' stack.push makeBlock(parsed[0...end]) parsed = parsed[end+1..] else if token == ':' name = parsed.shift() state.variables[name] = state.stack[state.stack.length - 1] else # Not built in syntax val = variables[token] log 'VAL:', val # Is it a variable if val? log 'FOUND' # Execute if it's a block if typeOf(val) == 'block' val.apply state else stack.push val else # Not a variable log 'NOT_FOUND' b = eval token stack.push b if b? log 'STACK:', stack log 'END STACK:', stack console.log stack.join('') if stack? block.code = parsed.join '' block
CoffeeScript
<Access id="recording" saveInterval="0.0010ms" separateFiles="true" recordClamps="true"> <CurrentClamp at="Seg0_soma_0" lineColor="red"> <CurrentPulse start="20.0ms" duration="60.0ms" to="0.0038nA"/> </CurrentClamp> <VoltageRecorder at="Seg0_soma_0" lineColor="0x000000" label="CG_CML_0.dat"/> </Access>
XML
@namespace p url(http://www.evolus.vn/Namespace/Pencil); .Stencil { /*text-align: center;*/ height: 170px; width: 550px; padding: 0; margin: 0; } .Stencil .StencilList { padding: 0px; margin: 0; height: 170px; width: 550px; overflow: auto; text-align: center; } .Stencil .StencilList > div { border: none; background: transparent; text-align: center; display: inline-block; width: 100px; cursor: pointer; } .Stencil .StencilList > div.Selected img, .Stencil .StencilList > div.Image img { max-width: 50px; max-height: 50px; } .Stencil .StencilList > div.Selected svg, .Stencil .StencilList > div.Selected img { -moz-border-radius: 2px; -moz-box-shadow: 0 0 3px #999; } .Stencil .StencilList > div.Image svg, .Stencil .StencilList > div.Image img { opacity: 0.9; border: none; } .Stencil .StencilList > div.Image svg:hover, .Stencil .StencilList > div.Image img:hover { opacity: 1; } .Stencil .StencilList > div.Text { /*overflow: hidden; vertical-align: middle;*/ } .Stencil .StencilList > div.Text label { cursor: pointer; } .Stencil .StencilList > div input[type='checkbox'] { vertical-align: middle; } vbox > hbox.StencilInformation { /*padding-top: 10px;*/ } vbox listbox { font: -moz-list; }
CSS
--[[ $%BEGINLICENSE%$ Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. 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; version 2 of the License. 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] --- -- a flexible statement based load balancer with connection pooling -- -- * build a connection pool of min_idle_connections for each backend and -- maintain its size -- * reusing a server-side connection when it is idling -- --- config -- -- connection pool local min_idle_connections = 4 local max_idle_connections = 8 -- debug local is_debug = false --- end of config --- -- read/write splitting sends all non-transactional SELECTs to the slaves -- -- is_in_transaction tracks the state of the transactions local is_in_transaction = 0 --- -- get a connection to a backend -- -- as long as we don't have enough connections in the pool, create new connections -- function connect_server() -- make sure that we connect to each backend at least ones to -- keep the connections to the servers alive -- -- on read_query we can switch the backends again to another backend if is_debug then print() print("[connect_server] ") end local least_idle_conns_ndx = 0 local least_idle_conns = 0 for i = 1, #proxy.global.backends do local s = proxy.global.backends[i] local pool = s.pool -- we don't have a username yet, try to find a connections which is idling local cur_idle = pool.users[""].cur_idle_connections if is_debug then print(" [".. i .."].connected_clients = " .. s.connected_clients) print(" [".. i .."].idling_connections = " .. cur_idle) print(" [".. i .."].type = " .. s.type) print(" [".. i .."].state = " .. s.state) end if s.state ~= proxy.BACKEND_STATE_DOWN then -- try to connect to each backend once at least if cur_idle == 0 then proxy.connection.backend_ndx = i if is_debug then print(" [".. i .."] open new connection") end return end -- try to open at least min_idle_connections if least_idle_conns_ndx == 0 or ( cur_idle < min_idle_connections and cur_idle < least_idle_conns ) then least_idle_conns_ndx = i least_idle_conns = s.idling_connections end end end if least_idle_conns_ndx > 0 then proxy.connection.backend_ndx = least_idle_conns_ndx end if proxy.connection.backend_ndx > 0 then local s = proxy.global.backends[proxy.connection.backend_ndx] local pool = s.pool -- we don't have a username yet, try to find a connections which is idling local cur_idle = pool.users[""].cur_idle_connections if cur_idle >= min_idle_connections then -- we have 4 idling connections in the pool, that's good enough if is_debug then print(" using pooled connection from: " .. proxy.connection.backend_ndx) end return proxy.PROXY_IGNORE_RESULT end end if is_debug then print(" opening new connection on: " .. proxy.connection.backend_ndx) end -- open a new connection end --- -- put the successfully authed connection into the connection pool -- -- @param auth the context information for the auth -- -- auth.packet is the packet function read_auth_result( auth ) if auth.packet:byte() == proxy.MYSQLD_PACKET_OK then -- auth was fine, disconnect from the server proxy.connection.backend_ndx = 0 elseif auth.packet:byte() == proxy.MYSQLD_PACKET_EOF then -- we received either a -- -- * MYSQLD_PACKET_ERR and the auth failed or -- * MYSQLD_PACKET_EOF which means a OLD PASSWORD (4.0) was sent print("(read_auth_result) ... not ok yet"); elseif auth.packet:byte() == proxy.MYSQLD_PACKET_ERR then -- auth failed end end --- -- read/write splitting function read_query( packet ) if is_debug then print("[read_query]") print(" authed backend = " .. proxy.connection.backend_ndx) print(" used db = " .. proxy.connection.client.default_db) end if packet:byte() == proxy.COM_QUIT then -- don't send COM_QUIT to the backend. We manage the connection -- in all aspects. proxy.response = { type = proxy.MYSQLD_PACKET_OK, } return proxy.PROXY_SEND_RESULT end if proxy.connection.backend_ndx == 0 then -- we don't have a backend right now -- -- let's pick a master as a good default for i = 1, #proxy.global.backends do local s = proxy.global.backends[i] local pool = s.pool -- we don't have a username yet, try to find a connections which is idling local cur_idle = pool.users[proxy.connection.client.username].cur_idle_connections if cur_idle > 0 and s.state ~= proxy.BACKEND_STATE_DOWN and s.type == proxy.BACKEND_TYPE_RW then proxy.connection.backend_ndx = i break end end end if true or proxy.connection.client.default_db and proxy.connection.client.default_db ~= proxy.connection.server.default_db then -- sync the client-side default_db with the server-side default_db proxy.queries:append(2, string.char(proxy.COM_INIT_DB) .. proxy.connection.client.default_db, { resultset_is_needed = true }) end proxy.queries:append(1, packet) return proxy.PROXY_SEND_QUERY end --- -- as long as we are in a transaction keep the connection -- otherwise release it so another client can use it function read_query_result( inj ) local res = assert(inj.resultset) local flags = res.flags if inj.id ~= 1 then -- ignore the result of the USE <default_db> return proxy.PROXY_IGNORE_RESULT end is_in_transaction = flags.in_trans if not is_in_transaction then -- release the backend proxy.connection.backend_ndx = 0 end end --- -- close the connections if we have enough connections in the pool -- -- @return nil - close connection -- IGNORE_RESULT - store connection in the pool function disconnect_client() if is_debug then print("[disconnect_client]") end if proxy.connection.backend_ndx == 0 then -- currently we don't have a server backend assigned -- -- pick a server which has too many idling connections and close one for i = 1, #proxy.global.backends do local s = proxy.global.backends[i] local pool = s.pool -- we don't have a username yet, try to find a connections which is idling local cur_idle = pool.users[proxy.connection.client.username].cur_idle_connections if s.state ~= proxy.BACKEND_STATE_DOWN and cur_idle > max_idle_connections then -- try to disconnect a backend proxy.connection.backend_ndx = i if is_debug then print(" [".. i .."] closing connection, idling: " .. cur_idle) end return end end end end
Lua
sum = 0 for i in 0:9 sum += i end println(sum)
Julia
#if ENABLE_UNET using System; using System.Runtime.InteropServices; namespace UnityEngine.Networking { // A growable buffer class used by NetworkReader and NetworkWriter. // this is used instead of MemoryStream and BinaryReader/BinaryWriter to avoid allocations. class NetBuffer { byte[] m_Buffer; uint m_Pos; const int k_InitialSize = 64; const float k_GrowthFactor = 1.5f; const int k_BufferSizeWarning = 1024 * 1024 * 128; public uint Position { get { return m_Pos; } } public int Length { get { return m_Buffer.Length; } } public NetBuffer() { m_Buffer = new byte[k_InitialSize]; } // this does NOT copy the buffer public NetBuffer(byte[] buffer) { m_Buffer = buffer; } public byte ReadByte() { if (m_Pos >= m_Buffer.Length) { throw new IndexOutOfRangeException("NetworkReader:ReadByte out of range:" + ToString()); } return m_Buffer[m_Pos++]; } public void ReadBytes(byte[] buffer, uint count) { if (m_Pos + count > m_Buffer.Length) { throw new IndexOutOfRangeException("NetworkReader:ReadBytes out of range: (" + count + ") " + ToString()); } for (ushort i = 0; i < count; i++) { buffer[i] = m_Buffer[m_Pos + i]; } m_Pos += count; } internal ArraySegment<byte> AsArraySegment() { return new ArraySegment<byte>(m_Buffer, 0, (int)m_Pos); } public void WriteByte(byte value) { WriteCheckForSpace(1); m_Buffer[m_Pos] = value; m_Pos += 1; } public void WriteByte2(byte value0, byte value1) { WriteCheckForSpace(2); m_Buffer[m_Pos] = value0; m_Buffer[m_Pos + 1] = value1; m_Pos += 2; } public void WriteByte4(byte value0, byte value1, byte value2, byte value3) { WriteCheckForSpace(4); m_Buffer[m_Pos] = value0; m_Buffer[m_Pos + 1] = value1; m_Buffer[m_Pos + 2] = value2; m_Buffer[m_Pos + 3] = value3; m_Pos += 4; } public void WriteByte8(byte value0, byte value1, byte value2, byte value3, byte value4, byte value5, byte value6, byte value7) { WriteCheckForSpace(8); m_Buffer[m_Pos] = value0; m_Buffer[m_Pos + 1] = value1; m_Buffer[m_Pos + 2] = value2; m_Buffer[m_Pos + 3] = value3; m_Buffer[m_Pos + 4] = value4; m_Buffer[m_Pos + 5] = value5; m_Buffer[m_Pos + 6] = value6; m_Buffer[m_Pos + 7] = value7; m_Pos += 8; } // every other Write() function in this class writes implicitly at the end-marker m_Pos. // this is the only Write() function that writes to a specific location within the buffer public void WriteBytesAtOffset(byte[] buffer, ushort targetOffset, ushort count) { uint newEnd = (uint)(count + targetOffset); WriteCheckForSpace((ushort)newEnd); if (targetOffset == 0 && count == buffer.Length) { buffer.CopyTo(m_Buffer, (int)m_Pos); } else { //CopyTo doesnt take a count :( for (int i = 0; i < count; i++) { m_Buffer[targetOffset + i] = buffer[i]; } } // although this writes within the buffer, it could move the end-marker if (newEnd > m_Pos) { m_Pos = newEnd; } } public void WriteBytes(byte[] buffer, ushort count) { WriteCheckForSpace(count); if (count == buffer.Length) { buffer.CopyTo(m_Buffer, (int)m_Pos); } else { //CopyTo doesnt take a count :( for (int i = 0; i < count; i++) { m_Buffer[m_Pos + i] = buffer[i]; } } m_Pos += count; } void WriteCheckForSpace(ushort count) { if (m_Pos + count < m_Buffer.Length) return; int newLen = (int)Math.Ceiling(m_Buffer.Length * k_GrowthFactor); while (m_Pos + count >= newLen) { newLen = (int)Math.Ceiling(newLen * k_GrowthFactor); if (newLen > k_BufferSizeWarning) { Debug.LogWarning("NetworkBuffer size is " + newLen + " bytes!"); } } // only do the copy once, even if newLen is increased multiple times byte[] tmp = new byte[newLen]; m_Buffer.CopyTo(tmp, 0); m_Buffer = tmp; } public void FinishMessage() { // two shorts (size and msgType) are in header. ushort sz = (ushort)(m_Pos - (sizeof(ushort) * 2)); m_Buffer[0] = (byte)(sz & 0xff); m_Buffer[1] = (byte)((sz >> 8) & 0xff); } public void SeekZero() { m_Pos = 0; } public void Replace(byte[] buffer) { m_Buffer = buffer; m_Pos = 0; } public override string ToString() { return String.Format("NetBuf sz:{0} pos:{1}", m_Buffer.Length, m_Pos); } } // end NetBuffer // -- helpers for float conversion -- [StructLayout(LayoutKind.Explicit)] internal struct UIntFloat { [FieldOffset(0)] public float floatValue; [FieldOffset(0)] public uint intValue; [FieldOffset(0)] public double doubleValue; [FieldOffset(0)] public ulong longValue; } [StructLayout(LayoutKind.Explicit)] internal struct UIntDecimal { [FieldOffset(0)] public ulong longValue1; [FieldOffset(8)] public ulong longValue2; [FieldOffset(0)] public decimal decimalValue; } internal class FloatConversion { public static float ToSingle(uint value) { UIntFloat uf = new UIntFloat(); uf.intValue = value; return uf.floatValue; } public static double ToDouble(ulong value) { UIntFloat uf = new UIntFloat(); uf.longValue = value; return uf.doubleValue; } public static decimal ToDecimal(ulong value1, ulong value2) { UIntDecimal uf = new UIntDecimal(); uf.longValue1 = value1; uf.longValue2 = value2; return uf.decimalValue; } } } #endif
C#
# The set of languages for which implicit dependencies are needed: SET(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: SET(CMAKE_DEPENDS_CHECK_CXX "/home/vv/groovy/pr2_tf/pr2_tf/src/pr2_tf_broadcaster.cpp" "/home/vv/groovy/pr2_tf/pr2_tf/build/CMakeFiles/pr2_tf_broadcaster.dir/src/pr2_tf_broadcaster.cpp.o" ) SET(CMAKE_CXX_COMPILER_ID "GNU") # Preprocessor definitions for this target. SET(CMAKE_TARGET_DEFINITIONS "DISABLE_OPENNI" "DISABLE_OPENNI" "EIGEN_USE_NEW_STDVECTOR" "EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET" "FLANN_STATIC" "qh_QHpointer" ) # Targets to which this target links. SET(CMAKE_TARGET_LINKED_INFO_FILES )
CMake
#!/bin/sh # # Start-up script for the GUI of ProGuard -- free class file shrinker, # optimizer, obfuscator, and preverifier for Java bytecode. # # Note: when passing file names containing spaces to this script, # you'll have to add escaped quotes around them, e.g. # "\"/My Directory/My File.txt\"" PROGUARD_HOME=`dirname "$0"` PROGUARD_HOME=`dirname "$PROGUARD_HOME"` java -jar $PROGUARD_HOME/lib/proguardgui.jar "$@"
Shell
package com.facetime.mgr.domain; import com.facetime.core.bean.BusinessObject; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.hibernate.annotations.GenericGenerator; @Entity public class UsrUsrGrp implements BusinessObject { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "system-uuid") @GenericGenerator(name = "system-uuid", strategy = "uuid") private String id; private String grpcode; private String userid; public UsrUsrGrp() { } /** full constructor */ public UsrUsrGrp(String id, String userid, String grpcode) { this.id = id; this.userid = userid; this.grpcode = grpcode; } @Override public boolean equals(Object other) { if (!(other instanceof UsrUsrGrp)) return false; UsrUsrGrp castOther = (UsrUsrGrp) other; return new EqualsBuilder().append(getId(), castOther.getId()).isEquals(); } public String getGrpcode() { return grpcode; } public String getId() { return id; } public String getUserid() { return userid; } @Override public int hashCode() { return new HashCodeBuilder().append(getId()).toHashCode(); } public void setGrpcode(String grpcode) { this.grpcode = grpcode; } public void setId(String id) { this.id = id; } public void setUserid(String userid) { this.userid = userid; } @Override public String toString() { return new ToStringBuilder(this).append("id", getId()).toString(); } }
Java
package me.smecsia.gawain.elasticsearch import groovy.transform.CompileStatic import me.smecsia.gawain.Opts import me.smecsia.gawain.Repository import me.smecsia.gawain.builders.RepoBuilder import me.smecsia.gawain.error.InitializationException import me.smecsia.gawain.serialize.ToJsonStateSerializer import org.elasticsearch.client.Client /** * @author Ilya Sadykov */ @CompileStatic class ElasticRepoBuilder implements RepoBuilder { public static final String LOCKS_SUFFIX = '__locks' final Client client final Opts opts final String indexName, locksSuffix ElasticRepoBuilder(Client client, String indexName, Opts opts = new Opts()) { this(client, indexName, LOCKS_SUFFIX, opts) } ElasticRepoBuilder(Client client, String indexName, String locksSuffix, Opts opts = new Opts()) { this.client = client this.opts = opts this.indexName = indexName this.locksSuffix = locksSuffix } @Override Repository build(String name, Opts opts) { if (!(opts.stateSerializer instanceof ToJsonStateSerializer)) { throw new InitializationException("Cannot use ${opts.stateSerializer}! " + "ElasticSearch supports only serialization to json") } def locking = new ElasticPessimisticLocking(client, indexName, "${name}${locksSuffix}", opts.lockPollIntervalMs) new ElasticRepo(indexName, name, locking, opts.stateSerializer as ToJsonStateSerializer, opts.maxLockWaitMs) } }
Groovy
// Verilog model: Circuit with boolean expressions module example_3_4(E, F, A, B, C, D); output E, F; input A, B, C, D; assign E = A || (B && C) || ((!B) && D); assign F = ((!B) && C) || (B && (!C) && (!D)); endmodule
Coq
#Requires -Version 3.0 #Requires -Module AzureRM.Resources #Requires -Module Azure.Storage Param( [string] [Parameter(Mandatory=$true)] $ResourceGroupLocation, [string] $ResourceGroupName = 'MusgraveAzure', [switch] $UploadArtifacts, [string] $StorageAccountName, [string] $StorageContainerName = $ResourceGroupName.ToLowerInvariant() + '-stageartifacts', [string] $TemplateFile = 'azuredeploy.json', [string] $TemplateParametersFile = 'azuredeploy.parameters.json', [string] $ArtifactStagingDirectory = '.', [string] $DSCSourceFolder = 'DSC', [switch] $ValidateOnly ) Import-Module Azure -ErrorAction SilentlyContinue try { [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent("VSAzureTools-$UI$($host.name)".replace(" ","_"), "2.9.6") } catch { } Set-StrictMode -Version 3 function Format-ValidationOutput { param ($ValidationOutput, [int] $Depth = 0) Set-StrictMode -Off return @($ValidationOutput | Where-Object { $_ -ne $null } | ForEach-Object { @(" " * $Depth + $_.Code + ": " + $_.Message) + @(Format-ValidationOutput @($_.Details) ($Depth + 1)) }) } $OptionalParameters = New-Object -TypeName Hashtable $TemplateFile = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, $TemplateFile)) $TemplateParametersFile = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, $TemplateParametersFile)) if ($UploadArtifacts) { # Convert relative paths to absolute paths if needed $ArtifactStagingDirectory = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, $ArtifactStagingDirectory)) $DSCSourceFolder = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, $DSCSourceFolder)) Set-Variable ArtifactsLocationName '_artifactsLocation' -Option ReadOnly -Force Set-Variable ArtifactsLocationSasTokenName '_artifactsLocationSasToken' -Option ReadOnly -Force $OptionalParameters.Add($ArtifactsLocationName, $null) $OptionalParameters.Add($ArtifactsLocationSasTokenName, $null) # Parse the parameter file and update the values of artifacts location and artifacts location SAS token if they are present $JsonContent = Get-Content $TemplateParametersFile -Raw | ConvertFrom-Json $JsonParameters = $JsonContent | Get-Member -Type NoteProperty | Where-Object {$_.Name -eq "parameters"} if ($JsonParameters -eq $null) { $JsonParameters = $JsonContent } else { $JsonParameters = $JsonContent.parameters } $JsonParameters | Get-Member -Type NoteProperty | ForEach-Object { $ParameterValue = $JsonParameters | Select-Object -ExpandProperty $_.Name if ($_.Name -eq $ArtifactsLocationName -or $_.Name -eq $ArtifactsLocationSasTokenName) { $OptionalParameters[$_.Name] = $ParameterValue.value } } # Create DSC configuration archive if (Test-Path $DSCSourceFolder) { $DSCSourceFilePaths = @(Get-ChildItem $DSCSourceFolder -File -Filter "*.ps1" | ForEach-Object -Process {$_.FullName}) foreach ($DSCSourceFilePath in $DSCSourceFilePaths) { $DSCArchiveFilePath = $DSCSourceFilePath.Substring(0, $DSCSourceFilePath.Length - 4) + ".zip" Publish-AzureRmVMDscConfiguration $DSCSourceFilePath -OutputArchivePath $DSCArchiveFilePath -Force -Verbose } } # Create a storage account name if none was provided if($StorageAccountName -eq "") { $subscriptionId = ((Get-AzureRmContext).Subscription.SubscriptionId).Replace('-', '').substring(0, 19) $StorageAccountName = "stage$subscriptionId" } $StorageAccount = (Get-AzureRmStorageAccount | Where-Object{$_.StorageAccountName -eq $StorageAccountName}) # Create the storage account if it doesn't already exist if($StorageAccount -eq $null){ $StorageResourceGroupName = "ARM_Deploy_Staging" New-AzureRmResourceGroup -Location "$ResourceGroupLocation" -Name $StorageResourceGroupName -Force $StorageAccount = New-AzureRmStorageAccount -StorageAccountName $StorageAccountName -Type 'Standard_LRS' -ResourceGroupName $StorageResourceGroupName -Location "$ResourceGroupLocation" } $StorageAccountContext = (Get-AzureRmStorageAccount | Where-Object{$_.StorageAccountName -eq $StorageAccountName}).Context # Generate the value for artifacts location if it is not provided in the parameter file $ArtifactsLocation = $OptionalParameters[$ArtifactsLocationName] if ($ArtifactsLocation -eq $null) { $ArtifactsLocation = $StorageAccountContext.BlobEndPoint + $StorageContainerName $OptionalParameters[$ArtifactsLocationName] = $ArtifactsLocation } # Copy files from the local storage staging location to the storage account container New-AzureStorageContainer -Name $StorageContainerName -Context $StorageAccountContext -ErrorAction SilentlyContinue *>&1 $ArtifactFilePaths = Get-ChildItem $ArtifactStagingDirectory -Recurse -File | ForEach-Object -Process {$_.FullName} foreach ($SourcePath in $ArtifactFilePaths) { $BlobName = $SourcePath.Substring($ArtifactStagingDirectory.length + 1) Set-AzureStorageBlobContent -File $SourcePath -Blob $BlobName -Container $StorageContainerName -Context $StorageAccountContext -Force -ErrorAction Stop } # Generate the value for artifacts location SAS token if it is not provided in the parameter file $ArtifactsLocationSasToken = $OptionalParameters[$ArtifactsLocationSasTokenName] if ($ArtifactsLocationSasToken -eq $null) { # Create a SAS token for the storage container - this gives temporary read-only access to the container $ArtifactsLocationSasToken = New-AzureStorageContainerSASToken -Container $StorageContainerName -Context $StorageAccountContext -Permission r -ExpiryTime (Get-Date).AddHours(4) $ArtifactsLocationSasToken = ConvertTo-SecureString $ArtifactsLocationSasToken -AsPlainText -Force $OptionalParameters[$ArtifactsLocationSasTokenName] = $ArtifactsLocationSasToken } } # Create or update the resource group using the specified template file and template parameters file New-AzureRmResourceGroup -Name $ResourceGroupName -Location $ResourceGroupLocation -Verbose -Force -ErrorAction Stop $ErrorMessages = @() if ($ValidateOnly) { $ErrorMessages = Format-ValidationOutput (Test-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName ` -TemplateFile $TemplateFile ` -TemplateParameterFile $TemplateParametersFile ` @OptionalParameters ` -Verbose) } else { New-AzureRmResourceGroupDeployment -Name ((Get-ChildItem $TemplateFile).BaseName + '-' + ((Get-Date).ToUniversalTime()).ToString('MMdd-HHmm')) ` -ResourceGroupName $ResourceGroupName ` -TemplateFile $TemplateFile ` -TemplateParameterFile $TemplateParametersFile ` @OptionalParameters ` -Force -Verbose ` -ErrorVariable ErrorMessages $ErrorMessages = $ErrorMessages | ForEach-Object { $_.Exception.Message.TrimEnd("`r`n") } } if ($ErrorMessages) { "", ("{0} returned the following errors:" -f ("Template deployment", "Validation")[[bool]$ValidateOnly]), @($ErrorMessages) | ForEach-Object { Write-Output $_ } }
PowerShell
FILE(REMOVE_RECURSE "CMakeFiles/git-osc-qml.zoker.pot" ) # Per-language clean rules from dependency scanning. FOREACH(lang) INCLUDE(CMakeFiles/git-osc-qml.zoker.pot.dir/cmake_clean_${lang}.cmake OPTIONAL) ENDFOREACH(lang)
CMake
;;; ---------------------------------------------------------------------------- ;;; gdk.init.lisp ;;; ;;; This file contains code from a fork of cl-gtk2. ;;; See http://common-lisp.net/project/cl-gtk2/ ;;; ;;; Copyright (C) 2009 - 2011 Kalyanov Dmitry ;;; Copyright (C) 2011 - 2014 Dieter Kaiser ;;; ;;; This program is free software: you can redistribute it and/or modify ;;; it under the terms of the GNU Lesser General Public License for Lisp ;;; as published by the Free Software Foundation, either version 3 of the ;;; License, or (at your option) any later version and with a preamble to ;;; the GNU Lesser General Public License that clarifies the terms for use ;;; with Lisp programs and is referred as the LLGPL. ;;; ;;; 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 Lesser General Public License for more details. ;;; ;;; You should have received a copy of the GNU Lesser General Public ;;; License along with this program and the preamble to the Gnu Lesser ;;; General Public License. If not, see <http://www.gnu.org/licenses/> ;;; and <http://opensource.franz.com/preamble.html>. ;;; ---------------------------------------------------------------------------- (in-package :gdk) (glib::at-init () (eval-when (:compile-toplevel :load-toplevel :execute) (define-foreign-library gdk ((:and :unix (:not :darwin)) (:or "libgdk-3.so.0" "libgdk-3.so")) (:darwin (:or "libgdk-3.0.dylib" "libgdk-3.dylib" "libgdk-x11-3.0.0.dylib" "libgdk-x11-3.0.dylib")) (:windows "libgdk-3-0.dll") (t "libgdk-3-0"))) (use-foreign-library gdk)) ;;; End of file gdk.init.lisp --------------------------------------------------
Common Lisp
%% Copyright (c) 2011-2013, Loïc Hoguin <essen@ninenines.eu> %% Copyright (c) 2011, Anthony Ramine <nox@dev-extend.eu> %% %% Permission to use, copy, modify, and/or distribute this software for any %% purpose with or without fee is hereby granted, provided that the above %% copyright notice and this permission notice appear in all copies. %% %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% @doc HTTP protocol handler. %% %% The available options are: %% <dl> %% <dt>compress</dt><dd>Whether to automatically compress the response %% body when the conditions are met. Disabled by default.</dd> %% <dt>env</dt><dd>The environment passed and optionally modified %% by middlewares.</dd> %% <dt>max_empty_lines</dt><dd>Max number of empty lines before a request. %% Defaults to 5.</dd> %% <dt>max_header_name_length</dt><dd>Max length allowed for header names. %% Defaults to 64.</dd> %% <dt>max_header_value_length</dt><dd>Max length allowed for header values. %% Defaults to 4096.</dd> %% <dt>max_headers</dt><dd>Max number of headers allowed. %% Defaults to 100.</dd> %% <dt>max_keepalive</dt><dd>Max number of requests allowed in a single %% keep-alive session. Defaults to 100.</dd> %% <dt>max_request_line_length</dt><dd>Max length allowed for the request %% line. Defaults to 4096.</dd> %% <dt>middlewares</dt><dd>The list of middlewares to execute when a %% request is received.</dd> %% <dt>onrequest</dt><dd>Optional fun that allows Req interaction before %% any dispatching is done. Host info, path info and bindings are thus %% not available at this point.</dd> %% <dt>onresponse</dt><dd>Optional fun that allows replacing a response %% sent by the application.</dd> %% <dt>timeout</dt><dd>Time in milliseconds a client has to send the %% full request line and headers. Defaults to 5000 milliseconds.</dd> %% </dl> %% %% Note that there is no need to monitor these processes when using Cowboyku as %% an application as it already supervises them under the listener supervisor. -module(cowboyku_protocol). %% API. -export([ become/4, start_link/4 ]). %% Internal. -export([init/4]). -export([parse_request/3]). -export([resume/6]). -type opts() :: [{compress, boolean()} | {env, cowboyku_middleware:env()} | {max_empty_lines, non_neg_integer()} | {max_header_name_length, non_neg_integer()} | {max_header_value_length, non_neg_integer()} | {max_headers, non_neg_integer()} | {max_keepalive, non_neg_integer()} | {max_request_line_length, non_neg_integer()} | {middlewares, [module()]} | {onrequest, cowboyku:onrequest_fun()} | {onresponse, cowboyku:onresponse_fun()} | {timeout, timeout()}]. -export_type([opts/0]). -record(state, { socket :: inet:socket(), transport :: module(), middlewares :: [module()], compress :: boolean(), env :: cowboyku_middleware:env(), onrequest :: undefined | cowboyku:onrequest_fun(), onresponse = undefined :: undefined | cowboyku:onresponse_fun(), max_empty_lines :: non_neg_integer(), req_keepalive = 1 :: non_neg_integer(), max_keepalive :: non_neg_integer(), max_request_line_length :: non_neg_integer(), max_header_name_length :: non_neg_integer(), max_header_value_length :: non_neg_integer(), max_headers :: non_neg_integer(), timeout :: timeout(), until :: non_neg_integer() | infinity }). %% API. %% @doc Start an HTTP protocol process. -spec start_link(ranch:ref(), inet:socket(), module(), opts()) -> {ok, pid()}. start_link(Ref, Socket, Transport, Opts) -> Pid = spawn_link(?MODULE, init, [Ref, Socket, Transport, Opts]), {ok, Pid}. %% Internal. %% @doc Faster alternative to proplists:get_value/3. %% @private get_value(Key, Opts, Default) -> case lists:keyfind(Key, 1, Opts) of {_, Value} -> Value; _ -> Default end. %% @private -spec init(ranch:ref(), inet:socket(), module(), opts()) -> ok. init(Ref, Socket, Transport, Opts) -> ok = ranch:accept_ack(Ref), become(Ref, Socket, Transport, Opts). -spec become( Ref :: ranch:ref(), Socket :: inet:socket(), Transport :: module(), Opts :: [proplists:property()]) -> any(). become(Ref, Socket, Transport, Opts) -> Compress = get_value(compress, Opts, false), MaxEmptyLines = get_value(max_empty_lines, Opts, 5), MaxHeaderNameLength = get_value(max_header_name_length, Opts, 64), MaxHeaderValueLength = get_value(max_header_value_length, Opts, 4096), MaxHeaders = get_value(max_headers, Opts, 100), MaxKeepalive = get_value(max_keepalive, Opts, 100), MaxRequestLineLength = get_value(max_request_line_length, Opts, 4096), Middlewares = get_value(middlewares, Opts, [cowboyku_router, cowboyku_handler]), Env = [{listener, Ref}|get_value(env, Opts, [])], OnRequest = get_value(onrequest, Opts, undefined), OnResponse = get_value(onresponse, Opts, undefined), Timeout = get_value(timeout, Opts, 5000), wait_request(<<>>, #state{socket=Socket, transport=Transport, middlewares=Middlewares, compress=Compress, env=Env, max_empty_lines=MaxEmptyLines, max_keepalive=MaxKeepalive, max_request_line_length=MaxRequestLineLength, max_header_name_length=MaxHeaderNameLength, max_header_value_length=MaxHeaderValueLength, max_headers=MaxHeaders, onrequest=OnRequest, onresponse=OnResponse, timeout=Timeout, until=until(Timeout)}, 0). -spec until(timeout()) -> non_neg_integer() | infinity. until(infinity) -> infinity; until(Timeout) -> {Me, S, Mi} = os:timestamp(), Me * 1000000000 + S * 1000 + Mi div 1000 + Timeout. %% Request parsing. %% %% The next set of functions is the request parsing code. All of it %% runs using a single binary match context. This optimization ends %% right after the header parsing is finished and the code becomes %% more interesting past that point. -spec recv(inet:socket(), module(), non_neg_integer() | infinity) -> {ok, binary()} | {error, closed | timeout | atom()}. recv(Socket, Transport, infinity) -> Transport:recv(Socket, 0, infinity); recv(Socket, Transport, Until) -> {Me, S, Mi} = os:timestamp(), Now = Me * 1000000000 + S * 1000 + Mi div 1000, Timeout = Until - Now, if Timeout < 0 -> {error, timeout}; true -> Transport:recv(Socket, 0, Timeout) end. -spec wait_request(binary(), #state{}, non_neg_integer()) -> ok. wait_request(Buffer, State=#state{socket=Socket, transport=Transport, until=Until}, ReqEmpty) -> case recv(Socket, Transport, Until) of {ok, Data} -> parse_request(<< Buffer/binary, Data/binary >>, State, ReqEmpty); {error, _} -> terminate(State) end. %% @private -spec parse_request(binary(), #state{}, non_neg_integer()) -> ok. %% Empty lines must be using \r\n. parse_request(<< $\n, _/binary >>, State, _) -> error_terminate(400, State); %% We limit the length of the Request-line to MaxLength to avoid endlessly %% reading from the socket and eventually crashing. parse_request(Buffer, State=#state{max_request_line_length=MaxLength, max_empty_lines=MaxEmpty}, ReqEmpty) -> case match_eol(Buffer, 0) of nomatch when byte_size(Buffer) > MaxLength -> error_terminate(414, State); nomatch -> wait_request(Buffer, State, ReqEmpty); 1 when ReqEmpty =:= MaxEmpty -> error_terminate(400, State); 1 -> << _:16, Rest/binary >> = Buffer, parse_request(Rest, State, ReqEmpty + 1); _ -> parse_method(Buffer, State, <<>>) end. match_eol(<< $\n, _/bits >>, N) -> N; match_eol(<< _, Rest/bits >>, N) -> match_eol(Rest, N + 1); match_eol(_, _) -> nomatch. parse_method(<< C, Rest/bits >>, State, SoFar) -> case C of $\r -> error_terminate(400, State); $\s -> parse_uri(Rest, State, SoFar); _ -> parse_method(Rest, State, << SoFar/binary, C >>) end. parse_uri(<< $\r, _/bits >>, State, _) -> error_terminate(400, State); parse_uri(<< "* ", Rest/bits >>, State, Method) -> parse_version(Rest, State, Method, <<"*">>, <<>>); parse_uri(<< "http://", Rest/bits >>, State, Method) -> parse_uri_skip_host(Rest, State, Method); parse_uri(<< "https://", Rest/bits >>, State, Method) -> parse_uri_skip_host(Rest, State, Method); parse_uri(Buffer, State, Method) -> parse_uri_path(Buffer, State, Method, <<>>). parse_uri_skip_host(<< C, Rest/bits >>, State, Method) -> case C of $\r -> error_terminate(400, State); $/ -> parse_uri_path(Rest, State, Method, <<"/">>); _ -> parse_uri_skip_host(Rest, State, Method) end. parse_uri_path(<< C, Rest/bits >>, State, Method, SoFar) -> case C of $\r -> error_terminate(400, State); $\s -> parse_version(Rest, State, Method, SoFar, <<>>); $? -> parse_uri_query(Rest, State, Method, SoFar, <<>>); $# -> skip_uri_fragment(Rest, State, Method, SoFar, <<>>); _ -> parse_uri_path(Rest, State, Method, << SoFar/binary, C >>) end. parse_uri_query(<< C, Rest/bits >>, S, M, P, SoFar) -> case C of $\r -> error_terminate(400, S); $\s -> parse_version(Rest, S, M, P, SoFar); $# -> skip_uri_fragment(Rest, S, M, P, SoFar); _ -> parse_uri_query(Rest, S, M, P, << SoFar/binary, C >>) end. skip_uri_fragment(<< C, Rest/bits >>, S, M, P, Q) -> case C of $\r -> error_terminate(400, S); $\s -> parse_version(Rest, S, M, P, Q); _ -> skip_uri_fragment(Rest, S, M, P, Q) end. parse_version(<< "HTTP/1.1\r\n", Rest/bits >>, S, M, P, Q) -> parse_header(Rest, S, M, P, Q, 'HTTP/1.1', []); parse_version(<< "HTTP/1.0\r\n", Rest/bits >>, S, M, P, Q) -> parse_header(Rest, S, M, P, Q, 'HTTP/1.0', []); parse_version(_, State, _, _, _) -> error_terminate(505, State). %% Stop receiving data if we have more than allowed number of headers. wait_header(_, State=#state{max_headers=MaxHeaders}, _, _, _, _, Headers) when length(Headers) >= MaxHeaders -> error_terminate(400, State); wait_header(Buffer, State=#state{socket=Socket, transport=Transport, until=Until}, M, P, Q, V, H) -> case recv(Socket, Transport, Until) of {ok, Data} -> parse_header(<< Buffer/binary, Data/binary >>, State, M, P, Q, V, H); {error, timeout} -> error_terminate(408, State); {error, _} -> terminate(State) end. parse_header(<< $\r, $\n, Rest/bits >>, S, M, P, Q, V, Headers) -> request(Rest, S, M, P, Q, V, lists:reverse(Headers)); parse_header(Buffer, State=#state{max_header_name_length=MaxLength}, M, P, Q, V, H) -> case match_colon(Buffer, 0) of nomatch when byte_size(Buffer) > MaxLength -> error_terminate(400, State); nomatch -> wait_header(Buffer, State, M, P, Q, V, H); _ -> parse_hd_name(Buffer, State, M, P, Q, V, H, <<>>) end. match_colon(<< $:, _/bits >>, N) -> N; match_colon(<< _, Rest/bits >>, N) -> match_colon(Rest, N + 1); match_colon(_, _) -> nomatch. %% I know, this isn't exactly pretty. But this is the most critical %% code path and as such needs to be optimized to death. %% %% ... Sorry for your eyes. %% %% But let's be honest, that's still pretty readable. parse_hd_name(<< C, Rest/bits >>, S, M, P, Q, V, H, SoFar) -> case C of $: -> parse_hd_before_value(Rest, S, M, P, Q, V, H, SoFar); $\s -> parse_hd_name_ws(Rest, S, M, P, Q, V, H, SoFar); $\t -> parse_hd_name_ws(Rest, S, M, P, Q, V, H, SoFar); $A -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $a >>); $B -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $b >>); $C -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $c >>); $D -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $d >>); $E -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $e >>); $F -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $f >>); $G -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $g >>); $H -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $h >>); $I -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $i >>); $J -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $j >>); $K -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $k >>); $L -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $l >>); $M -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $m >>); $N -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $n >>); $O -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $o >>); $P -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $p >>); $Q -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $q >>); $R -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $r >>); $S -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $s >>); $T -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $t >>); $U -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $u >>); $V -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $v >>); $W -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $w >>); $X -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $x >>); $Y -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $y >>); $Z -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, $z >>); C -> parse_hd_name(Rest, S, M, P, Q, V, H, << SoFar/binary, C >>) end. parse_hd_name_ws(<< C, Rest/bits >>, S, M, P, Q, V, H, Name) -> case C of $\s -> parse_hd_name_ws(Rest, S, M, P, Q, V, H, Name); $\t -> parse_hd_name_ws(Rest, S, M, P, Q, V, H, Name); $: -> parse_hd_before_value(Rest, S, M, P, Q, V, H, Name); _ -> error_terminate(400, S) end. wait_hd_before_value(Buffer, State=#state{ socket=Socket, transport=Transport, until=Until}, M, P, Q, V, H, N) -> case recv(Socket, Transport, Until) of {ok, Data} -> parse_hd_before_value(<< Buffer/binary, Data/binary >>, State, M, P, Q, V, H, N); {error, timeout} -> error_terminate(408, State); {error, _} -> terminate(State) end. parse_hd_before_value(<< $\s, Rest/bits >>, S, M, P, Q, V, H, N) -> parse_hd_before_value(Rest, S, M, P, Q, V, H, N); parse_hd_before_value(<< $\t, Rest/bits >>, S, M, P, Q, V, H, N) -> parse_hd_before_value(Rest, S, M, P, Q, V, H, N); parse_hd_before_value(Buffer, State=#state{ max_header_value_length=MaxLength}, M, P, Q, V, H, N) -> case match_eol(Buffer, 0) of nomatch when byte_size(Buffer) > MaxLength -> error_terminate(400, State); nomatch -> wait_hd_before_value(Buffer, State, M, P, Q, V, H, N); _ -> parse_hd_value(Buffer, State, M, P, Q, V, H, N, <<>>) end. %% We completely ignore the first argument which is always %% the empty binary. We keep it there because we don't want %% to change the other arguments' position and trigger costy %% operations for no reasons. wait_hd_value(_, State=#state{ socket=Socket, transport=Transport, until=Until}, M, P, Q, V, H, N, SoFar) -> case recv(Socket, Transport, Until) of {ok, Data} -> parse_hd_value(Data, State, M, P, Q, V, H, N, SoFar); {error, timeout} -> error_terminate(408, State); {error, _} -> terminate(State) end. %% Pushing back as much as we could the retrieval of new data %% to check for multilines allows us to avoid a few tests in %% the critical path, but forces us to have a special function. wait_hd_value_nl(_, State=#state{ socket=Socket, transport=Transport, until=Until}, M, P, Q, V, Headers, Name, SoFar) -> case recv(Socket, Transport, Until) of {ok, << C, Data/bits >>} when C =:= $\s; C =:= $\t -> parse_hd_value(Data, State, M, P, Q, V, Headers, Name, SoFar); {ok, Data} -> parse_header(Data, State, M, P, Q, V, [{Name, SoFar}|Headers]); {error, timeout} -> error_terminate(408, State); {error, _} -> terminate(State) end. parse_hd_value(<< $\r, Rest/bits >>, S, M, P, Q, V, Headers, Name, SoFar) -> case Rest of << $\n >> -> wait_hd_value_nl(<<>>, S, M, P, Q, V, Headers, Name, SoFar); << $\n, C, Rest2/bits >> when C =:= $\s; C =:= $\t -> parse_hd_value(Rest2, S, M, P, Q, V, Headers, Name, SoFar); << $\n, Rest2/bits >> -> parse_header(Rest2, S, M, P, Q, V, [{Name, SoFar}|Headers]); _ -> error_terminate(400, S) end; parse_hd_value(<< C, Rest/bits >>, S, M, P, Q, V, H, N, SoFar) -> parse_hd_value(Rest, S, M, P, Q, V, H, N, << SoFar/binary, C >>); parse_hd_value(<<>>, State=#state{max_header_value_length=MaxLength}, _, _, _, _, _, _, SoFar) when byte_size(SoFar) > MaxLength -> error_terminate(400, State); parse_hd_value(<<>>, S, M, P, Q, V, H, N, SoFar) -> wait_hd_value(<<>>, S, M, P, Q, V, H, N, SoFar); parse_hd_value(_, State, _M, _P, _Q, _V, _H, _N, _SoFar) -> error_terminate(400, State). request(B, State=#state{transport=Transport}, M, P, Q, Version, Headers) -> case lists:keyfind(<<"host">>, 1, Headers) of false when Version =:= 'HTTP/1.1' -> error_terminate(400, State); false -> request(B, State, M, P, Q, Version, Headers, <<>>, default_port(Transport:name())); {_, RawHost} -> try parse_host(RawHost, false, <<>>) of {Host, undefined} -> request(B, State, M, P, Q, Version, Headers, Host, default_port(Transport:name())); {Host, Port} -> request(B, State, M, P, Q, Version, Headers, Host, Port) catch _:_ -> error_terminate(400, State) end end. -spec default_port(atom()) -> 80 | 443. default_port(ssl) -> 443; default_port(_) -> 80. %% Another hurtful block of code. :) %% %% Same code as cow_http:parse_fullhost/1, but inline because we %% really want this to go fast. parse_host(<< $[, Rest/bits >>, false, <<>>) -> parse_host(Rest, true, << $[ >>); parse_host(<<>>, false, Acc) -> {Acc, undefined}; parse_host(<< $:, Rest/bits >>, false, Acc) -> {Acc, list_to_integer(binary_to_list(Rest))}; parse_host(<< $], Rest/bits >>, true, Acc) -> parse_host(Rest, false, << Acc/binary, $] >>); parse_host(<< C, Rest/bits >>, E, Acc) -> case C of $A -> parse_host(Rest, E, << Acc/binary, $a >>); $B -> parse_host(Rest, E, << Acc/binary, $b >>); $C -> parse_host(Rest, E, << Acc/binary, $c >>); $D -> parse_host(Rest, E, << Acc/binary, $d >>); $E -> parse_host(Rest, E, << Acc/binary, $e >>); $F -> parse_host(Rest, E, << Acc/binary, $f >>); $G -> parse_host(Rest, E, << Acc/binary, $g >>); $H -> parse_host(Rest, E, << Acc/binary, $h >>); $I -> parse_host(Rest, E, << Acc/binary, $i >>); $J -> parse_host(Rest, E, << Acc/binary, $j >>); $K -> parse_host(Rest, E, << Acc/binary, $k >>); $L -> parse_host(Rest, E, << Acc/binary, $l >>); $M -> parse_host(Rest, E, << Acc/binary, $m >>); $N -> parse_host(Rest, E, << Acc/binary, $n >>); $O -> parse_host(Rest, E, << Acc/binary, $o >>); $P -> parse_host(Rest, E, << Acc/binary, $p >>); $Q -> parse_host(Rest, E, << Acc/binary, $q >>); $R -> parse_host(Rest, E, << Acc/binary, $r >>); $S -> parse_host(Rest, E, << Acc/binary, $s >>); $T -> parse_host(Rest, E, << Acc/binary, $t >>); $U -> parse_host(Rest, E, << Acc/binary, $u >>); $V -> parse_host(Rest, E, << Acc/binary, $v >>); $W -> parse_host(Rest, E, << Acc/binary, $w >>); $X -> parse_host(Rest, E, << Acc/binary, $x >>); $Y -> parse_host(Rest, E, << Acc/binary, $y >>); $Z -> parse_host(Rest, E, << Acc/binary, $z >>); _ -> parse_host(Rest, E, << Acc/binary, C >>) end. %% End of request parsing. %% %% We create the Req object and start handling the request. request(Buffer, State=#state{socket=Socket, transport=Transport, req_keepalive=ReqKeepalive, max_keepalive=MaxKeepalive, compress=Compress, onresponse=OnResponse}, Method, Path, Query, Version, Headers, Host, Port) -> case Transport:peername(Socket) of {ok, Peer} -> Req = cowboyku_req:new(Socket, Transport, Peer, Method, Path, Query, Version, Headers, Host, Port, Buffer, ReqKeepalive < MaxKeepalive, Compress, OnResponse), onrequest(Req, State); {error, _} -> %% Couldn't read the peer address; connection is gone. terminate(State) end. %% Call the global onrequest callback. The callback can send a reply, %% in which case we consider the request handled and move on to the next %% one. Note that since we haven't dispatched yet, we don't know the %% handler, host_info, path_info or bindings yet. -spec onrequest(cowboyku_req:req(), #state{}) -> ok. onrequest(Req, State=#state{onrequest=undefined}) -> execute(Req, State); onrequest(Req, State=#state{onrequest=OnRequest}) -> Req2 = OnRequest(Req), case cowboyku_req:get(resp_state, Req2) of waiting -> execute(Req2, State); _ -> next_request(Req2, State, ok) end. -spec execute(cowboyku_req:req(), #state{}) -> ok. execute(Req, State=#state{middlewares=Middlewares, env=Env}) -> execute(Req, State, Env, Middlewares). -spec execute(cowboyku_req:req(), #state{}, cowboyku_middleware:env(), [module()]) -> ok. execute(Req, State, Env, []) -> next_request(Req, State, get_value(result, Env, ok)); execute(Req, State, Env, [Middleware|Tail]) -> case Middleware:execute(Req, Env) of {ok, Req2, Env2} -> execute(Req2, State, Env2, Tail); {suspend, Module, Function, Args} -> erlang:hibernate(?MODULE, resume, [State, Env, Tail, Module, Function, Args]); {halt, Req2} -> next_request(Req2, State, ok); {error, Code, Req2} -> error_terminate(Code, Req2, State) end. %% @private -spec resume(#state{}, cowboyku_middleware:env(), [module()], module(), module(), [any()]) -> ok. resume(State, Env, Tail, Module, Function, Args) -> case apply(Module, Function, Args) of {ok, Req2, Env2} -> execute(Req2, State, Env2, Tail); {suspend, Module2, Function2, Args2} -> erlang:hibernate(?MODULE, resume, [State, Env, Tail, Module2, Function2, Args2]); {halt, Req2} -> next_request(Req2, State, ok); {error, Code, Req2} -> error_terminate(Code, Req2, State) end. -spec next_request(cowboyku_req:req(), #state{}, any()) -> ok. next_request(Req, State=#state{req_keepalive=Keepalive, timeout=Timeout}, HandlerRes) -> cowboyku_req:ensure_response(Req, 204), %% If we are going to close the connection, %% we do not want to attempt to skip the body. case cowboyku_req:get(connection, Req) of close -> terminate(State); _ -> Buffer = case cowboyku_req:skip_body(Req) of {ok, Req2} -> cowboyku_req:get(buffer, Req2); _ -> close end, %% Flush the resp_sent message before moving on. receive {cowboyku_req, resp_sent} -> ok after 0 -> ok end, if HandlerRes =:= ok, Buffer =/= close -> ?MODULE:parse_request(Buffer, State#state{req_keepalive=Keepalive + 1, until=until(Timeout)}, 0); true -> terminate(State) end end. -spec error_terminate(cowboyku:http_status(), #state{}) -> ok. error_terminate(Status, State=#state{socket=Socket, transport=Transport, compress=Compress, onresponse=OnResponse}) -> error_terminate(Status, cowboyku_req:new(Socket, Transport, undefined, <<"GET">>, <<>>, <<>>, 'HTTP/1.1', [], <<>>, undefined, <<>>, false, Compress, OnResponse), State). -spec error_terminate(cowboyku:http_status(), cowboyku_req:req(), #state{}) -> ok. error_terminate(Status, Req, State) -> cowboyku_req:maybe_reply(Status, Req), terminate(State). -spec terminate(#state{}) -> ok. terminate(#state{socket=Socket, transport=Transport}) -> Transport:close(Socket), ok.
Erlang
using System; namespace OpenCvSharp { // ReSharper disable once InconsistentNaming #if LANG_JP /// <summary> /// ORB 実装 /// </summary> #else /// <summary> /// Class implementing the ORB (*oriented BRIEF*) keypoint detector and descriptor extractor /// </summary> /// <remarks> /// described in @cite RRKB11 . The algorithm uses FAST in pyramids to detect stable keypoints, /// selects the strongest features using FAST or Harris response, finds their orientation /// using first-order moments and computes the descriptors using BRIEF (where the coordinates /// of random point pairs (or k-tuples) are rotated according to the measured orientation). /// </remarks> #endif // ReSharper disable once InconsistentNaming public class ORB : Feature2D { private Ptr ptrObj; //internal override IntPtr PtrObj => ptrObj.CvPtr; #region Init & Disposal /// <summary> /// /// </summary> protected ORB(IntPtr p) { ptrObj = new Ptr(p); ptr = ptrObj.Get(); } /// <summary> /// /// </summary> /// <param name="nFeatures"></param> /// <param name="scaleFactor"></param> /// <param name="nLevels"></param> /// <param name="edgeThreshold"></param> /// <param name="firstLevel"></param> /// <param name="wtaK"></param> /// <param name="scoreType"></param> /// <param name="patchSize"></param> public static ORB Create( int nFeatures = 500, float scaleFactor = 1.2f, int nLevels = 8, int edgeThreshold = 31, int firstLevel = 0, int wtaK = 2, ORBScore scoreType = ORBScore.Harris, int patchSize = 31) { IntPtr ptr = NativeMethods.features2d_ORB_create( nFeatures, scaleFactor, nLevels, edgeThreshold, firstLevel, wtaK, (int)scoreType, patchSize); return new ORB(ptr); } /// <summary> /// Releases managed resources /// </summary> protected override void DisposeManaged() { ptrObj?.Dispose(); ptrObj = null; base.DisposeManaged(); } #endregion #region Properties /// <summary> /// /// </summary> public int MaxFeatures { get { ThrowIfDisposed(); return NativeMethods.features2d_ORB_getMaxFeatures(ptr); } set { ThrowIfDisposed(); NativeMethods.features2d_ORB_setMaxFeatures(ptr, value); } } /// <summary> /// /// </summary> public double ScaleFactor { get { ThrowIfDisposed(); return NativeMethods.features2d_ORB_getScaleFactor(ptr); } set { ThrowIfDisposed(); NativeMethods.features2d_ORB_setScaleFactor(ptr, value); } } /// <summary> /// /// </summary> public int NLevels { get { ThrowIfDisposed(); return NativeMethods.features2d_ORB_getNLevels(ptr); } set { ThrowIfDisposed(); NativeMethods.features2d_ORB_setNLevels(ptr, value); } } /// <summary> /// /// </summary> public int EdgeThreshold { get { ThrowIfDisposed(); return NativeMethods.features2d_ORB_getEdgeThreshold(ptr); } set { ThrowIfDisposed(); NativeMethods.features2d_ORB_setEdgeThreshold(ptr, value); } } /// <summary> /// /// </summary> public int FirstLevel { get { ThrowIfDisposed(); return NativeMethods.features2d_ORB_getFirstLevel(ptr); } set { ThrowIfDisposed(); NativeMethods.features2d_ORB_setFirstLevel(ptr, value); } } /// <summary> /// /// </summary> // ReSharper disable once InconsistentNaming public int WTA_K { get { ThrowIfDisposed(); return NativeMethods.features2d_ORB_getWTA_K(ptr); } set { ThrowIfDisposed(); NativeMethods.features2d_ORB_setWTA_K(ptr, value); } } /// <summary> /// /// </summary> public int ScoreType { get { ThrowIfDisposed(); return NativeMethods.features2d_ORB_getScoreType(ptr); } set { ThrowIfDisposed(); NativeMethods.features2d_ORB_setScoreType(ptr, value); } } /// <summary> /// /// </summary> public int PatchSize { get { ThrowIfDisposed(); return NativeMethods.features2d_ORB_getPatchSize(ptr); } set { ThrowIfDisposed(); NativeMethods.features2d_ORB_setPatchSize(ptr, value); } } /// <summary> /// /// </summary> public int FastThreshold { get { ThrowIfDisposed(); return NativeMethods.features2d_ORB_getFastThreshold(ptr); } set { ThrowIfDisposed(); NativeMethods.features2d_ORB_setFastThreshold(ptr, value); } } #endregion internal new class Ptr : OpenCvSharp.Ptr { public Ptr(IntPtr ptr) : base(ptr) { } public override IntPtr Get() { return NativeMethods.features2d_Ptr_ORB_get(ptr); } protected override void DisposeUnmanaged() { NativeMethods.features2d_Ptr_ORB_delete(ptr); base.DisposeUnmanaged(); } } } }
C#
/* ===================================================================================== The UQ Toolkit (UQTk) version 3.1.5 Copyright (2024) NTESS https://www.sandia.gov/UQToolkit/ https://github.com/sandialabs/UQTk Copyright 2024 National Technology & Engineering Solutions of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights in this software. This file is part of The UQ Toolkit (UQTk) UQTk is open source software: you can redistribute it and/or modify it under the terms of BSD 3-Clause License UQTk 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 BSD 3 Clause License for more details. You should have received a copy of the BSD 3 Clause License along with UQTk. If not, see https://choosealicense.com/licenses/bsd-3-clause/. Questions? Contact the UQTk Developers at https://github.com/sandialabs/UQTk/discussions Sandia National Laboratories, Livermore, CA, USA ===================================================================================== */ /// \file quad.cpp /// \author K. Sargsyan, C. Safta 2010 - /// \brief Quadrature class #include <math.h> #include <assert.h> #include <cfloat> #include "quad.h" #include "error_handlers.h" #include "combin.h" #include "multiindex.h" #include "gq.h" #include "arrayio.h" #include "arraytools.h" // Constructor given quadrature type, sparsity, dimensionaility, grid parameter (ppd or level), and associated PC parameters, if relevant Quad::Quad(char *grid_type, char *fs_type,int ndim, int param,double alpha, double betta)//Default { // Initialize the dimensionality, grid types and boundaries this->ndim_=ndim; aa_.Resize(ndim,-1.e0); bb_.Resize(ndim,1.e0); this->grid_type_=grid_type; this->fs_type_=fs_type; // Initialize parameters this->alpha_=alpha; this->beta_=betta; this->alphas_.Resize(this->ndim_,alpha); this->betas_.Resize(this->ndim_,betta); this->growth_rules_.Resize(this->ndim_,0); this->grid_types_.Resize(this->ndim_,grid_type); this->param_.Resize(this->ndim_,param); // Set the quadrature level maxlevel_=param; // The rest of initialization this->init(); } // Constructor given quadrature type, sparsity, dimensionaility, grid parameter (ppd or level), and associated PC parameters, if relevant // Overloaded for unisotropy Quad::Quad(Array1D<string>& grid_types, char *fs_type, Array1D<int>& param,Array1D<double>& alphas, Array1D<double>& bettas) { // Initialize the dimensionality, grid types and boundaries this->ndim_=grid_types.Length(); aa_.Resize(this->ndim_,-1.e0); bb_.Resize(this->ndim_,1.e0); this->growth_rules_.Resize(this->ndim_,0); this->grid_types_=grid_types; this->fs_type_=fs_type; // Initialize parameters this->alphas_=alphas; this->betas_=bettas; // Set the quadrature level maxlevel_=param(0); param_=param; // The rest of initialization this->init(); } void Quad::init() { // Hardwired non-verbosity SetVerbosity(0); // Make sure we are not asking for too many quadrature points if (this->fs_type_=="full"){ double prod=1.; for (int i=0;i<this->ndim_;i++) prod *= this->param_(i); if (quadverbose_>0) cout << "Computing " << prod << " quadrature points in " << this->ndim_ << " dimensions" << endl; if (this->ndim_*prod > QD_MAX){ throw Tantrum("Quad::Quad(): The requested number of points is too large"); } } // Sanity check - do not use 0 ppd with full tensor-product if (this->fs_type_=="full"){ if(this->maxlevel_==0) throw Tantrum("Quad::Quad(): 'full' does not make sense with parameter 0."); } // Set the proper growth rules for sparse quadrature else if (this->fs_type_=="sparse"){ if(this->ndim_==1) throw Tantrum("Quad::Quad(): 'sparse' does not make sense in 1D, use 'full' instead."); for (int i=0;i<this->ndim_;i++){ if (this->grid_types_(i)=="CC" or this->grid_types_(i)=="NC") this->growth_rules_(i)=0; else if (this->grid_types_(i)=="LU") this->growth_rules_(i)=0; else if (this->grid_types_(i)=="NCO" or this->grid_types_(i)=="CCO") this->growth_rules_(i)=1; else if (this->grid_types_(i)=="HG") this->growth_rules_(i)=1; else if (this->grid_types_(i)=="JB") this->growth_rules_(i)=0; else if (this->grid_types_(i)=="LG") this->growth_rules_(i)=0; else if (this->grid_types_(i)=="SW") this->growth_rules_(i)=0; else if (this->grid_types_(i)=="pdf") this->growth_rules_(i)=0; else if (this->grid_types_(i)=="GP3") this->growth_rules_(i)=0; else throw Tantrum("Quad::Quad(): Grid type unrecognized! Options are 'CC','CCO','NC','NCO','LU', 'HG', 'JB', 'LG', 'SW', 'pdf' or 'GP3'"); } } else throw Tantrum("Quad::Quad(): Either 'full' or 'sparse' should be specified"); return; } // Set two-sided domain for quadrature void Quad::SetDomain(Array1D<double>& aa, Array1D<double>& bb) { // Dimensionality check if ( (int) aa.XSize() != ndim_ or (int) bb.XSize() != ndim_ ) throw Tantrum("Quad::SetDomain(): Dimension error!"); aa_=aa; bb_=bb; return; } // Set one-sided domain for quadrature void Quad::SetDomain(Array1D<double>& aa) { // Dimensionality check if ( (int) aa.XSize() != ndim_ ) throw Tantrum("Quad::SetDomain(): Dimension error!"); aa_=aa; return; } // Set quadrature rule (i.e. points and weights) void Quad::SetRule(Array2D<double>& q, Array1D<double>& w) { // Set a rule this->SetQdpts(q); this->SetWghts(w); return; } // Get quadrature rule (i.e. points and weights) void Quad::GetRule(Array2D<double>& q, Array1D<double>& w) { // Get the rule this->GetQdpts(q); this->GetWghts(w); return; } // Multiply two rules (tensor product of points and weights) void Quad::MultiplyTwoRules(QuadRule *rule1,QuadRule *rule2,QuadRule *rule_prod) { // Get the sizes int n1=rule1->qdpts.XSize(); int n2=rule2->qdpts.XSize(); int d1=rule1->qdpts.YSize(); int d2=rule2->qdpts.YSize(); // Compute the sizes of the product rule int n12=n1*n2; int d12=d1+d2; // Resize the product rule containers rule_prod->qdpts.Resize(n12,d12,0.e0); rule_prod->wghts.Resize(n12,0.e0); for(int in2=0;in2<n2;in2++){ for(int in1=0;in1<n1;in1++){ // Quadrature points and indices are 'mesh'-ed for(int id1=0;id1<d1;id1++){ rule_prod->qdpts(in1+in2*n1,id1)=rule1->qdpts(in1,id1); } for(int id2=0;id2<d2;id2++){ rule_prod->qdpts(in1+in2*n1,id2+d1)=rule2->qdpts(in2,id2); } // Weights are multiplied rule_prod->wghts(in1+in2*n1)=rule1->wghts(in1)*rule2->wghts(in2); } } return; } // Multiple and array of rules void Quad::MultiplyManyRules(int nrules, QuadRule *rules, QuadRule *rule_prod) { // Working rules QuadRule rule_1d; QuadRule rule_cur; QuadRule rule_prod_h; for(int i=0;i<nrules;i++){ rule_1d=rules[i]; // Recursively multiply all the rules if(i==0) rule_prod_h=rule_1d; else this->MultiplyTwoRules(&rule_cur,&rule_1d,&rule_prod_h); rule_cur=rule_prod_h; } rule_prod->qdpts=rule_prod_h.qdpts; rule_prod->wghts=rule_prod_h.wghts; return; } void Quad::MultiplyManyRules_(int nrules, QuadRule *rules, QuadRule *rule_prod) { // Working rules QuadRule rule_1d; QuadRule rule_cur; QuadRule rule_prod_h; for(int i=0;i<nrules;i++){ rule_1d=rules[i]; // Recursively multiply all the rules if(i==0) rule_prod_h=rule_1d; else this->MultiplyTwoRules(&rule_1d,&rule_cur,&rule_prod_h); rule_cur=rule_prod_h; } rule_prod->qdpts=rule_prod_h.qdpts; rule_prod->wghts=rule_prod_h.wghts; return; } // Subtract two rules void Quad::SubtractTwoRules(QuadRule *rule1,QuadRule *rule2,QuadRule *rule_sum) { for(int i=0;i<(int) rule2->wghts.XSize();i++) rule2->wghts(i) *= -1.; this->AddTwoRules(rule1,rule2,rule_sum); return; } // Add two rules void Quad::AddTwoRules(QuadRule *rule1,QuadRule *rule2,QuadRule *rule_sum) { // Get the sizes int n1=rule1->qdpts.XSize(); int n2=rule2->qdpts.XSize(); int d1=rule1->qdpts.YSize(); int d2=rule2->qdpts.YSize(); // Sanity check if(d1!=d2){ printf("Quad::AddTwoRules(): only rules of same dimensionality can be added to each other! %d %d\n",d1,d2); exit(1); } int d=d1; // The size of the full sum int n12=n1+n2; merge(rule1->qdpts,rule2->qdpts,rule_sum->qdpts); merge(rule1->wghts,rule2->wghts,rule_sum->wghts); return; } /**********************************************************************************/ /**********************************************************************************/ // Creating 1D rules void Quad::create1DRule(string gridtype,Array1D<double>& qdpts,Array1D<double>& wghts,int ngr, double a, double b) { if (gridtype=="CC"){ this->create1DRule_CC(qdpts,wghts,ngr,a,b); } else if (gridtype=="NC"){ this->create1DRule_NC(qdpts,wghts,ngr,a,b); } else if (gridtype=="NCO"){ this->create1DRule_NCO(qdpts,wghts,ngr,a,b); } else if (gridtype=="CCO"){ this->create1DRule_CCO(qdpts,wghts,ngr,a,b); } else if (gridtype=="LU" or gridtype=="LU_N"){ this->create1DRule_LU(qdpts,wghts,ngr,a,b); } else if (gridtype=="HG"){ this->create1DRule_HG(qdpts,wghts,ngr); } else if (gridtype=="JB"){ this->create1DRule_JB(qdpts,wghts,ngr,a,b); } else if (gridtype=="LG"){ this->create1DRule_LG(qdpts,wghts,ngr); } else if (gridtype=="SW"){ this->create1DRule_SW(qdpts,wghts,ngr); } else if (gridtype=="pdf"){ this->create1DRule_pdf(qdpts,wghts,ngr,a,b); } else if (gridtype=="GP3"){ this->create1DRule_GP3(qdpts,wghts,ngr,a,b); } else throw Tantrum("Quad::create1DRule(): Grid type unrecognized! Options are 'CC','CCO','NC','NCO','LU', 'HG', 'JB', 'LG', 'SW', 'pdf' or 'GP3' "); return; } /**********************************************************************************/ /**********************************************************************************/ // Legendre-Uniform void Quad::create1DRule_LU(Array1D<double>& qdpts,Array1D<double>& wghts, int ngr, double a, double b) { qdpts.Resize(ngr,0.e0); wghts.Resize(ngr,0.e0); // Work arrays Array1D<double> endpts(2,0.e0); // real array of length two with zeroed values, needed to pass to gaussqC Array1D<double> bwork(ngr,0.e0); Array1D<double> qdpts_1d(ngr,0.e0); int kind=1; double alpha=0.0,beta=0.0; gq( kind, alpha, beta, qdpts_1d, wghts ); // Rescale and index for(int i=0; i<ngr;i++){ qdpts(i)=a+(b-a)*(qdpts_1d(i)+1.)/2.; wghts(i) *= (b-a)/4.; //since the integral is with respect to pdf=1/2 } return; } /**********************************************************************************/ // Gauss-Hermite void Quad::create1DRule_HG(Array1D<double>& qdpts,Array1D<double>& wghts, int ngr) { qdpts.Resize(ngr,0.e0); wghts.Resize(ngr,0.e0); // Work arrays Array1D<double> endpts(2,0.e0); // real array of length two with zeroed values, needed to pass to gaussqC Array1D<double> bwork(ngr,0.e0); Array1D<double> qdpts_1d(ngr,0.e0); int kind=4; double alpha=0.0,beta=0.0; const double pi = 4.e0*atan(1.e0); double spi = sqrt(pi); double fac = sqrt(2.0); gq( kind, alpha, beta, qdpts_1d, wghts ); // Rescale and index for(int i=0; i<ngr;i++){ qdpts(i)=qdpts_1d(i)*fac; wghts(i) /= spi; } return; } /**********************************************************************************/ // Newton-Cotes (i.e., uniform spacing) void Quad::create1DRule_NC(Array1D<double>& qdpts,Array1D<double>& wghts, int ngr, double a, double b) { qdpts.Resize(ngr,0.e0); wghts.Resize(ngr,0.e0); if (ngr==1){ qdpts(0)=0.0; wghts(0)=2.0; } else{ for (int i=0;i<ngr;i++) qdpts(i) = -1.+2.*double(i)/ double(ngr-1.); Array1D<double> exact(ngr,0.e0); for (int i=0;i<ngr;i=i+2) exact(i)=2./(i+1.); vandermonde_gq(qdpts,wghts,exact); } // Rescale and index for (int i=0;i<ngr;i++){ qdpts(i) = (b+a)/2.+ qdpts(i)* (b-a)/2.; wghts(i) = wghts(i) *(b-a)/4.; //since the integral is with respect to pdf=1/2 } return; } /**********************************************************************************/ // Newton-Cotes open (i.e. no boundary points) void Quad::create1DRule_NCO(Array1D<double>& qdpts,Array1D<double>& wghts,int ngr, double a, double b) { qdpts.Resize(ngr,0.e0); wghts.Resize(ngr,0.e0); for (int i=0;i<ngr;i++) qdpts(i) = -1.+2.*(i+1.)/ double(ngr+1.); Array1D<double> exact(ngr,0.e0); for (int i=0;i<ngr;i=i+2) exact(i)=2./(i+1.); vandermonde_gq(qdpts,wghts,exact); // Rescale and index for (int i=0;i<ngr;i++){ qdpts(i) = (b+a)/2.+ qdpts(i)* (b-a)/2.; wghts(i) = wghts(i) *(b-a)/4.; //since the integral is with respect to pdf=1/2 } return; } /**********************************************************************************/ // Clenshaw-Curtis (useful for nestedness) void Quad::create1DRule_CC(Array1D<double>& qdpts,Array1D<double>& wghts, int ngr, double a, double b) { qdpts.Resize(ngr,0.e0); wghts.Resize(ngr,0.e0); if (ngr==1){ qdpts(0)=0.0; wghts(0)=2.0; } else { double pi=4.*atan(1.); double theta,f; for (int i=0;i<ngr;i++) qdpts(i) = cos( (double) (ngr-1-i) * pi / (double) (ngr-1) ); for (int i=0;i<ngr;i++){ theta = (double) i * pi / (double) (ngr-1); wghts(i) = 1.0; for (int j=1;j<=( ngr - 1 ) / 2; j++ ){ if ( 2 * j == ( ngr - 1 ) ) f = 1.0; else f = 2.0; wghts(i)-= f*cos ( 2.0 * ( double ) j * theta ) / ( double ) ( 4 * j * j - 1 ); } } wghts(0) /= (double) ( ngr - 1 ); for ( int i = 1; i < ngr - 1; i++ ) wghts(i) *= 2.0 / ( double ) ( ngr - 1 ); wghts(ngr-1) *= 1.0 / ( double ) ( ngr - 1 ); } // Rescale and index for (int i=0;i<ngr;i++){ qdpts(i) = (b+a)/2.+ qdpts(i)* (b-a)/2.; wghts(i) = wghts(i) *(b-a)/4.; //since the integral is with respect to pdf=1/2 } return; } /**********************************************************************************/ // Clenshaw-Curtis open (i.e. no boundary points) void Quad::create1DRule_CCO(Array1D<double>& qdpts,Array1D<double>& wghts, int ngr, double a, double b) { qdpts.Resize(ngr,0.e0); wghts.Resize(ngr,0.e0); double pi=4.*atan(1.); double theta,f; for (int i=0;i<ngr;i++) qdpts(i) = cos( (double) (ngr-i) * pi / (double) (ngr+1) ); for (int i=0;i<ngr;i++){ theta = (double) (ngr-i) * pi / (double) (ngr+1); wghts(i) = 1.0; for (int j=1;j<=( ngr - 1 ) / 2; j++ ){ wghts(i)-= 2.0*cos ( 2.0 * ( double ) j * theta ) / ( double ) ( 4 * j * j - 1 ); } if(ngr%2==1) f=ngr; else f=ngr-1; wghts(i)-=cos((f+1.)*theta) / f; } for ( int i = 0; i < ngr; i++ ) wghts(i) *= 2.0 / ( double ) ( ngr + 1 ); // Rescale and index for (int i=0;i<ngr;i++){ qdpts(i) = (b+a)/2.+ qdpts(i)* (b-a)/2.; wghts(i) = wghts(i) *(b-a)/4.; //since the integral is with respect to pdf=1/2 } return; } /**********************************************************************************/ // Beta-Jacobi void Quad::create1DRule_JB(Array1D<double>& qdpts,Array1D<double>& wghts, int ngr, double a, double b) { qdpts.Resize(ngr,0.e0); wghts.Resize(ngr,0.e0); // The norm double mu0= pow(2.,alpha_+beta_+1.)*beta(alpha_+1.,beta_+1.); gq (5, alpha_, beta_, qdpts, wghts ) ; // Rescale and index for(int i=0; i<ngr;i++){ qdpts(i)=a+(b-a)*(qdpts(i)+1.)/2.; wghts(i) *= (b-a)/(2.*mu0); } return; } /**********************************************************************************/ // Gamma-Laguerre (positive half-line) void Quad::create1DRule_LG(Array1D<double>& qdpts,Array1D<double>& wghts, int ngr) { qdpts.Resize(ngr,0.e0); wghts.Resize(ngr,0.e0); gq (6, alpha_, 0.0, qdpts, wghts ) ; // Indexing for(int i=0; i<ngr;i++){ wghts(i) /= exp(lgamma(alpha_+1)); } return; } /**********************************************************************************/ // Stieltjes-Wishart (lognormal pdf) void Quad::create1DRule_SW(Array1D<double>& qdpts,Array1D<double>& wghts, int ngr) { assert(alpha_>0.0); qdpts.Resize(ngr,0.e0); wghts.Resize(ngr,0.e0); // Work arrays Array1D<double> al(ngr,0.e0); Array1D<double> be(ngr, 0.e0); double ee=exp(beta_*beta_/2.); double eesq = ee*ee ; for(int i=0; i<ngr;i++){ al(i)=exp(alpha_)*pow(ee,2.e0*i-1.e0)*((eesq+1.0)*pow(eesq,i)-1.e0); be(i)=exp(2.e0*alpha_)*pow(eesq,3.e0*i-2.e0)*(pow(ee,2.e0*(double)(i))-1.e0); } // The norm double mu0=1.; // Computes the quadrature given the recursion coefficients gq_gen(al,be,mu0,qdpts, wghts) ; return; } /**********************************************************************************/ // Custom pdf given by recurrence relation coefficients in a hardwired file void Quad::create1DRule_pdf(Array1D<double>& qdpts,Array1D<double>& wghts, int ngr, double a, double b) { qdpts.Resize(ngr,0.e0); wghts.Resize(ngr,0.e0); // Work arrays Array1D<double> al(ngr,0.e0); Array1D<double> be(ngr, 0.e0); // Read the recursion coefficients from the data file Array2D<double> albe; read_datafileVS(albe,"ab.dat"); if ((int)albe.XSize()<ngr) { printf("Quad::create1DRule_pdf() : ngr=%d, rows(ab.dat)=%d !\n",ngr,(int) albe.XSize()) ; throw Tantrum("The input coefficient file 'ab.dat' has fewer rows than needed"); } for(int i=0; i<ngr;i++){ al(i)=albe(i,0); be(i)=albe(i,1); } // \todo This is problem specific!!! double mu0=1.0; //0.5+0.5*erf(3.2/sqrt(2.)); // Computes the quadrature given the recursion coefficients gq_gen(al,be,mu0,qdpts, wghts) ; return; } /**********************************************************************************/ // Gauss-Patterson void Quad::create1DRule_GP3(Array1D<double>& qdpts,Array1D<double>& wghts, int ngr, double a, double b) { int nqp[7]={1,3,7,15,31,63,127}; if ((ngr<1) || (ngr>7)) { printf("Quad::create1DRule_GP3() : ngr=%d !\n",ngr) ; throw Tantrum("The above Gauss-Patterson rule is not available!"); } qdpts.Resize(nqp[ngr-1],0.e0); wghts.Resize(nqp[ngr-1],0.e0); /* Read the quadrature points and weights from data file */ stringstream fname; fname << "gp3rules/gp3_o" << ngr << "_p.dat"; Array2D<double> din; read_datafileVS(din,fname.str().c_str()); if ((int)din.XSize()!=nqp[ngr]) { printf("Quad::create1DRule_GP3() : ngr=%d, nqp=%d vs %d !\n",ngr,(int) din.XSize(), nqp[ngr]) ; throw Tantrum("The the number of quadrature points does not match the expected value"); } for(int i=0; i<(int)din.XSize();i++) qdpts(i) = din(i,0); fname.str("gp3rules/gp3_o"); fname << ngr << "_w.dat"; read_datafileVS(din,fname.str().c_str()); if ((int)din.XSize()!=nqp[ngr]) { printf("Quad::create1DRule_GP3() : ngr=%d, nqp=%d vs %d !\n",ngr,(int) din.XSize(), nqp[ngr]) ; throw Tantrum("The the number of quadrature weights does not match the expected value"); } for(int i=0; i<(int)din.XSize();i++) wghts(i) = din(i,0); // Rescale for(int i=0; i<ngr;i++){ qdpts(i) = a+(b-a)*(qdpts(i)+1.)/2.; wghts(i) *= (b-a)/2.0; } return; } /**********************************************************************************/ /**********************************************************************************/ // Set the rule (essentially main part of the class) void Quad::SetRule() { // Either the full product of the 1D rules if (this->fs_type_=="full"){ QuadRule rule_1d; QuadRule rule_cur; QuadRule rule_prod; for(int id=0;id<this->ndim_;id++){ Array1D<double> qdpts_1d; this->create1DRule(this->grid_types_(id),qdpts_1d,rule_1d.wghts,param_(id),aa_(id),bb_(id)); array1Dto2D(qdpts_1d,rule_1d.qdpts); if(id==0) rule_prod=rule_1d; else this->MultiplyTwoRules(&rule_cur,&rule_1d,&rule_prod); rule_cur=rule_prod; } rule_=rule_prod; } //...or multiply rules in a specific way and combine them to obtain sparse rule else if (this->fs_type_=="sparse"){ this->SetLevel(-1); npts_all.Resize(maxlevel_+1, 2); npts_1_all.Resize(maxlevel_+1, 2); for(int il=0;il<=maxlevel_;il++){ if (il==0) npts_all(il,0)=1; else npts_all(il,0)= (int) pow(2,il)+1; npts_all(il,1)= (int) pow(2,il+1)-1; if (il<=1) npts_1_all(il,0)=il; else npts_1_all(il,0)= (int) pow(2,il-1)+1; npts_1_all(il,1)= (int) pow(2,il)-1; } Array1D<double> qq; qr_all.Resize(maxlevel_+1, this->ndim_); for(int il=0;il<=maxlevel_;il++){ for(int id=0;id<this->ndim_;id++){ QuadRule r_temp; this->create1DRule(this->grid_types_(id),qq,r_temp.wghts,npts_all(il, this->growth_rules_(id)),aa_(id),bb_(id)); array1Dto2D(qq,r_temp.qdpts); qr_all(il,id)=r_temp; } } qr_1_all.Resize(maxlevel_+1, this->ndim_); for(int il=0;il<=maxlevel_;il++){ for(int id=0;id<this->ndim_;id++){ if (npts_1_all(il, this->growth_rules_(id))>0){ QuadRule r_temp; this->create1DRule(this->grid_types_(id),qq,r_temp.wghts,npts_1_all(il, this->growth_rules_(id)),aa_(id),bb_(id)); array1Dto2D(qq,r_temp.qdpts); qr_1_all(il,id)=r_temp; } } } // Incremental buildup of levels for(int il=0;il<=maxlevel_;il++){ if (quadverbose_ > 0) cout << "Level " << il << " / " << maxlevel_ << endl; this->nextLevel(); } } else throw Tantrum("Quad::SetRule(): unknown rule type."); return; } // Compute the next-level points void Quad::nextLevel() { this->SetLevel(nlevel_+1); QuadRule rule_level; QuadRule rule_cur; QuadRule rule_total; Array2D<int> multiIndexLevel; this->getMultiIndexLevel(multiIndexLevel,nlevel_,ndim_); int nMultiIndicesLevel=multiIndexLevel.XSize(); Array2D<int> multiIndexLevel_npts(nMultiIndicesLevel,ndim_,0); for(int j=0;j<nMultiIndicesLevel;j++){ if (quadverbose_==2) cout << j << " / " << nMultiIndicesLevel << endl; QuadRule* rules; QuadRule* rules_1; QuadRule* srules; rules = new QuadRule[ndim_]; rules_1 = new QuadRule[ndim_]; srules = new QuadRule[ndim_]; for(int id=0;id<ndim_;id++){ // multiIndexLevel(j,id)=multiIndex(j+levelCounter_start,id); int npts=npts_all(multiIndexLevel(j,id), this->growth_rules_(id)); int npts_1=npts_1_all(multiIndexLevel(j,id), this->growth_rules_(id)); //cout << npts << " " << npts_1 << endl; Array1D<double> qdpts_1d; Array1D<int> indices_1d; rules[id]=qr_all(multiIndexLevel(j,id), id); // this->create1DRule(this->grid_types_(id),qdpts_1d,rules[id].wghts,npts,aa_(id),bb_(id)); // array1Dto2D(qdpts_1d,rules[id].qdpts); if(npts_1>0){ rules_1[id]=qr_1_all(multiIndexLevel(j,id), id); this->SubtractTwoRules(&rules[id],&rules_1[id], &srules[id]); } else srules[id]=rules[id]; }//end of id loop QuadRule rule_temp; this->MultiplyManyRules(ndim_,srules,&rule_temp); if(j==0) rule_level=rule_temp; else this->AddTwoRules(&rule_cur,&rule_temp,&rule_level); // if (rule_level.wghts.XSize()>1.e+6) // this->compressRule(&rule_level); rule_cur=rule_level; delete []rules; delete []rules_1; delete []srules; } if (nlevel_==0) rule_total=rule_level; else this->AddTwoRules(&rule_,&rule_level,&rule_total); rule_=rule_total; this->compressRule(&rule_); return; } // Auxilliary function: get the level of the multi-index void Quad::getMultiIndexLevel(Array2D<int>& multiIndexLevel, int level,int ndim) { int iup=0; int nup_level=choose(ndim+level-1,level); multiIndexLevel.Resize(nup_level,ndim,0); if (ndim==1) multiIndexLevel(0,0)=level; else{ for (int first = level; first >= 0; first--){ Array2D<int> theRest; getMultiIndexLevel(theRest,level-first,ndim-1); for(int j=0;j<(int)theRest.XSize();j++){ multiIndexLevel(iup,0)=first; for(int id=1;id<ndim;id++){ multiIndexLevel(iup,id)=theRest(j,id-1); } iup++; } } } return; } // Compress the rule to remove repeated points void Quad::compressRule(QuadRule *rule) { int nqdpts = rule->qdpts.XSize(); int ndim = rule->qdpts.YSize(); for(int iq=0;iq<nqdpts;iq++) for(int id=0;id<ndim;id++) if(fabs(rule->qdpts(iq,id))<1.e-15) rule->qdpts(iq,id)=0.e0; Array1D<int> ind; for(int i=0;i<ndim;i++) ind.PushBack(i); Array2D<double> qw = rule->qdpts; paddMatCol(qw,rule->wghts); if (quadverbose_==1) cout << "Sorting quadrature of size " << qw.XSize() << endl; quicksort3(qw,0,qw.XSize()-1); Array1D<double> qw_prev,q_prev; getRow(qw,0,qw_prev); subVector(qw_prev,ind,q_prev); Array2D<double> qwt=Trans(qw); Array1D<int> choose_ind(1,0); int iq_prev=0; for(int iq=1; iq<nqdpts; iq++){ if ( quadverbose_ == 1 ) if ( iq%1000000 == 0 ) cout << "Compressing quadrature : "<< iq << " / " << nqdpts << endl; Array1D<double> qw_cur,q_cur; getCol(qwt,iq,qw_cur); subVector(qw_cur,ind,q_cur); if(is_equal(q_cur,q_prev)) qwt(ndim,iq_prev)+=qwt(ndim,iq); else{ choose_ind.PushBack(iq); q_prev = q_cur; iq_prev=iq; } } qw=Trans(qwt); Array2D<double> tmp; subMatrix_row(qw,choose_ind,tmp); subMatrix_col(tmp,ind,rule->qdpts); getCol(tmp,ndim,rule->wghts); if (quadverbose_==1) cout << "Quadrature size " << choose_ind.XSize() << " points" << endl; return; }
C++
% Default to the notebook output style % Inherit from the specified cell style. \documentclass{article} \usepackage{graphicx} % Used to insert images \usepackage{adjustbox} % Used to constrain images to a maximum size \usepackage{color} % Allow colors to be defined \usepackage{enumerate} % Needed for markdown enumerations to work \usepackage{geometry} % Used to adjust the document margins \usepackage{amsmath} % Equations \usepackage{amssymb} % Equations \usepackage{eurosym} % defines \euro \usepackage[mathletters]{ucs} % Extended unicode (utf-8) support \usepackage[utf8x]{inputenc} % Allow utf-8 characters in the tex document \usepackage{fancyvrb} % verbatim replacement that allows latex \usepackage{grffile} % extends the file name processing of package graphics % to support a larger range % The hyperref package gives us a pdf with properly built % internal navigation ('pdf bookmarks' for the table of contents, % internal cross-reference links, web links for URLs, etc.) \usepackage{hyperref} \usepackage{longtable} % longtable support required by pandoc >1.10 \usepackage{booktabs} % table support for pandoc > 1.12.2 \definecolor{orange}{cmyk}{0,0.4,0.8,0.2} \definecolor{darkorange}{rgb}{.71,0.21,0.01} \definecolor{darkgreen}{rgb}{.12,.54,.11} \definecolor{myteal}{rgb}{.26, .44, .56} \definecolor{gray}{gray}{0.45} \definecolor{lightgray}{gray}{.95} \definecolor{mediumgray}{gray}{.8} \definecolor{inputbackground}{rgb}{.95, .95, .85} \definecolor{outputbackground}{rgb}{.95, .95, .95} \definecolor{traceback}{rgb}{1, .95, .95} % ansi colors \definecolor{red}{rgb}{.6,0,0} \definecolor{green}{rgb}{0,.65,0} \definecolor{brown}{rgb}{0.6,0.6,0} \definecolor{blue}{rgb}{0,.145,.698} \definecolor{purple}{rgb}{.698,.145,.698} \definecolor{cyan}{rgb}{0,.698,.698} \definecolor{lightgray}{gray}{0.5} % bright ansi colors \definecolor{darkgray}{gray}{0.25} \definecolor{lightred}{rgb}{1.0,0.39,0.28} \definecolor{lightgreen}{rgb}{0.48,0.99,0.0} \definecolor{lightblue}{rgb}{0.53,0.81,0.92} \definecolor{lightpurple}{rgb}{0.87,0.63,0.87} \definecolor{lightcyan}{rgb}{0.5,1.0,0.83} % commands and environments needed by pandoc snippets % extracted from the output of `pandoc -s` \providecommand{\tightlist}{% \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}} \DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}} % Add ',fontsize=\small' for more characters per line \newenvironment{Shaded}{}{} \newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{\textbf{{#1}}}} \newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.56,0.13,0.00}{{#1}}} \newcommand{\DecValTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{{#1}}} \newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{{#1}}} \newcommand{\FloatTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{{#1}}} \newcommand{\CharTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{{#1}}} \newcommand{\StringTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{{#1}}} \newcommand{\CommentTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textit{{#1}}}} \newcommand{\OtherTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{{#1}}} \newcommand{\AlertTok}[1]{\textcolor[rgb]{1.00,0.00,0.00}{\textbf{{#1}}}} \newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.02,0.16,0.49}{{#1}}} \newcommand{\RegionMarkerTok}[1]{{#1}} \newcommand{\ErrorTok}[1]{\textcolor[rgb]{1.00,0.00,0.00}{\textbf{{#1}}}} \newcommand{\NormalTok}[1]{{#1}} % Define a nice break command that doesn't care if a line doesn't already % exist. \def\br{\hspace*{\fill} \\* } % Math Jax compatability definitions \def\gt{>} \def\lt{<} % Document parameters \title{RoberPrecisionTest} % Pygments definitions \makeatletter \def\PY@reset{\let\PY@it=\relax \let\PY@bf=\relax% \let\PY@ul=\relax \let\PY@tc=\relax% \let\PY@bc=\relax \let\PY@ff=\relax} \def\PY@tok#1{\csname PY@tok@#1\endcsname} \def\PY@toks#1+{\ifx\relax#1\empty\else% \PY@tok{#1}\expandafter\PY@toks\fi} \def\PY@do#1{\PY@bc{\PY@tc{\PY@ul{% \PY@it{\PY@bf{\PY@ff{#1}}}}}}} \def\PY#1#2{\PY@reset\PY@toks#1+\relax+\PY@do{#2}} \expandafter\def\csname PY@tok@vc\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}} \expandafter\def\csname PY@tok@sh\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}} \expandafter\def\csname PY@tok@gh\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.00,0.50}{##1}}} \expandafter\def\csname PY@tok@gu\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.50,0.00,0.50}{##1}}} \expandafter\def\csname PY@tok@gt\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.27,0.87}{##1}}} \expandafter\def\csname PY@tok@kp\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} \expandafter\def\csname PY@tok@ss\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}} \expandafter\def\csname PY@tok@go\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.53,0.53,0.53}{##1}}} \expandafter\def\csname PY@tok@kt\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.69,0.00,0.25}{##1}}} \expandafter\def\csname PY@tok@gs\endcsname{\let\PY@bf=\textbf} \expandafter\def\csname PY@tok@cm\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.25,0.50,0.50}{##1}}} \expandafter\def\csname PY@tok@nv\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}} \expandafter\def\csname PY@tok@na\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.49,0.56,0.16}{##1}}} \expandafter\def\csname PY@tok@nd\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.67,0.13,1.00}{##1}}} \expandafter\def\csname PY@tok@sx\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} \expandafter\def\csname PY@tok@o\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}} \expandafter\def\csname PY@tok@c\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.25,0.50,0.50}{##1}}} \expandafter\def\csname PY@tok@c1\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.25,0.50,0.50}{##1}}} \expandafter\def\csname PY@tok@m\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}} \expandafter\def\csname PY@tok@gi\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.63,0.00}{##1}}} \expandafter\def\csname PY@tok@kc\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} \expandafter\def\csname PY@tok@err\endcsname{\def\PY@bc##1{\setlength{\fboxsep}{0pt}\fcolorbox[rgb]{1.00,0.00,0.00}{1,1,1}{\strut ##1}}} \expandafter\def\csname PY@tok@cp\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.74,0.48,0.00}{##1}}} \expandafter\def\csname PY@tok@ow\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.67,0.13,1.00}{##1}}} \expandafter\def\csname PY@tok@si\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.73,0.40,0.53}{##1}}} \expandafter\def\csname PY@tok@k\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} \expandafter\def\csname PY@tok@nn\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}} \expandafter\def\csname PY@tok@sr\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.40,0.53}{##1}}} \expandafter\def\csname PY@tok@s2\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}} \expandafter\def\csname PY@tok@nb\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} \expandafter\def\csname PY@tok@cs\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.25,0.50,0.50}{##1}}} \expandafter\def\csname PY@tok@mi\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}} \expandafter\def\csname PY@tok@ne\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.82,0.25,0.23}{##1}}} \expandafter\def\csname PY@tok@gr\endcsname{\def\PY@tc##1{\textcolor[rgb]{1.00,0.00,0.00}{##1}}} \expandafter\def\csname PY@tok@mo\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}} \expandafter\def\csname PY@tok@w\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.73,0.73}{##1}}} \expandafter\def\csname PY@tok@kr\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} \expandafter\def\csname PY@tok@kd\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} \expandafter\def\csname PY@tok@se\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.73,0.40,0.13}{##1}}} \expandafter\def\csname PY@tok@mf\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}} \expandafter\def\csname PY@tok@nt\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} \expandafter\def\csname PY@tok@nl\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.63,0.63,0.00}{##1}}} \expandafter\def\csname PY@tok@s\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}} \expandafter\def\csname PY@tok@vg\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}} \expandafter\def\csname PY@tok@kn\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} \expandafter\def\csname PY@tok@no\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.53,0.00,0.00}{##1}}} \expandafter\def\csname PY@tok@sd\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}} \expandafter\def\csname PY@tok@ni\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.60,0.60,0.60}{##1}}} \expandafter\def\csname PY@tok@s1\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}} \expandafter\def\csname PY@tok@sb\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}} \expandafter\def\csname PY@tok@nc\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}} \expandafter\def\csname PY@tok@gp\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.00,0.50}{##1}}} \expandafter\def\csname PY@tok@vi\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}} \expandafter\def\csname PY@tok@mh\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}} \expandafter\def\csname PY@tok@mb\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}} \expandafter\def\csname PY@tok@bp\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}} \expandafter\def\csname PY@tok@ge\endcsname{\let\PY@it=\textit} \expandafter\def\csname PY@tok@gd\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.63,0.00,0.00}{##1}}} \expandafter\def\csname PY@tok@nf\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}} \expandafter\def\csname PY@tok@il\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}} \expandafter\def\csname PY@tok@sc\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}} \def\PYZbs{\char`\\} \def\PYZus{\char`\_} \def\PYZob{\char`\{} \def\PYZcb{\char`\}} \def\PYZca{\char`\^} \def\PYZam{\char`\&} \def\PYZlt{\char`\<} \def\PYZgt{\char`\>} \def\PYZsh{\char`\#} \def\PYZpc{\char`\%} \def\PYZdl{\char`\$} \def\PYZhy{\char`\-} \def\PYZsq{\char`\'} \def\PYZdq{\char`\"} \def\PYZti{\char`\~} % for compatibility with earlier versions \def\PYZat{@} \def\PYZlb{[} \def\PYZrb{]} \makeatother % Exact colors from NB \definecolor{incolor}{rgb}{0.0, 0.0, 0.5} \definecolor{outcolor}{rgb}{0.545, 0.0, 0.0} % Prevent overflowing lines due to hard-to-break entities \sloppy % Setup hyperref package \hypersetup{ breaklinks=true, % so long urls are correctly broken across lines colorlinks=true, urlcolor=blue, linkcolor=darkorange, citecolor=darkgreen, } % Slightly bigger margins than the latex defaults \geometry{verbose,tmargin=1in,bmargin=1in,lmargin=1in,rmargin=1in} \begin{document} \begin{Verbatim}[commandchars=\\\{\}] \PY{c}{\PYZsh{} Check if all the packages are installed or not} \PY{n}{cond} \PY{o}{=} \PY{l+s}{\PYZdq{}}\PY{l+s}{Gadfly}\PY{l+s}{\PYZdq{}} \PY{k}{in} \PY{n}{keys}\PY{p}{(}\PY{n}{Pkg}\PY{o}{.}\PY{n}{installed}\PY{p}{(}\PY{p}{)}\PY{p}{)} \PY{o}{\PYZam{}\PYZam{}} \PY{l+s}{\PYZdq{}}\PY{l+s}{Colors}\PY{l+s}{\PYZdq{}} \PY{k}{in} \PY{n}{keys}\PY{p}{(}\PY{n}{Pkg}\PY{o}{.}\PY{n}{installed}\PY{p}{(}\PY{p}{)}\PY{p}{)} \PY{o}{\PYZam{}\PYZam{}} \PY{l+s}{\PYZdq{}}\PY{l+s}{ODEInterface}\PY{l+s}{\PYZdq{}} \PY{k}{in} \PY{n}{keys}\PY{p}{(}\PY{n}{Pkg}\PY{o}{.}\PY{n}{installed}\PY{p}{(}\PY{p}{)}\PY{p}{)} \PY{o}{\PYZam{}\PYZam{}} \PY{l+s}{\PYZdq{}}\PY{l+s}{ForwardDiff}\PY{l+s}{\PYZdq{}} \PY{k}{in} \PY{n}{keys}\PY{p}{(}\PY{n}{Pkg}\PY{o}{.}\PY{n}{installed}\PY{p}{(}\PY{p}{)}\PY{p}{)}\PY{p}{;} \PY{p}{@}\PY{n+nb}{assert} \PY{n}{cond} \PY{l+s}{\PYZdq{}}\PY{l+s}{Please check if the following package(s) are installed:}\PY{l+s+se}{\PYZbs{}} \PY{l+s}{ Gadfly}\PY{l+s+se}{\PYZbs{}} \PY{l+s}{ Colors}\PY{l+s+se}{\PYZbs{}} \PY{l+s}{ ODEInterface}\PY{l+s+se}{\PYZbs{}} \PY{l+s}{ ForwardDiff}\PY{l+s}{\PYZdq{}} \PY{c}{\PYZsh{} Load all the required packages} \PY{k}{using} \PY{n}{Gadfly} \PY{k}{using} \PY{n}{Colors} \PY{k}{using} \PY{n}{ODEInterface} \PY{k}{using} \PY{n}{ForwardDiff} \PY{p}{@}\PY{n}{ODEInterface}\PY{o}{.}\PY{n}{import\PYZus{}huge} \PY{n}{loadODESolvers}\PY{p}{(}\PY{p}{)}\PY{p}{;} \end{Verbatim} \begin{Verbatim}[commandchars=\\\{\}] \PY{c}{\PYZsh{} Define the right\PYZhy{}hand function for Automatic Differentiation} \PY{k}{function}\PY{n+nf}{ }\PY{n+nf}{roberAD}\PY{p}{(}\PY{n}{x}\PY{p}{)} \PY{k}{return} \PY{p}{[}\PY{o}{\PYZhy{}}\PY{l+m+mf}{0.04}\PY{o}{*}\PY{n}{x}\PY{p}{[}\PY{l+m+mi}{1}\PY{p}{]}\PY{o}{+}\PY{l+m+mf}{1e4}\PY{o}{*}\PY{n}{x}\PY{p}{[}\PY{l+m+mi}{2}\PY{p}{]}\PY{o}{*}\PY{n}{x}\PY{p}{[}\PY{l+m+mi}{3}\PY{p}{]}\PY{p}{,} \PY{l+m+mf}{0.04}\PY{o}{*}\PY{n}{x}\PY{p}{[}\PY{l+m+mi}{1}\PY{p}{]}\PY{o}{\PYZhy{}}\PY{l+m+mf}{1e4}\PY{o}{*}\PY{n}{x}\PY{p}{[}\PY{l+m+mi}{2}\PY{p}{]}\PY{o}{*}\PY{n}{x}\PY{p}{[}\PY{l+m+mi}{3}\PY{p}{]}\PY{o}{\PYZhy{}}\PY{l+m+mf}{3e7}\PY{o}{*}\PY{p}{(}\PY{n}{x}\PY{p}{[}\PY{l+m+mi}{2}\PY{p}{]}\PY{p}{)}\PY{o}{\PYZca{}}\PY{l+m+mi}{2}\PY{p}{,} \PY{l+m+mi}{3}\PY{o}{*}\PY{l+m+mi}{10}\PY{o}{\PYZca{}}\PY{l+m+mi}{7}\PY{o}{*}\PY{p}{(}\PY{n}{x}\PY{p}{[}\PY{l+m+mi}{2}\PY{p}{]}\PY{p}{)}\PY{o}{\PYZca{}}\PY{l+m+mi}{2}\PY{p}{]} \PY{k}{end} \PY{c}{\PYZsh{} Define the system for the solver} \PY{k}{function}\PY{n+nf}{ }\PY{n+nf}{rober}\PY{p}{(}\PY{n}{t}\PY{p}{,}\PY{n}{x}\PY{p}{,}\PY{n}{dx}\PY{p}{)} \PY{n}{dx}\PY{p}{[}\PY{l+m+mi}{1}\PY{p}{]} \PY{o}{=} \PY{o}{\PYZhy{}}\PY{l+m+mf}{0.04}\PY{o}{*}\PY{n}{x}\PY{p}{[}\PY{l+m+mi}{1}\PY{p}{]}\PY{o}{+}\PY{l+m+mf}{1e4}\PY{o}{*}\PY{n}{x}\PY{p}{[}\PY{l+m+mi}{2}\PY{p}{]}\PY{o}{*}\PY{n}{x}\PY{p}{[}\PY{l+m+mi}{3}\PY{p}{]}\PY{p}{;} \PY{n}{dx}\PY{p}{[}\PY{l+m+mi}{2}\PY{p}{]} \PY{o}{=} \PY{l+m+mf}{0.04}\PY{o}{*}\PY{n}{x}\PY{p}{[}\PY{l+m+mi}{1}\PY{p}{]}\PY{o}{\PYZhy{}}\PY{l+m+mf}{1e4}\PY{o}{*}\PY{n}{x}\PY{p}{[}\PY{l+m+mi}{2}\PY{p}{]}\PY{o}{*}\PY{n}{x}\PY{p}{[}\PY{l+m+mi}{3}\PY{p}{]}\PY{o}{\PYZhy{}}\PY{l+m+mf}{3e7}\PY{o}{*}\PY{p}{(}\PY{n}{x}\PY{p}{[}\PY{l+m+mi}{2}\PY{p}{]}\PY{p}{)}\PY{o}{\PYZca{}}\PY{l+m+mi}{2}\PY{p}{;} \PY{n}{dx}\PY{p}{[}\PY{l+m+mi}{3}\PY{p}{]} \PY{o}{=} \PY{l+m+mf}{3e7}\PY{o}{*}\PY{p}{(}\PY{n}{x}\PY{p}{[}\PY{l+m+mi}{2}\PY{p}{]}\PY{p}{)}\PY{o}{\PYZca{}}\PY{l+m+mi}{2}\PY{p}{;} \PY{k}{return} \PY{n}{nothing} \PY{k}{end} \PY{c}{\PYZsh{} Automatic Differentiation for a more general problem} \PY{k}{function}\PY{n+nf}{ }\PY{n+nf}{getJacobian}\PY{p}{(}\PY{n}{t}\PY{p}{,}\PY{n}{x}\PY{p}{,}\PY{n}{J}\PY{p}{)} \PY{n}{J}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{p}{:}\PY{p}{]} \PY{o}{=} \PY{n}{ForwardDiff}\PY{o}{.}\PY{n}{jacobian}\PY{p}{(}\PY{n}{roberAD}\PY{p}{,}\PY{n}{x}\PY{p}{)}\PY{p}{;} \PY{k}{return} \PY{n}{nothing} \PY{k}{end} \PY{c}{\PYZsh{} Flag to check whether plot is to be generated and saved or not} \PY{c}{\PYZsh{} Also checks if all solvers are successful} \PY{n}{printFlag} \PY{o}{=} \PY{n}{true}\PY{p}{;} \PY{c}{\PYZsh{} Initial conditions} \PY{n}{t0} \PY{o}{=} \PY{l+m+mf}{0.0}\PY{p}{;} \PY{n}{T} \PY{o}{=} \PY{l+m+mf}{10.}\PY{o}{\PYZca{}}\PY{p}{[}\PY{l+m+mf}{0.0}\PY{p}{:}\PY{l+m+mf}{11.0}\PY{p}{;}\PY{p}{]}\PY{p}{;} \PY{n}{x0}\PY{o}{=}\PY{p}{[}\PY{l+m+mf}{1.0}\PY{p}{,}\PY{l+m+mf}{0.0}\PY{p}{,}\PY{l+m+mf}{0.0}\PY{p}{]}\PY{p}{;} \PY{c}{\PYZsh{} Get \PYZdq{}reference solution\PYZdq{} from} \PY{c}{\PYZsh{} http://www.unige.ch/\PYZti{}hairer/testset/testset.html} \PY{n}{f} \PY{o}{=} \PY{n}{open}\PY{p}{(}\PY{l+s}{\PYZdq{}}\PY{l+s}{roberRefSol.txt}\PY{l+s}{\PYZdq{}}\PY{p}{)} \PY{n}{lines} \PY{o}{=} \PY{n}{readlines}\PY{p}{(}\PY{n}{f}\PY{p}{)} \PY{n}{numLines} \PY{o}{=} \PY{n}{length}\PY{p}{(}\PY{n}{lines}\PY{p}{)} \PY{n}{lenArray} \PY{o}{=} \PY{n+nb}{convert}\PY{p}{(}\PY{k+kt}{Int64}\PY{p}{,}\PY{n}{numLines}\PY{o}{/}\PY{l+m+mi}{3}\PY{p}{)} \PY{n}{x\PYZus{}ref} \PY{o}{=} \PY{n}{Array}\PY{p}{\PYZob{}}\PY{k+kt}{Float64}\PY{p}{\PYZcb{}}\PY{p}{(}\PY{n}{lenArray}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{)}\PY{p}{;} \PY{n}{tmp} \PY{o}{=} \PY{n}{Array}\PY{p}{\PYZob{}}\PY{k+kt}{Float64}\PY{p}{\PYZcb{}}\PY{p}{(}\PY{n}{numLines}\PY{p}{)} \PY{n}{counter} \PY{o}{=} \PY{l+m+mi}{1} \PY{k}{for} \PY{n}{l} \PY{k}{in} \PY{n}{lines} \PY{n}{tmp}\PY{p}{[}\PY{n}{counter}\PY{p}{]} \PY{o}{=} \PY{n}{parse}\PY{p}{(}\PY{k+kt}{Float64}\PY{p}{,}\PY{n}{l}\PY{p}{)}\PY{p}{;} \PY{n}{counter} \PY{o}{+}\PY{o}{=}\PY{l+m+mi}{1}\PY{p}{;} \PY{k}{end} \PY{n}{x\PYZus{}ref} \PY{o}{=} \PY{p}{[}\PY{n}{tmp}\PY{p}{[}\PY{l+m+mi}{1}\PY{p}{:}\PY{l+m+mi}{3}\PY{p}{:}\PY{k}{end}\PY{p}{]} \PY{n}{tmp}\PY{p}{[}\PY{l+m+mi}{2}\PY{p}{:}\PY{l+m+mi}{3}\PY{p}{:}\PY{k}{end}\PY{p}{]} \PY{n}{tmp}\PY{p}{[}\PY{l+m+mi}{3}\PY{p}{:}\PY{l+m+mi}{3}\PY{p}{:}\PY{k}{end}\PY{p}{]}\PY{p}{]}\PY{p}{;} \PY{n}{close}\PY{p}{(}\PY{n}{f}\PY{p}{)} \end{Verbatim} \begin{Verbatim}[commandchars=\\\{\}] \PY{c}{\PYZsh{} Store the solver names for plotting} \PY{n}{solverNames} \PY{o}{=} \PY{p}{[}\PY{l+s}{\PYZdq{}}\PY{l+s}{RADAU}\PY{l+s}{\PYZdq{}}\PY{p}{,}\PY{l+s}{\PYZdq{}}\PY{l+s}{RADAU5}\PY{l+s}{\PYZdq{}}\PY{p}{,}\PY{l+s}{\PYZdq{}}\PY{l+s}{SEULEX}\PY{l+s}{\PYZdq{}}\PY{p}{]}\PY{p}{;} \PY{c}{\PYZsh{} Initialize the variables for plots} \PY{c}{\PYZsh{} err = error wrt ref solution over all time steps and components } \PY{n}{err} \PY{o}{=} \PY{n}{zeros}\PY{p}{(}\PY{l+m+mi}{33}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{)}\PY{p}{;} \PY{c}{\PYZsh{} f\PYZus{}e = number of function evaluations} \PY{n}{f\PYZus{}e} \PY{o}{=} \PY{n}{zeros}\PY{p}{(}\PY{l+m+mi}{33}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{)}\PY{p}{;} \PY{c}{\PYZsh{} flops = Floating point operations} \PY{n}{flops} \PY{o}{=} \PY{n}{zeros}\PY{p}{(}\PY{l+m+mi}{33}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{)}\PY{p}{;} \PY{c}{\PYZsh{} Weights for computing flops} \PY{n}{dim} \PY{o}{=} \PY{l+m+mi}{3}\PY{p}{;} \PY{c}{\PYZsh{} dimension of the system} \PY{n}{flopsRHS} \PY{o}{=} \PY{l+m+mi}{13}\PY{p}{;} \PY{c}{\PYZsh{} Counted} \PY{n}{flopsLU} \PY{o}{=} \PY{n}{ceil}\PY{p}{(}\PY{l+m+mi}{2}\PY{o}{*}\PY{p}{(}\PY{p}{(}\PY{n}{dim}\PY{p}{)}\PY{o}{\PYZca{}}\PY{l+m+mi}{3}\PY{p}{)}\PY{o}{/}\PY{l+m+mi}{3}\PY{p}{)}\PY{p}{;} \PY{c}{\PYZsh{} As per LU algorithm (can be less)} \PY{n}{flopsFW\PYZus{}BW} \PY{o}{=} \PY{p}{(}\PY{n}{dim}\PY{p}{)}\PY{o}{\PYZca{}}\PY{l+m+mi}{2}\PY{p}{;} \PY{c}{\PYZsh{} As per FW/BW algorithm (can be less)} \PY{n}{flopsJac} \PY{o}{=} \PY{n}{ceil}\PY{p}{(}\PY{l+m+mf}{1.5}\PY{o}{*}\PY{n}{flopsRHS}\PY{p}{)}\PY{p}{;} \PY{c}{\PYZsh{} A guess at the moment} \PY{c}{\PYZsh{} Loop over all the tolerances} \PY{k}{for} \PY{n}{m} \PY{o}{=} \PY{l+m+mi}{0}\PY{p}{:}\PY{l+m+mi}{32} \PY{c}{\PYZsh{} Set the tolerance for current run} \PY{n}{Tol} \PY{o}{=} \PY{l+m+mi}{10}\PY{o}{\PYZca{}}\PY{p}{(}\PY{o}{\PYZhy{}}\PY{l+m+mi}{2}\PY{o}{\PYZhy{}}\PY{n}{m}\PY{o}{/}\PY{l+m+mi}{4}\PY{p}{)}\PY{p}{;} \PY{c}{\PYZsh{} Set solver options} \PY{n}{opt} \PY{o}{=} \PY{n}{OptionsODE}\PY{p}{(}\PY{n}{OPT\PYZus{}EPS}\PY{o}{=}\PY{o}{\PYZgt{}}\PY{l+m+mf}{1.11e\PYZhy{}16}\PY{p}{,}\PY{n}{OPT\PYZus{}ATOL}\PY{o}{=}\PY{o}{\PYZgt{}}\PY{n}{Tol}\PY{o}{*}\PY{l+m+mf}{1e\PYZhy{}6}\PY{p}{,}\PY{n}{OPT\PYZus{}RTOL}\PY{o}{=}\PY{o}{\PYZgt{}}\PY{n}{Tol}\PY{p}{,} \PY{n}{OPT\PYZus{}RHS\PYZus{}CALLMODE} \PY{o}{=}\PY{o}{\PYZgt{}} \PY{n}{RHS\PYZus{}CALL\PYZus{}INSITU}\PY{p}{,} \PY{n}{OPT\PYZus{}JACOBIMATRIX}\PY{o}{=}\PY{o}{\PYZgt{}}\PY{n}{getJacobian}\PY{p}{)}\PY{p}{;} \PY{c}{\PYZsh{} Store the stats of the last t\PYZus{}end} \PY{c}{\PYZsh{} for computing flops} \PY{n}{stats} \PY{o}{=} \PY{n}{Dict}\PY{p}{\PYZob{}}\PY{n}{ASCIIString}\PY{p}{,}\PY{k+kt}{Any}\PY{p}{\PYZcb{}}\PY{p}{;} \PY{c}{\PYZsh{} Restart the solution for each end time} \PY{c}{\PYZsh{} to ensure a more accurate solution} \PY{c}{\PYZsh{} compared to dense output} \PY{c}{\PYZsh{} Solve using RADAU} \PY{n}{x\PYZus{}radau} \PY{o}{=} \PY{n}{Array}\PY{p}{\PYZob{}}\PY{k+kt}{Float64}\PY{p}{\PYZcb{}}\PY{p}{(}\PY{l+m+mi}{12}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{)}\PY{p}{;} \PY{k}{for} \PY{n}{j}\PY{o}{=}\PY{l+m+mi}{1}\PY{p}{:}\PY{l+m+mi}{12} \PY{p}{(}\PY{n}{t}\PY{p}{,}\PY{n}{x}\PY{p}{,}\PY{n}{retcode}\PY{p}{,}\PY{n}{stats}\PY{p}{)} \PY{o}{=} \PY{n}{radau}\PY{p}{(}\PY{n}{rober}\PY{p}{,}\PY{n}{t0}\PY{p}{,} \PY{n}{T}\PY{p}{[}\PY{n}{j}\PY{p}{]}\PY{p}{,} \PY{n}{x0}\PY{p}{,} \PY{n}{opt}\PY{p}{)}\PY{p}{;} \PY{c}{\PYZsh{} If solver fails do not continue further} \PY{k}{if} \PY{n}{retcode} \PY{o}{!=} \PY{l+m+mi}{1} \PY{n}{println}\PY{p}{(}\PY{l+s}{\PYZdq{}}\PY{l+s}{Solver RADAU failed}\PY{l+s}{\PYZdq{}}\PY{p}{)}\PY{p}{;} \PY{n}{printFlag} \PY{o}{=} \PY{n}{false}\PY{p}{;} \PY{k}{break}\PY{p}{;} \PY{k}{end} \PY{n}{x\PYZus{}radau}\PY{p}{[}\PY{n}{j}\PY{p}{,}\PY{l+m+mi}{1}\PY{p}{]} \PY{o}{=} \PY{n}{x}\PY{p}{[}\PY{l+m+mi}{1}\PY{p}{]}\PY{p}{;} \PY{n}{x\PYZus{}radau}\PY{p}{[}\PY{n}{j}\PY{p}{,}\PY{l+m+mi}{2}\PY{p}{]} \PY{o}{=} \PY{n}{x}\PY{p}{[}\PY{l+m+mi}{2}\PY{p}{]}\PY{p}{;} \PY{n}{x\PYZus{}radau}\PY{p}{[}\PY{n}{j}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{]} \PY{o}{=} \PY{n}{x}\PY{p}{[}\PY{l+m+mi}{3}\PY{p}{]}\PY{p}{;} \PY{n}{f\PYZus{}e}\PY{p}{[}\PY{n}{m}\PY{o}{+}\PY{l+m+mi}{1}\PY{p}{,}\PY{l+m+mi}{1}\PY{p}{]} \PY{o}{=} \PY{n}{stats}\PY{o}{.}\PY{n}{vals}\PY{p}{[}\PY{l+m+mi}{13}\PY{p}{]}\PY{p}{;} \PY{k}{end} \PY{c}{\PYZsh{} If solver fails do not continue further} \PY{k}{if} \PY{o}{!}\PY{n}{printFlag} \PY{k}{break}\PY{p}{;} \PY{k}{end} \PY{n}{err}\PY{p}{[}\PY{n}{m}\PY{o}{+}\PY{l+m+mi}{1}\PY{p}{,}\PY{l+m+mi}{1}\PY{p}{]} \PY{o}{=} \PY{n}{norm}\PY{p}{(}\PY{p}{[}\PY{n}{norm}\PY{p}{(}\PY{n}{x\PYZus{}radau}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{1}\PY{p}{]}\PY{o}{\PYZhy{}}\PY{n}{x\PYZus{}ref}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{1}\PY{p}{]}\PY{p}{,}\PY{n+nb}{Inf}\PY{p}{)}\PY{p}{,} \PY{n}{norm}\PY{p}{(}\PY{n}{x\PYZus{}radau}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{2}\PY{p}{]}\PY{o}{\PYZhy{}}\PY{n}{x\PYZus{}ref}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{2}\PY{p}{]}\PY{p}{,}\PY{n+nb}{Inf}\PY{p}{)}\PY{p}{,} \PY{n}{norm}\PY{p}{(}\PY{n}{x\PYZus{}radau}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{]}\PY{o}{\PYZhy{}}\PY{n}{x\PYZus{}ref}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{]}\PY{p}{,}\PY{n+nb}{Inf}\PY{p}{)}\PY{p}{]}\PY{p}{,}\PY{n+nb}{Inf}\PY{p}{)}\PY{p}{;} \PY{n}{flops}\PY{p}{[}\PY{n}{m}\PY{o}{+}\PY{l+m+mi}{1}\PY{p}{,}\PY{l+m+mi}{1}\PY{p}{]} \PY{o}{=} \PY{n}{stats}\PY{p}{[}\PY{l+s}{\PYZdq{}}\PY{l+s}{no\PYZus{}rhs\PYZus{}calls}\PY{l+s}{\PYZdq{}}\PY{p}{]}\PY{o}{*}\PY{n}{flopsRHS}\PY{o}{+} \PY{n}{stats}\PY{p}{[}\PY{l+s}{\PYZdq{}}\PY{l+s}{no\PYZus{}fw\PYZus{}bw\PYZus{}subst}\PY{l+s}{\PYZdq{}}\PY{p}{]}\PY{o}{*}\PY{n}{flopsFW\PYZus{}BW} \PY{o}{+} \PY{n}{stats}\PY{p}{[}\PY{l+s}{\PYZdq{}}\PY{l+s}{no\PYZus{}jac\PYZus{}calls}\PY{l+s}{\PYZdq{}}\PY{p}{]}\PY{o}{*}\PY{n}{flopsJac}\PY{o}{+} \PY{n}{stats}\PY{p}{[}\PY{l+s}{\PYZdq{}}\PY{l+s}{no\PYZus{}lu\PYZus{}decomp}\PY{l+s}{\PYZdq{}}\PY{p}{]}\PY{o}{*}\PY{n}{flopsLU}\PY{p}{;} \PY{c}{\PYZsh{} Solve using RADAU5} \PY{n}{x\PYZus{}radau5} \PY{o}{=} \PY{n}{Array}\PY{p}{\PYZob{}}\PY{k+kt}{Float64}\PY{p}{\PYZcb{}}\PY{p}{(}\PY{l+m+mi}{12}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{)}\PY{p}{;} \PY{k}{for} \PY{n}{j}\PY{o}{=}\PY{l+m+mi}{1}\PY{p}{:}\PY{l+m+mi}{12} \PY{p}{(}\PY{n}{t}\PY{p}{,}\PY{n}{x}\PY{p}{,}\PY{n}{retcode}\PY{p}{,}\PY{n}{stats}\PY{p}{)} \PY{o}{=} \PY{n}{radau5}\PY{p}{(}\PY{n}{rober}\PY{p}{,}\PY{n}{t0}\PY{p}{,} \PY{n}{T}\PY{p}{[}\PY{n}{j}\PY{p}{]}\PY{p}{,} \PY{n}{x0}\PY{p}{,} \PY{n}{opt}\PY{p}{)}\PY{p}{;} \PY{c}{\PYZsh{} If solver fails do not continue further} \PY{k}{if} \PY{n}{retcode} \PY{o}{!=} \PY{l+m+mi}{1} \PY{n}{println}\PY{p}{(}\PY{l+s}{\PYZdq{}}\PY{l+s}{Solver RADAU5 failed}\PY{l+s}{\PYZdq{}}\PY{p}{)}\PY{p}{;} \PY{n}{printFlag} \PY{o}{=} \PY{n}{false}\PY{p}{;} \PY{k}{break}\PY{p}{;} \PY{k}{end} \PY{n}{x\PYZus{}radau5}\PY{p}{[}\PY{n}{j}\PY{p}{,}\PY{l+m+mi}{1}\PY{p}{]} \PY{o}{=} \PY{n}{x}\PY{p}{[}\PY{l+m+mi}{1}\PY{p}{]}\PY{p}{;} \PY{n}{x\PYZus{}radau5}\PY{p}{[}\PY{n}{j}\PY{p}{,}\PY{l+m+mi}{2}\PY{p}{]} \PY{o}{=} \PY{n}{x}\PY{p}{[}\PY{l+m+mi}{2}\PY{p}{]}\PY{p}{;} \PY{n}{x\PYZus{}radau5}\PY{p}{[}\PY{n}{j}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{]} \PY{o}{=} \PY{n}{x}\PY{p}{[}\PY{l+m+mi}{3}\PY{p}{]}\PY{p}{;} \PY{n}{f\PYZus{}e}\PY{p}{[}\PY{n}{m}\PY{o}{+}\PY{l+m+mi}{1}\PY{p}{,}\PY{l+m+mi}{2}\PY{p}{]} \PY{o}{=} \PY{n}{stats}\PY{o}{.}\PY{n}{vals}\PY{p}{[}\PY{l+m+mi}{13}\PY{p}{]}\PY{p}{;} \PY{k}{end} \PY{c}{\PYZsh{} If solver fails do not continue further} \PY{k}{if} \PY{o}{!}\PY{n}{printFlag} \PY{k}{break}\PY{p}{;} \PY{k}{end} \PY{n}{err}\PY{p}{[}\PY{n}{m}\PY{o}{+}\PY{l+m+mi}{1}\PY{p}{,}\PY{l+m+mi}{2}\PY{p}{]} \PY{o}{=} \PY{n}{norm}\PY{p}{(}\PY{p}{[}\PY{n}{norm}\PY{p}{(}\PY{n}{x\PYZus{}radau5}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{1}\PY{p}{]}\PY{o}{\PYZhy{}}\PY{n}{x\PYZus{}ref}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{1}\PY{p}{]}\PY{p}{,}\PY{n+nb}{Inf}\PY{p}{)}\PY{p}{,} \PY{n}{norm}\PY{p}{(}\PY{n}{x\PYZus{}radau5}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{2}\PY{p}{]}\PY{o}{\PYZhy{}}\PY{n}{x\PYZus{}ref}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{2}\PY{p}{]}\PY{p}{,}\PY{n+nb}{Inf}\PY{p}{)}\PY{p}{,} \PY{n}{norm}\PY{p}{(}\PY{n}{x\PYZus{}radau5}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{]}\PY{o}{\PYZhy{}}\PY{n}{x\PYZus{}ref}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{]}\PY{p}{,}\PY{n+nb}{Inf}\PY{p}{)}\PY{p}{]}\PY{p}{,}\PY{n+nb}{Inf}\PY{p}{)}\PY{p}{;} \PY{n}{flops}\PY{p}{[}\PY{n}{m}\PY{o}{+}\PY{l+m+mi}{1}\PY{p}{,}\PY{l+m+mi}{2}\PY{p}{]} \PY{o}{=} \PY{n}{stats}\PY{p}{[}\PY{l+s}{\PYZdq{}}\PY{l+s}{no\PYZus{}rhs\PYZus{}calls}\PY{l+s}{\PYZdq{}}\PY{p}{]}\PY{o}{*}\PY{n}{flopsRHS}\PY{o}{+} \PY{n}{stats}\PY{p}{[}\PY{l+s}{\PYZdq{}}\PY{l+s}{no\PYZus{}fw\PYZus{}bw\PYZus{}subst}\PY{l+s}{\PYZdq{}}\PY{p}{]}\PY{o}{*}\PY{n}{flopsFW\PYZus{}BW} \PY{o}{+} \PY{n}{stats}\PY{p}{[}\PY{l+s}{\PYZdq{}}\PY{l+s}{no\PYZus{}jac\PYZus{}calls}\PY{l+s}{\PYZdq{}}\PY{p}{]}\PY{o}{*}\PY{n}{flopsJac}\PY{o}{+} \PY{n}{stats}\PY{p}{[}\PY{l+s}{\PYZdq{}}\PY{l+s}{no\PYZus{}lu\PYZus{}decomp}\PY{l+s}{\PYZdq{}}\PY{p}{]}\PY{o}{*}\PY{n}{flopsLU}\PY{p}{;} \PY{c}{\PYZsh{} Solve using SEULEX} \PY{n}{x\PYZus{}seulex} \PY{o}{=} \PY{n}{Array}\PY{p}{\PYZob{}}\PY{k+kt}{Float64}\PY{p}{\PYZcb{}}\PY{p}{(}\PY{l+m+mi}{12}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{)}\PY{p}{;} \PY{k}{for} \PY{n}{j}\PY{o}{=}\PY{l+m+mi}{1}\PY{p}{:}\PY{l+m+mi}{12} \PY{p}{(}\PY{n}{t}\PY{p}{,}\PY{n}{x}\PY{p}{,}\PY{n}{retcode}\PY{p}{,}\PY{n}{stats}\PY{p}{)} \PY{o}{=} \PY{n}{seulex}\PY{p}{(}\PY{n}{rober}\PY{p}{,}\PY{n}{t0}\PY{p}{,} \PY{n}{T}\PY{p}{[}\PY{n}{j}\PY{p}{]}\PY{p}{,} \PY{n}{x0}\PY{p}{,} \PY{n}{opt}\PY{p}{)}\PY{p}{;} \PY{c}{\PYZsh{} If solver fails do not continue further} \PY{k}{if} \PY{n}{retcode} \PY{o}{!=} \PY{l+m+mi}{1} \PY{n}{println}\PY{p}{(}\PY{l+s}{\PYZdq{}}\PY{l+s}{Solver seulex failed}\PY{l+s}{\PYZdq{}}\PY{p}{)}\PY{p}{;} \PY{n}{printFlag} \PY{o}{=} \PY{n}{false}\PY{p}{;} \PY{k}{break}\PY{p}{;} \PY{k}{end} \PY{n}{x\PYZus{}seulex}\PY{p}{[}\PY{n}{j}\PY{p}{,}\PY{l+m+mi}{1}\PY{p}{]} \PY{o}{=} \PY{n}{x}\PY{p}{[}\PY{l+m+mi}{1}\PY{p}{]}\PY{p}{;} \PY{n}{x\PYZus{}seulex}\PY{p}{[}\PY{n}{j}\PY{p}{,}\PY{l+m+mi}{2}\PY{p}{]} \PY{o}{=} \PY{n}{x}\PY{p}{[}\PY{l+m+mi}{2}\PY{p}{]}\PY{p}{;} \PY{n}{x\PYZus{}seulex}\PY{p}{[}\PY{n}{j}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{]} \PY{o}{=} \PY{n}{x}\PY{p}{[}\PY{l+m+mi}{3}\PY{p}{]}\PY{p}{;} \PY{n}{f\PYZus{}e}\PY{p}{[}\PY{n}{m}\PY{o}{+}\PY{l+m+mi}{1}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{]} \PY{o}{=} \PY{n}{stats}\PY{o}{.}\PY{n}{vals}\PY{p}{[}\PY{l+m+mi}{13}\PY{p}{]}\PY{p}{;} \PY{k}{end} \PY{c}{\PYZsh{} If solver fails do not continue further} \PY{k}{if} \PY{o}{!}\PY{n}{printFlag} \PY{k}{break}\PY{p}{;} \PY{k}{end} \PY{n}{err}\PY{p}{[}\PY{n}{m}\PY{o}{+}\PY{l+m+mi}{1}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{]} \PY{o}{=} \PY{n}{norm}\PY{p}{(}\PY{p}{[}\PY{n}{norm}\PY{p}{(}\PY{n}{x\PYZus{}seulex}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{1}\PY{p}{]}\PY{o}{\PYZhy{}}\PY{n}{x\PYZus{}ref}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{1}\PY{p}{]}\PY{p}{,}\PY{n+nb}{Inf}\PY{p}{)}\PY{p}{,} \PY{n}{norm}\PY{p}{(}\PY{n}{x\PYZus{}seulex}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{2}\PY{p}{]}\PY{o}{\PYZhy{}}\PY{n}{x\PYZus{}ref}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{2}\PY{p}{]}\PY{p}{,}\PY{n+nb}{Inf}\PY{p}{)}\PY{p}{,} \PY{n}{norm}\PY{p}{(}\PY{n}{x\PYZus{}seulex}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{]}\PY{o}{\PYZhy{}}\PY{n}{x\PYZus{}ref}\PY{p}{[}\PY{p}{:}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{]}\PY{p}{,}\PY{n+nb}{Inf}\PY{p}{)}\PY{p}{]}\PY{p}{,}\PY{n+nb}{Inf}\PY{p}{)}\PY{p}{;} \PY{n}{flops}\PY{p}{[}\PY{n}{m}\PY{o}{+}\PY{l+m+mi}{1}\PY{p}{,}\PY{l+m+mi}{3}\PY{p}{]} \PY{o}{=} \PY{n}{stats}\PY{p}{[}\PY{l+s}{\PYZdq{}}\PY{l+s}{no\PYZus{}rhs\PYZus{}calls}\PY{l+s}{\PYZdq{}}\PY{p}{]}\PY{o}{*}\PY{n}{flopsRHS}\PY{o}{+} \PY{n}{stats}\PY{p}{[}\PY{l+s}{\PYZdq{}}\PY{l+s}{no\PYZus{}fw\PYZus{}bw\PYZus{}subst}\PY{l+s}{\PYZdq{}}\PY{p}{]}\PY{o}{*}\PY{n}{flopsFW\PYZus{}BW} \PY{o}{+} \PY{n}{stats}\PY{p}{[}\PY{l+s}{\PYZdq{}}\PY{l+s}{no\PYZus{}jac\PYZus{}calls}\PY{l+s}{\PYZdq{}}\PY{p}{]}\PY{o}{*}\PY{n}{flopsJac}\PY{o}{+} \PY{n}{stats}\PY{p}{[}\PY{l+s}{\PYZdq{}}\PY{l+s}{no\PYZus{}lu\PYZus{}decomp}\PY{l+s}{\PYZdq{}}\PY{p}{]}\PY{o}{*}\PY{n}{flopsLU}\PY{p}{;} \PY{k}{end} \PY{k}{if} \PY{n}{printFlag} \PY{n}{savePlotPNG}\PY{p}{(}\PY{l+s}{\PYZdq{}}\PY{l+s}{RoberPrecisionTest}\PY{l+s}{\PYZdq{}}\PY{p}{,}\PY{n}{f\PYZus{}e}\PY{p}{,}\PY{n}{err}\PY{p}{,}\PY{n}{solverNames}\PY{p}{)}\PY{p}{;} \PY{k}{else} \PY{n}{println}\PY{p}{(}\PY{l+s}{\PYZdq{}}\PY{l+s}{Plot cannot be generated due to failure}\PY{l+s}{\PYZdq{}}\PY{p}{)}\PY{p}{;} \PY{k}{end} \end{Verbatim} % Add a bibliography block to the postdoc \end{document}
TeX
!vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvC ! C ! Subroutine: CALC_EXPLICIT_MOM_SOURCE_S C ! Purpose: Determine any additional momentum source terms that are C ! calculated explicitly here C ! C ! C !^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^C SUBROUTINE CALC_EXPLICIT_MOM_SOURCE_S() !----------------------------------------------- ! Modules !----------------------------------------------- USE param1, only: zero ! kinetic theories USE run, only: kt_type_enum USE run, only: ia_2005 ! number of solids phases USE physprop, only: smax ! solids source term USE kintheory, only: ktmom_u_s, ktmom_v_s, ktmom_w_s IMPLICIT NONE !----------------------------------------------- ! Local variables !----------------------------------------------- ! Solids phase index INTEGER :: M !----------------------------------------------- ! Additional interphase interaction terms that arise from kinetic theory DO M = 1, SMAX KTMOM_U_s(:,M) = ZERO KTMOM_V_S(:,M) = ZERO KTMOM_W_S(:,M) = ZERO IF (KT_TYPE_ENUM == IA_2005) THEN CALL CALC_IA_MOMSOURCE_U_S(M) CALL CALC_IA_MOMSOURCE_V_S(M) CALL CALC_IA_MOMSOURCE_W_S(M) ENDIF ENDDO RETURN END SUBROUTINE CALC_EXPLICIT_MOM_SOURCE_S !vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvC ! C ! Subroutine: CALC_IA_MOMSOURCE_U_S C ! Purpose: Determine source terms for U_S momentum equation arising C ! from IA kinetic theory constitutive relations for stress C ! and solids-solids drag (collisional momentum source) C ! C ! Literature/Document References: C ! Idir, Y.H., "Modeling of the multiphase mixture of particles C ! using the kinetic theory approach," PhD Thesis, Illinois C ! Institute of Technology, Chicago, Illinois, 2004 C ! Iddir, Y.H., & H. Arastoopour, "Modeling of multitype particle C ! flow using the kinetic theory approach," AIChE J., Vol 51, C ! No 6, June 2005 C ! C !^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^C SUBROUTINE CALC_IA_MOMSOURCE_U_S(M) !----------------------------------------------- ! Modules !----------------------------------------------- USE param1, only: half, zero USE constant, only: pi ! trace of D_s at i, j, k USE visc_s, only: trD_s ! number of solids phases USE physprop, only: mmax ! x,y,z-components of solids velocity USE fldvar, only: u_s, v_s, w_s ! particle diameter, bulk density, material density USE fldvar, only: d_p, rop_s, ro_s ! granular temperature USE fldvar, only: theta_m, ep_s ! dilute threshold USE toleranc, only: dil_ep_s Use kintheory USE geometry USE indices USE compar USE fun_avg USE functions IMPLICIT NONE !----------------------------------------------- ! Dummy arguments !----------------------------------------------- ! solids phase index INTEGER, INTENT(IN) :: M !----------------------------------------------- ! Local variables !----------------------------------------------- ! Temporary variable DOUBLE PRECISION :: STRESS_TERMS, DRAG_TERMS ! Indices INTEGER :: I, J, JM, K, KM, IJK, IJKE, IPJK, IP, IMJK, IJKN,& IJKNE, IJKS, IJKSE, IPJMK, IJMK, IJKT, IJKTE,& IJKB, IJKBE, IJKM, IPJKM, & IJPK, IJKP, IM, IJKW ! solids phase index INTEGER :: L ! Viscosity values for stress calculations DOUBLE PRECISION :: MU_sL_pE, MU_sL_pW, MU_sL_pN, MU_sL_pS, MU_sL_pT,& MU_sL_pB, Mu_sL_p ! Bulk viscosity values for calculations DOUBLE PRECISION :: XI_sL_pE, XI_sL_pW, LAMBDA_sL_pE, LAMBDA_sL_pW ! Variables for drag calculations DOUBLE PRECISION :: M_PM, M_PL, D_PM, D_PL, NU_PM_pE, NU_PM_pW, NU_PM_p, & NU_PL_pE, NU_PL_pW, NU_PL_p, T_PM_pE, T_PM_pW, & T_PL_pE, T_PL_pW, Fnu_s_p, FT_sM_p, FT_sL_p ! Average volume fraction DOUBLE PRECISION :: EPSA ! Source terms (Surface) DOUBLE PRECISION :: ssux, ssuy, ssuz, ssx, ssy, ssz, ssbv ! Source terms (Volumetric) DOUBLE PRECISION :: tauzz, DS1, DS2, DS3, DS4, DS1plusDS2 !----------------------------------------------- ! section largely based on tau_u_g: DO IJK = IJKSTART3, IJKEND3 ! Skip walls where some values are undefined. IF(WALL_AT(IJK)) cycle D_PM = D_P(IJK,M) M_PM = (Pi/6d0)*D_PM**3 * RO_S(IJK,M) I = I_OF(IJK) IJKE = EAST_OF(IJK) EPSA = AVG_X(EP_S(IJK,M),EP_S(IJKE,M),I) IF ( .NOT.SIP_AT_E(IJK) .AND. EPSA>DIL_EP_S) THEN IP = IP1(I) IM = Im1(I) IJKW = WEST_OF(IJK) J = J_OF(IJK) JM = JM1(J) K = K_OF(IJK) KM = KM1(K) IPJK = IP_OF(IJK) IMJK = IM_OF(IJK) IJMK = JM_OF(IJK) IJKM = KM_OF(IJK) IPJMK = JM_OF(IPJK) IPJKM = IP_OF(IJKM) IJKN = NORTH_OF(IJK) IJKS = SOUTH_OF(IJK) IJKNE = EAST_OF(IJKN) IJKSE = EAST_OF(IJKS) IJKT = TOP_OF(IJK) IJKB = BOTTOM_OF(IJK) IJKTE = EAST_OF(IJKT) IJKBE = EAST_OF(IJKB) ! additional required quantities: IJPK = JP_OF(IJK) IJKP = KP_OF(IJK) ! initialize variable STRESS_TERMS = ZERO DRAG_TERMS = ZERO DO L = 1,MMAX IF (M .ne. L) THEN !--------------------- Sources from Stress Terms --------------------- ! Surface Forces ! standard shear stress terms (i.e. ~diffusion) MU_sL_pE = MU_sL_ip(IJKE,M,L) MU_sL_pW = MU_sL_ip(IJK,M,L) SSUX = MU_sL_pE*(U_S(IPJK,L)-U_S(IJK,L))*AYZ_U(IJK)*ODX(IP)& -MU_sL_PW*(U_S(IJK,L)-U_S(IMJK,L))*AYZ_U(IMJK)*ODX(I) MU_sL_pN = AVG_X_H(AVG_Y_H(MU_sL_ip(IJK,M,L),MU_sL_ip(IJKN,M,L), J),& AVG_Y_H(MU_sL_ip(IJKE,M,L),MU_sL_ip(IJKNE,M,L), J), I) MU_sL_pS = AVG_X_H(AVG_Y_H(MU_sL_ip(IJKS,M,L),MU_sL_ip(IJK,M,L), JM),& AVG_Y_H(MU_sL_ip(IJKSE,M,L),MU_sL_ip(IJKE,M,L), JM), I) SSUY = MU_sL_pN*(U_S(IJPK,L)-U_S(IJK,L))*AXZ_U(IJK)*ODY_N(J)& -MU_sL_pS*(U_S(IJK,L)-U_S(IJMK,L))*AXZ_U(IJMK)*ODY_N(JM) MU_sL_pT = AVG_X_H(AVG_Z_H(MU_sL_ip(IJK,M,L),MU_sL_ip(IJKT,M,L),K),& AVG_Z_H(MU_sL_ip(IJKE,M,L),MU_sL_ip(IJKTE,M,L),K),I) MU_sL_pB = AVG_X_H(AVG_Z_H(MU_sL_ip(IJKB,M,L),MU_sL_ip(IJK,M,L),KM),& AVG_Z_H(MU_sL_ip(IJKBE,M,L),MU_sL_ip(IJKE,M,L),KM),I) SSUZ = MU_sL_pT*(U_S(IJKP,L)-U_S(IJK,L))*AXY_U(IJK)*ODZ_T(K)*OX_E(I)& -MU_sL_pB*(U_S(IJK,L)-U_S(IJKM,L))*AXY_U(IJKM)*ODZ_T(KM)*OX_E(I) ! bulk viscosity term XI_sL_pE = XI_sL_ip(IJKE,M,L) XI_sL_pW = XI_sL_ip(IJK,M,L) LAMBDA_sL_pE = -(2.d0/3.d0)*Mu_sL_pE + XI_sL_pE LAMBDA_sL_pW = -(2.d0/3.d0)*Mu_sL_pW + XI_sL_pW SSBV = (LAMBDA_sL_pE*TRD_S(IJKE,L)-LAMBDA_sL_pW*TRD_S(IJK,L))*AYZ(IJK) ! off diagonal shear stress terms SSX = SSUX SSY = MU_sL_pN*(V_S(IPJK,L)-V_S(IJK,L))*AXZ_U(IJK)*ODX_E(I)& -MU_sL_pS*(V_S(IPJMK,L)-V_S(IJMK,L))*AXZ_U(IJMK)*ODX_E(I) SSZ = MU_sL_pT*(W_S(IPJK,L)-W_S(IJK,L))*AXY_U(IJK)*ODX_E(I)& -MU_sL_pB*(W_S(IPJKM,L)-W_S(IJKM,L))*AXY_U(IJKM)*ODX_E(I) ! special terms for cylindrical coordinates IF (CYLINDRICAL) THEN ! modify Ssz: (1/x) (d/dz) (tau_zz) ! integral of (1/x) (d/dz) (mu*(-w/x)) ! (normally part of tau_u_s) - explicit SSZ = SSZ - (MU_sL_pT*(W_S(IPJK,L)+W_S(IJK,L))*HALF*OX_E(I)*AXY_U(IJK)& -MU_sL_pB*(W_S(IPJKM,L)+W_S(IJKM,L))*HALF*OX_E(I)*AXY_U(IJKM)) ! tau_zz/x terms: (tau_zz/x) ! integral of -(2mu/x)*(1/x)*dw/dz ! (normally part of tau_u_s) - explicit MU_sL_p = AVG_X(MU_sL_ip(IJK,M,L),MU_sL_ip(IJKE,M,L),I) tauzz = -2.d0*MU_sL_p*OX_E(I)*HALF*(& ((W_S(IPJK,L)-W_S(IPJKM,L))*OX(IP)*ODZ(K))+& ((W_S(IJK,L)-W_S(IJKM,L))*OX(I)*ODZ(K)) & ) * VOL_U(IJK) ! integral of -(2mu/x)*(1/x)*u ! (normally part of source_u_s) tauzz = tauzz + (-2.d0*MU_sL_p*OX_E(I)*OX_E(I)*& U_S(IJK,L)*VOL_U(IJK)) ELSE tauzz = ZERO ENDIF !--------------------- End Sources from Stress Term --------------------- !--------------------- Sources from Momentum Source Term --------------------- ! Momentum source associated with the difference in the gradients in ! number density of solids phase m and all other solids phases D_PL = D_P(IJK,L) M_PL = (PI/6.d0)*D_PL**3 * RO_S(IJK,L) NU_PM_pE = ROP_S(IJKE,M)/M_PM NU_PM_pW = ROP_S(IJK,M)/M_PM NU_PM_p = AVG_X(NU_PM_pW,NU_PM_pE,I) NU_PL_pE = ROP_S(IJKE,L)/M_PL NU_PL_pW = ROP_S(IJK,L)/M_PL NU_PL_p = AVG_X(NU_PL_pW,NU_PL_pE,I) Fnu_s_p = AVG_X(Fnu_s_ip(IJK,M,L),Fnu_s_ip(IJKE,M,L),I) DS1 = Fnu_s_p*NU_PL_p*(NU_PM_pE-NU_PM_pW)*ODX_E(I) DS2 = -Fnu_s_p*NU_PM_p*(NU_PL_pE-NU_PL_pW)*ODX_E(I) DS1plusDS2 = DS1 + DS2 ! Momentum source associated with the gradient in granular ! temperature of species M T_PM_pE = Theta_M(IJKE,M) T_PM_pW = Theta_M(IJK,M) FT_sM_p = AVG_X(FT_sM_ip(IJK,M,L),FT_sM_ip(IJKE,M,L),I) DS3 = FT_sM_p*(T_PM_pE-T_PM_pW)*ODX_E(I) ! Momentum source associated with the gradient in granular ! temperature of species L T_PL_pE = Theta_M(IJKE,L) T_PL_pW = Theta_M(IJK,L) FT_sL_p = AVG_X(FT_sL_ip(IJK,M,L),FT_sL_ip(IJKE,M,L),I) DS4 = FT_sL_p*(T_PL_pE-T_PL_pW)*ODX_E(I) !--------------------- End Sources from Momentum Source Term --------------------- ! Add the terms STRESS_TERMS = STRESS_TERMS + SSUX + SSUY + SSUZ + & SSBV + SSX + SSY + SSZ + tauzz DRAG_TERMS = DRAG_TERMS + (DS1plusDS2+DS3+DS4)*VOL_U(IJK) ELSE ! if m .ne. L ! for m = l all stress terms should already be handled in existing routines ! for m = l all drag terms should become zero STRESS_TERMS = STRESS_TERMS + ZERO DRAG_TERMS = DRAG_TERMS + ZERO ENDIF ! if m .ne. L ENDDO ! over L KTMOM_U_S(IJK,M) = STRESS_TERMS + DRAG_TERMS ELSE KTMOM_U_S(IJK,M) = ZERO ENDIF ! dilute ENDDO ! over ijk RETURN END SUBROUTINE CALC_IA_MOMSOURCE_U_S !vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv! ! ! ! Subroutine: COLL_MOMENTUM_COEFF_IA ! ! Purpose: Compute collisional momentum source terms betweem solids ! ! phase M and solids phase L using Iddir Arastoopour (2005) kinetic ! ! theory model that are not proportional to the relative velocity ! ! between the two phases. Specifically, terms proportional to the ! ! gradient in number density and gradient in temperature ! ! ! ! Literature/Document References: ! ! Iddir, Y.H., "Modeling of the multiphase mixture of particles ! ! using the kinetic theory approach," PhD Thesis, Illinois ! ! Institute of Technology, Chicago, Illinois, 2004 ! ! Iddir, Y.H., & H. Arastoopour, "Modeling of Multitype particle ! ! flow using the kinetic theory approach," AIChE J., Vol 51, ! ! no. 6, June 2005 ! ! ! !^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^! SUBROUTINE COLL_MOMENTUM_COEFF_IA(L, M) !----------------------------------------------- ! Modules !----------------------------------------------- USE compar USE constant USE drag USE fldvar USE functions USE geometry USE indices USE kintheory USE param1 USE physprop USE rdf USE sendrecv IMPLICIT NONE !----------------------------------------------- ! Dummy arguments !----------------------------------------------- ! Solids phase index INTEGER, INTENT(IN) :: L INTEGER, INTENT(IN) :: M !----------------------------------------------- ! Local variables !----------------------------------------------- ! Indices INTEGER :: IJK ! Particle diameters DOUBLE PRECISION :: D_PM, D_PL ! Sum of particle diameters DOUBLE PRECISION :: DPSUM ! DOUBLE PRECISION :: M_PM, M_PL, MPSUM, DPSUMo2, NU_PL, NU_PM DOUBLE PRECISION :: Ap_lm, Dp_lm, Bp_lm DOUBLE PRECISION :: R0p_lm, R3p_lm, R4p_lm, R10p_lm DOUBLE PRECISION :: Fnus_ip, FTsM_ip, FTsL_ip, F_common_term !----------------------------------------------- DO IJK = ijkstart3, ijkend3 IF (.NOT.WALL_AT(IJK)) THEN IF (M == L) THEN Fnu_s_ip(IJK,M,L) = ZERO FT_sM_ip(IJK,M,L) = ZERO FT_sL_ip(IJK,M,L) = ZERO ELSE D_PM = D_P(IJK,M) D_PL = D_P(IJK,L) DPSUM = D_PL + D_PM M_PM = (Pi/6.d0) * D_PM**3 *RO_S(IJK,M) M_PL = (Pi/6.d0) * D_PL**3 *RO_S(IJK,L) MPSUM = M_PM + M_PL DPSUMo2 = DPSUM/2.d0 NU_PM = ROP_S(IJK,M)/M_PM NU_PL = ROP_S(IJK,L)/M_PL IF(Theta_m(IJK,M) > ZERO .AND. Theta_m(IJK,L) > ZERO) THEN Ap_lm = (M_PM*Theta_m(IJK,L)+M_PL*Theta_m(IJK,M))/& 2.d0 Bp_lm = (M_PM*M_PL*(Theta_m(IJK,L)-Theta_m(IJK,M) ))/& (2.d0*MPSUM) Dp_lm = (M_PL*M_PM*(M_PM*Theta_m(IJK,M)+M_PL*Theta_m(IJK,L) ))/& (2.d0*MPSUM*MPSUM) R0p_lm = ( 1.d0/( Ap_lm**1.5 * Dp_lm**2.5 ) )+ & ( (15.d0*Bp_lm*Bp_lm)/( 2.d0* Ap_lm**2.5 * Dp_lm**3.5 ) )+& ( (175.d0*(Bp_lm**4))/( 8.d0*Ap_lm**3.5 * Dp_lm**4.5 ) ) R3p_lm = ( 1.d0/( (Ap_lm**1.5)*(Dp_lm**3.5) ) )+& ( (21.d0*Bp_lm*Bp_lm)/( 2.d0 * Ap_lm**2.5 * Dp_lm**4.5 ) )+& ( (315.d0*Bp_lm**4)/( 8.d0 * Ap_lm**3.5 *Dp_lm**5.5 ) ) R4p_lm = ( 3.d0/( Ap_lm**2.5 * Dp_lm**3.5 ) )+& ( (35.d0*Bp_lm*Bp_lm)/( 2.d0 * Ap_lm**3.5 * Dp_lm**4.5 ) )+& ( (441.d0*Bp_lm**4)/( 8.d0 * Ap_lm**4.5 * Dp_lm**5.5 ) ) R10p_lm = ( 1.d0/( Ap_lm**2.5 * Dp_lm**2.5 ) )+& ( (25.d0*Bp_lm*Bp_lm)/( 2.d0* Ap_lm**3.5 * Dp_lm**3.5 ) )+& ( (1225.d0*Bp_lm**4)/( 24.d0* Ap_lm**4.5 * Dp_lm**4.5 ) ) F_common_term = (DPSUMo2*DPSUMo2/4.d0)*(M_PM*M_PL/MPSUM)*& G_0(IJK,M,L)*(1.d0+C_E)*(M_PM*M_PL)**1.5 ! Momentum source associated with the difference in the gradients in ! number density of solids phase m and all other solids phases Fnus_ip = F_common_term*(PI*DPSUMo2/12.d0)*R0p_lm*& (Theta_m(IJK,M)*Theta_m(IJK,L))**2.5 ! Momentum source associated with the gradient in granular temperature ! of solid phase M FTsM_ip = F_common_term*NU_PM*NU_PL*DPSUMo2*PI*& (Theta_m(IJK,M)**1.5 * Theta_m(IJK,L)**2.5) *& ( (-1.5d0/12.d0*R0p_lm)+& Theta_m(IJK,L)/16.d0*( (-M_PM*R10p_lm) - & ((5.d0*M_PL*M_PL*M_PM/(192.d0*MPSUM*MPSUM))*R3p_lm)+& ((5.d0*M_PM*M_PL)/(96.d0*MPSUM)*R4p_lm*Bp_lm) ) ) ! Momentum source associated with the gradient in granular temperature ! of solid phase L ! no need to recompute (sof Aug 30 2006) FTsL_ip = F_common_term*NU_PM*NU_PL*DPSUMo2*PI*& (Theta_m(IJK,L)**1.5 * Theta_m(IJK,M)**2.5) *& ( (1.5d0/12.d0*R0p_lm)+& Theta_m(IJK,M)/16.d0*( (M_PL*R10p_lm)+& (5.d0*M_PM*M_PM*M_PL/(192.d0*MPSUM*MPSUM)*R3p_lm)+& (5.d0*M_PM*M_PL/(96.d0*MPSUM) *R4p_lm*Bp_lm) ) ) Fnu_s_ip(IJK,M,L) = Fnus_ip ! WARNING: the following two terms have caused some convergence problems ! earlier. Set them to ZERO for debugging in case of converegence ! issues. (sof) FT_sM_ip(IJK,M,L) = FTsM_ip ! ZERO FT_sL_ip(IJK,M,L) = FTsL_ip ! ZERO ELSE Fnu_s_ip(IJK,M,L) = ZERO FT_sM_ip(IJK,M,L) = ZERO FT_sL_ip(IJK,M,L) = ZERO ENDIF ENDIF ENDIF ENDDO RETURN END SUBROUTINE COLL_MOMENTUM_COEFF_IA
Fortran Free Form
create table validations( validation_id varchar(40) primary key, account_id varchar(40), status varchar(20), strategy varchar(20), vendor varchar(20), created_at datetime, updated_at datetime );
PLSQL
SUBROUTINE L7VML(N, X, L, Y) C C *** COMPUTE X = L*Y, WHERE L IS AN N X N LOWER TRIANGULAR C *** MATRIX STORED COMPACTLY BY ROWS. X AND Y MAY OCCUPY THE SAME C *** STORAGE. *** C INTEGER N REAL X(N), L(1), Y(N) C DIMENSION L(N*(N+1)/2) INTEGER I, II, IJ, I0, J, NP1 REAL T, ZERO C/6 C DATA ZERO/0.E+0/ C/7 PARAMETER (ZERO=0.E+0) C/ C NP1 = N + 1 I0 = N*(N+1)/2 DO 20 II = 1, N I = NP1 - II I0 = I0 - I T = ZERO DO 10 J = 1, I IJ = I0 + J T = T + L(IJ)*Y(J) 10 CONTINUE X(I) = T 20 CONTINUE 999 RETURN C *** LAST CARD OF L7VML FOLLOWS *** END
Fortran Free Form
// Copyright 2014 beego Author. 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. package utils import ( "bytes" "encoding/base64" "encoding/json" "errors" "fmt" "io" "mime" "mime/multipart" "net/mail" "net/smtp" "net/textproto" "os" "path" "path/filepath" "strconv" "strings" ) const ( maxLineLength = 76 ) // Email is the type used for email messages type Email struct { Auth smtp.Auth Identity string `json:"identity"` Username string `json:"username"` Password string `json:"password"` Host string `json:"host"` Port int `json:"port"` From string `json:"from"` To []string Bcc []string Cc []string Subject string Text string // Plaintext message (optional) HTML string // Html message (optional) Headers textproto.MIMEHeader Attachments []*Attachment ReadReceipt []string } // Attachment is a struct representing an email attachment. // Based on the mime/multipart.FileHeader struct, Attachment contains the name, MIMEHeader, and content of the attachment in question type Attachment struct { Filename string Header textproto.MIMEHeader Content []byte } // NewEMail create new Email struct with config json. // config json is followed from Email struct fields. func NewEMail(config string) *Email { e := new(Email) e.Headers = textproto.MIMEHeader{} err := json.Unmarshal([]byte(config), e) if err != nil { return nil } if e.From == "" { e.From = e.Username } return e } // Bytes Make all send information to byte func (e *Email) Bytes() ([]byte, error) { buff := &bytes.Buffer{} w := multipart.NewWriter(buff) // Set the appropriate headers (overwriting any conflicts) // Leave out Bcc (only included in envelope headers) e.Headers.Set("To", strings.Join(e.To, ",")) if e.Cc != nil { e.Headers.Set("Cc", strings.Join(e.Cc, ",")) } e.Headers.Set("From", e.From) e.Headers.Set("Subject", e.Subject) if len(e.ReadReceipt) != 0 { e.Headers.Set("Disposition-Notification-To", strings.Join(e.ReadReceipt, ",")) } e.Headers.Set("MIME-Version", "1.0") // Write the envelope headers (including any custom headers) if err := headerToBytes(buff, e.Headers); err != nil { return nil, fmt.Errorf("Failed to render message headers: %s", err) } e.Headers.Set("Content-Type", fmt.Sprintf("multipart/mixed;\r\n boundary=%s\r\n", w.Boundary())) fmt.Fprintf(buff, "%s:", "Content-Type") fmt.Fprintf(buff, " %s\r\n", fmt.Sprintf("multipart/mixed;\r\n boundary=%s\r\n", w.Boundary())) // Start the multipart/mixed part fmt.Fprintf(buff, "--%s\r\n", w.Boundary()) header := textproto.MIMEHeader{} // Check to see if there is a Text or HTML field if e.Text != "" || e.HTML != "" { subWriter := multipart.NewWriter(buff) // Create the multipart alternative part header.Set("Content-Type", fmt.Sprintf("multipart/alternative;\r\n boundary=%s\r\n", subWriter.Boundary())) // Write the header if err := headerToBytes(buff, header); err != nil { return nil, fmt.Errorf("Failed to render multipart message headers: %s", err) } // Create the body sections if e.Text != "" { header.Set("Content-Type", fmt.Sprintf("text/plain; charset=UTF-8")) header.Set("Content-Transfer-Encoding", "quoted-printable") if _, err := subWriter.CreatePart(header); err != nil { return nil, err } // Write the text if err := quotePrintEncode(buff, e.Text); err != nil { return nil, err } } if e.HTML != "" { header.Set("Content-Type", fmt.Sprintf("text/html; charset=UTF-8")) header.Set("Content-Transfer-Encoding", "quoted-printable") if _, err := subWriter.CreatePart(header); err != nil { return nil, err } // Write the text if err := quotePrintEncode(buff, e.HTML); err != nil { return nil, err } } if err := subWriter.Close(); err != nil { return nil, err } } // Create attachment part, if necessary for _, a := range e.Attachments { ap, err := w.CreatePart(a.Header) if err != nil { return nil, err } // Write the base64Wrapped content to the part base64Wrap(ap, a.Content) } if err := w.Close(); err != nil { return nil, err } return buff.Bytes(), nil } // AttachFile Add attach file to the send mail func (e *Email) AttachFile(args ...string) (a *Attachment, err error) { if len(args) < 1 && len(args) > 2 { err = errors.New("Must specify a file name and number of parameters can not exceed at least two") return } filename := args[0] id := "" if len(args) > 1 { id = args[1] } f, err := os.Open(filename) if err != nil { return } ct := mime.TypeByExtension(filepath.Ext(filename)) basename := path.Base(filename) return e.Attach(f, basename, ct, id) } // Attach is used to attach content from an io.Reader to the email. // Parameters include an io.Reader, the desired filename for the attachment, and the Content-Type. func (e *Email) Attach(r io.Reader, filename string, args ...string) (a *Attachment, err error) { if len(args) < 1 && len(args) > 2 { err = errors.New("Must specify the file type and number of parameters can not exceed at least two") return } c := args[0] //Content-Type id := "" if len(args) > 1 { id = args[1] //Content-ID } var buffer bytes.Buffer if _, err = io.Copy(&buffer, r); err != nil { return } at := &Attachment{ Filename: filename, Header: textproto.MIMEHeader{}, Content: buffer.Bytes(), } // Get the Content-Type to be used in the MIMEHeader if c != "" { at.Header.Set("Content-Type", c) } else { // If the Content-Type is blank, set the Content-Type to "application/octet-stream" at.Header.Set("Content-Type", "application/octet-stream") } if id != "" { at.Header.Set("Content-Disposition", fmt.Sprintf("inline;\r\n filename=\"%s\"", filename)) at.Header.Set("Content-ID", fmt.Sprintf("<%s>", id)) } else { at.Header.Set("Content-Disposition", fmt.Sprintf("attachment;\r\n filename=\"%s\"", filename)) } at.Header.Set("Content-Transfer-Encoding", "base64") e.Attachments = append(e.Attachments, at) return at, nil } // Send will send out the mail func (e *Email) Send() error { if e.Auth == nil { e.Auth = smtp.PlainAuth(e.Identity, e.Username, e.Password, e.Host) } // Merge the To, Cc, and Bcc fields to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc)) to = append(append(append(to, e.To...), e.Cc...), e.Bcc...) // Check to make sure there is at least one recipient and one "From" address if e.From == "" || len(to) == 0 { return errors.New("Must specify at least one From address and one To address") } from, err := mail.ParseAddress(e.From) if err != nil { return err } e.From = from.String() raw, err := e.Bytes() if err != nil { return err } return smtp.SendMail(e.Host+":"+strconv.Itoa(e.Port), e.Auth, from.Address, to, raw) } // quotePrintEncode writes the quoted-printable text to the IO Writer (according to RFC 2045) func quotePrintEncode(w io.Writer, s string) error { var buf [3]byte mc := 0 for i := 0; i < len(s); i++ { c := s[i] // We're assuming Unix style text formats as input (LF line break), and // quoted-printble uses CRLF line breaks. (Literal CRs will become // "=0D", but probably shouldn't be there to begin with!) if c == '\n' { io.WriteString(w, "\r\n") mc = 0 continue } var nextOut []byte if isPrintable(c) { nextOut = append(buf[:0], c) } else { nextOut = buf[:] qpEscape(nextOut, c) } // Add a soft line break if the next (encoded) byte would push this line // to or past the limit. if mc+len(nextOut) >= maxLineLength { if _, err := io.WriteString(w, "=\r\n"); err != nil { return err } mc = 0 } if _, err := w.Write(nextOut); err != nil { return err } mc += len(nextOut) } // No trailing end-of-line?? Soft line break, then. TODO: is this sane? if mc > 0 { io.WriteString(w, "=\r\n") } return nil } // isPrintable returns true if the rune given is "printable" according to RFC 2045, false otherwise func isPrintable(c byte) bool { return (c >= '!' && c <= '<') || (c >= '>' && c <= '~') || (c == ' ' || c == '\n' || c == '\t') } // qpEscape is a helper function for quotePrintEncode which escapes a // non-printable byte. Expects len(dest) == 3. func qpEscape(dest []byte, c byte) { const nums = "0123456789ABCDEF" dest[0] = '=' dest[1] = nums[(c&0xf0)>>4] dest[2] = nums[(c & 0xf)] } // headerToBytes enumerates the key and values in the header, and writes the results to the IO Writer func headerToBytes(w io.Writer, t textproto.MIMEHeader) error { for k, v := range t { // Write the header key _, err := fmt.Fprintf(w, "%s:", k) if err != nil { return err } // Write each value in the header for _, c := range v { _, err := fmt.Fprintf(w, " %s\r\n", c) if err != nil { return err } } } return nil } // base64Wrap encodes the attachment content, and wraps it according to RFC 2045 standards (every 76 chars) // The output is then written to the specified io.Writer func base64Wrap(w io.Writer, b []byte) { // 57 raw bytes per 76-byte base64 line. const maxRaw = 57 // Buffer for each line, including trailing CRLF. var buffer [maxLineLength + len("\r\n")]byte copy(buffer[maxLineLength:], "\r\n") // Process raw chunks until there's no longer enough to fill a line. for len(b) >= maxRaw { base64.StdEncoding.Encode(buffer[:], b[:maxRaw]) w.Write(buffer[:]) b = b[maxRaw:] } // Handle the last chunk of bytes. if len(b) > 0 { out := buffer[:base64.StdEncoding.EncodedLen(len(b))] base64.StdEncoding.Encode(out, b) out = append(out, "\r\n"...) w.Write(out) } }
Go
/////////////////////////////////////////////////////////////////////////////// // Name: src/osx/cocoa/evtloop.mm // Purpose: implementation of wxEventLoop for OS X // Author: Vadim Zeitlin, Stefan Csomor // Modified by: // Created: 2006-01-12 // Copyright: (c) 2006 Vadim Zeitlin <vadim@wxwindows.org> // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // for compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #include "wx/evtloop.h" #ifndef WX_PRECOMP #include "wx/app.h" #include "wx/nonownedwnd.h" #endif // WX_PRECOMP #include "wx/log.h" #include "wx/scopeguard.h" #include "wx/vector.h" #include "wx/hashmap.h" #include "wx/osx/private.h" struct wxModalSessionStackElement { WXWindow dummyWindow; void* modalSession; }; typedef wxVector<wxModalSessionStackElement> wxModalSessionStack; WX_DECLARE_HASH_MAP(wxGUIEventLoop*, wxModalSessionStack*, wxPointerHash, wxPointerEqual, wxModalSessionStackMap); static wxModalSessionStackMap gs_modalSessionStackMap; // ============================================================================ // wxEventLoop implementation // ============================================================================ #if 0 // in case we want to integrate this static NSUInteger CalculateNSEventMaskFromEventCategory(wxEventCategory cat) { // the masking system doesn't really help, as only the lowlevel UI events // are split in a useful way, all others are way to broad if ( (cat | wxEVT_CATEGORY_USER_INPUT) && (cat | (~wxEVT_CATEGORY_USER_INPUT) ) ) return NSAnyEventMask; NSUInteger mask = 0; if ( cat | wxEVT_CATEGORY_USER_INPUT ) { mask |= NSLeftMouseDownMask | NSLeftMouseUpMask | NSRightMouseDownMask | NSRightMouseUpMask | NSMouseMovedMask | NSLeftMouseDraggedMask | NSRightMouseDraggedMask | NSMouseEnteredMask | NSMouseExitedMask | NSScrollWheelMask | NSTabletPointMask | NSTabletProximityMask | NSOtherMouseDownMask | NSOtherMouseUpMask | NSOtherMouseDraggedMask | NSKeyDownMask | NSKeyUpMask | NSFlagsChangedMask | NSEventMaskGesture | NSEventMaskMagnify | NSEventMaskSwipe | NSEventMaskRotate | NSEventMaskBeginGesture | NSEventMaskEndGesture | 0; } if ( cat | (~wxEVT_CATEGORY_USER_INPUT) ) { mask |= NSAppKitDefinedMask | NSSystemDefinedMask | NSApplicationDefinedMask | NSPeriodicMask | NSCursorUpdateMask; } return mask; } #endif wxGUIEventLoop::wxGUIEventLoop() { m_modalSession = nil; m_dummyWindow = nil; m_modalNestedLevel = 0; m_modalWindow = NULL; m_osxLowLevelWakeUp = false; } wxGUIEventLoop::~wxGUIEventLoop() { wxASSERT( gs_modalSessionStackMap.find( this ) == gs_modalSessionStackMap.end() ); wxASSERT( m_modalSession == nil ); wxASSERT( m_dummyWindow == nil ); wxASSERT( m_modalNestedLevel == 0 ); } //----------------------------------------------------------------------------- // events dispatch and loop handling //----------------------------------------------------------------------------- #if 0 bool wxGUIEventLoop::Pending() const { #if 0 // this code doesn't reliably detect pending events // so better return true and have the dispatch deal with it // as otherwise we end up in a tight loop when idle events are responded // to by RequestMore(true) wxMacAutoreleasePool autoreleasepool; return [[NSApplication sharedApplication] nextEventMatchingMask: NSAnyEventMask untilDate: nil inMode: NSDefaultRunLoopMode dequeue: NO] != nil; #else return true; #endif } bool wxGUIEventLoop::Dispatch() { if ( !wxTheApp ) return false; wxMacAutoreleasePool autoreleasepool; if(NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate dateWithTimeIntervalSinceNow: m_sleepTime] inMode:NSDefaultRunLoopMode dequeue: YES]) { WXEVENTREF formerEvent = wxTheApp == NULL ? NULL : wxTheApp->MacGetCurrentEvent(); WXEVENTHANDLERCALLREF formerHandler = wxTheApp == NULL ? NULL : wxTheApp->MacGetCurrentEventHandlerCallRef(); if (wxTheApp) wxTheApp->MacSetCurrentEvent(event, NULL); m_sleepTime = 0.0; [NSApp sendEvent: event]; if (wxTheApp) wxTheApp->MacSetCurrentEvent(formerEvent , formerHandler); } else { if (wxTheApp) wxTheApp->ProcessPendingEvents(); if ( wxTheApp->ProcessIdle() ) m_sleepTime = 0.0 ; else { m_sleepTime = 1.0; #if wxUSE_THREADS wxMutexGuiLeave(); wxMilliSleep(20); wxMutexGuiEnter(); #endif } } return true; } #endif int wxGUIEventLoop::DoDispatchTimeout(unsigned long timeout) { wxMacAutoreleasePool autoreleasepool; if ( m_modalSession ) { NSInteger response = [NSApp runModalSession:(NSModalSession)m_modalSession]; switch (response) { case NSRunContinuesResponse: { if ( [[NSApplication sharedApplication] nextEventMatchingMask: NSAnyEventMask untilDate: [NSDate dateWithTimeIntervalSinceNow: timeout/1000.0] inMode: NSDefaultRunLoopMode dequeue: NO] != nil ) return 1; return -1; } case NSRunStoppedResponse: case NSRunAbortedResponse: return -1; default: // nested native loops may return other codes here, just ignore them break; } return -1; } else { NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate dateWithTimeIntervalSinceNow: timeout/1000.0] inMode:NSDefaultRunLoopMode dequeue: YES]; if ( event == nil ) return -1; [NSApp sendEvent: event]; return 1; } } static int gs_loopNestingLevel = 0; void wxGUIEventLoop::OSXDoRun() { /* In order to properly nest GUI event loops in Cocoa, it is important to have [NSApp run] only as the main/outermost event loop. There are many problems if [NSApp run] is used as an inner event loop. The main issue is that a call to [NSApp stop] is needed to exit an [NSApp run] event loop. But the [NSApp stop] has some side effects that we do not want - such as if there was a modal dialog box with a modal event loop running, that event loop would also get exited, and the dialog would be closed. The call to [NSApp stop] would also cause the enclosing event loop to exit as well. webkit's webcore library uses CFRunLoopRun() for nested event loops. See the log of the commit log about the change in webkit's webcore module: http://www.mail-archive.com/webkit-changes@lists.webkit.org/msg07397.html See here for the latest run loop that is used in webcore: https://github.com/WebKit/webkit/blob/master/Source/WebCore/platform/mac/RunLoopMac.mm CFRunLoopRun() was tried for the nested event loop here but it causes a problem in that all user input is disabled - and there is no way to re-enable it. The caller of this event loop may not want user input disabled (such as synchronous wxExecute with wxEXEC_NODISABLE flag). In order to have an inner event loop where user input can be enabled, the old wxCocoa code that used the [NSApp nextEventMatchingMask] was borrowed but changed to use blocking instead of polling. By specifying 'distantFuture' in 'untildate', we can have it block until the next event. Then we can keep looping on each new event until m_shouldExit is raised to exit the event loop. */ gs_loopNestingLevel++; wxON_BLOCK_EXIT_SET(gs_loopNestingLevel, gs_loopNestingLevel - 1); while ( !m_shouldExit ) { // By putting this inside the loop, we can drain it in each // loop iteration. wxMacAutoreleasePool autoreleasepool; if ( gs_loopNestingLevel == 1 ) { // Use -[NSApplication run] for the main run loop. [NSApp run]; } else { // We use this blocking call to [NSApp nextEventMatchingMask:...] // because the other methods (such as CFRunLoopRun() and [runLoop // runMode:beforeDate] were always disabling input to the windows // (even if we wanted it enabled). // // Here are the other run loops which were tried, but always left // user input disabled: // // [runLoop runMode:NSDefaultRunLoopMode beforeDate:date]; // CFRunLoopRun(); // CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10 , true); // // Using [NSApp nextEventMatchingMask:...] would leave windows // enabled if we wanted them to be, so that is why it is used. NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue: YES]; [NSApp sendEvent: event]; /** The NSApplication documentation states that: " This method is invoked automatically in the main event loop after each event when running in NSDefaultRunLoopMode or NSModalRunLoopMode. This method is not invoked automatically when running in NSEventTrackingRunLoopMode. " So to be safe, we also invoke it here in this event loop. See: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSApplication_Class/Reference/Reference.html */ [NSApp updateWindows]; } } // Wake up the enclosing loop so that it can check if it also needs // to exit. WakeUp(); } void wxGUIEventLoop::OSXDoStop() { // We should only stop the top level event loop. if ( gs_loopNestingLevel <= 1 ) { [NSApp stop:0]; } // For the top level loop only calling stop: is not enough when called from // a runloop-observer, therefore add a dummy event, to make sure the // runloop gets another round. And for the nested loops we need to wake it // up to notice that it should exit, so do this unconditionally. WakeUp(); } void wxGUIEventLoop::WakeUp() { // NSEvent* cevent = [NSApp currentEvent]; // NSString* mode = [[NSRunLoop mainRunLoop] currentMode]; // when already in a mouse event handler, don't add higher level event // if ( cevent != nil && [cevent type] <= NSMouseMoved && ) if ( m_osxLowLevelWakeUp /* [NSEventTrackingRunLoopMode isEqualToString:mode] */ ) { // NSLog(@"event for wakeup %@ in mode %@",cevent,mode); wxCFEventLoop::WakeUp(); } else { wxMacAutoreleasePool autoreleasepool; NSEvent *event = [NSEvent otherEventWithType:NSApplicationDefined location:NSMakePoint(0.0, 0.0) modifierFlags:0 timestamp:0 windowNumber:0 context:nil subtype:0 data1:0 data2:0]; [NSApp postEvent:event atStart:FALSE]; } } CFRunLoopRef wxGUIEventLoop::CFGetCurrentRunLoop() const { NSRunLoop* nsloop = [NSRunLoop currentRunLoop]; return [nsloop getCFRunLoop]; } // TODO move into a evtloop_osx.cpp wxModalEventLoop::wxModalEventLoop(wxWindow *modalWindow) { m_modalWindow = dynamic_cast<wxNonOwnedWindow*> (modalWindow); wxASSERT_MSG( m_modalWindow != NULL, "must pass in a toplevel window for modal event loop" ); m_modalNativeWindow = m_modalWindow->GetWXWindow(); } wxModalEventLoop::wxModalEventLoop(WXWindow modalNativeWindow) { m_modalWindow = NULL; wxASSERT_MSG( modalNativeWindow != NULL, "must pass in a toplevel window for modal event loop" ); m_modalNativeWindow = modalNativeWindow; } // END move into a evtloop_osx.cpp #define OSX_USE_MODAL_SESSION 1 void wxModalEventLoop::OSXDoRun() { wxMacAutoreleasePool pool; // If the app hasn't started, flush the event queue // If we don't do this, the Dock doesn't get the message that // the app has started so will refuse to activate it. [NSApplication sharedApplication]; if (![NSApp isRunning]) { while(NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil inMode:NSDefaultRunLoopMode dequeue:YES]) { [NSApp sendEvent:event]; } } #if OSX_USE_MODAL_SESSION if ( m_modalWindow ) { BeginModalSession(m_modalWindow); wxCFEventLoop::OSXDoRun(); EndModalSession(); } else #endif { [NSApp runModalForWindow:m_modalNativeWindow]; } } void wxModalEventLoop::OSXDoStop() { [NSApp abortModal]; } void wxGUIEventLoop::BeginModalSession( wxWindow* modalWindow ) { WXWindow nsnow = nil; m_modalNestedLevel++; if ( m_modalNestedLevel > 1 ) { wxModalSessionStack* stack = NULL; if ( m_modalNestedLevel == 2 ) { stack = new wxModalSessionStack; gs_modalSessionStackMap[this] = stack; } else { stack = gs_modalSessionStackMap[this]; } wxModalSessionStackElement element; element.dummyWindow = m_dummyWindow; element.modalSession = m_modalSession; stack->push_back(element); // shortcut if nothing changed in this level if ( m_modalWindow == modalWindow ) return; } m_modalWindow = modalWindow; if ( modalWindow ) { // we must show now, otherwise beginModalSessionForWindow does it but it // also would do a centering of the window before overriding all our position if ( !modalWindow->IsShownOnScreen() ) modalWindow->Show(); wxNonOwnedWindow* now = dynamic_cast<wxNonOwnedWindow*> (modalWindow); wxASSERT_MSG( now != NULL, "must pass in a toplevel window for modal event loop" ); nsnow = now ? now->GetWXWindow() : nil; } else { NSRect r = NSMakeRect(10, 10, 0, 0); nsnow = [NSPanel alloc]; [nsnow initWithContentRect:r styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:YES ]; m_dummyWindow = nsnow; [nsnow orderOut:nil]; } m_modalSession = [NSApp beginModalSessionForWindow:nsnow]; wxASSERT_MSG(m_modalSession != NULL, "modal session couldn't be started"); } void wxGUIEventLoop::EndModalSession() { wxASSERT_MSG(m_modalSession != NULL, "no modal session active"); wxASSERT_MSG(m_modalNestedLevel > 0, "incorrect modal nesting level"); --m_modalNestedLevel; if ( m_modalNestedLevel == 0 ) { [NSApp endModalSession:(NSModalSession)m_modalSession]; m_modalSession = nil; if ( m_dummyWindow ) { [m_dummyWindow release]; m_dummyWindow = nil; } } else { wxModalSessionStack* stack = gs_modalSessionStackMap[this]; wxModalSessionStackElement element = stack->back(); stack->pop_back(); if( m_modalNestedLevel == 1 ) { gs_modalSessionStackMap.erase(this); delete stack; } if ( m_modalSession != element.modalSession ) { [NSApp endModalSession:(NSModalSession)m_modalSession]; m_modalSession = element.modalSession; } if ( m_dummyWindow != element.dummyWindow ) { if ( element.dummyWindow ) [element.dummyWindow release]; m_dummyWindow = element.dummyWindow; } } } // // // wxWindowDisabler::wxWindowDisabler(bool disable) { m_modalEventLoop = NULL; m_disabled = disable; if ( disable ) DoDisable(); } wxWindowDisabler::wxWindowDisabler(wxWindow *winToSkip) { m_disabled = true; DoDisable(winToSkip); } void wxWindowDisabler::DoDisable(wxWindow *winToSkip) { // remember the top level windows which were already disabled, so that we // don't reenable them later m_winDisabled = NULL; wxWindowList::compatibility_iterator node; for ( node = wxTopLevelWindows.GetFirst(); node; node = node->GetNext() ) { wxWindow *winTop = node->GetData(); if ( winTop == winToSkip ) continue; // we don't need to disable the hidden or already disabled windows if ( winTop->IsEnabled() && winTop->IsShown() ) { winTop->Disable(); } else { if ( !m_winDisabled ) { m_winDisabled = new wxWindowList; } m_winDisabled->Append(winTop); } } m_modalEventLoop = (wxEventLoop*)wxEventLoopBase::GetActive(); if (m_modalEventLoop) m_modalEventLoop->BeginModalSession(winToSkip); } wxWindowDisabler::~wxWindowDisabler() { if ( !m_disabled ) return; if (m_modalEventLoop) m_modalEventLoop->EndModalSession(); wxWindowList::compatibility_iterator node; for ( node = wxTopLevelWindows.GetFirst(); node; node = node->GetNext() ) { wxWindow *winTop = node->GetData(); if ( !m_winDisabled || !m_winDisabled->Find(winTop) ) { winTop->Enable(); } //else: had been already disabled, don't reenable } delete m_winDisabled; }
Objective-C++
% Use this template for starting initializing the release notes % after a release has just been made. \subsection{Version mf6.5.0---May 23, 2024} \underline{NEW FUNCTIONALITY} \begin{itemize} \item A new Groundwater Energy (GWE) transport model was added to simulate heat transport in the subsurface. GWE Models can be coupled together using a new GWE-GWE Exchange. Additional information for activating the GWE model type within a MODFLOW 6 simulation is available within the mf6io.pdf document. Technical details about the GWE Model are given in the supplemental technical information document (mf6suptechinfo) provided with the release. New example problems have been developed for testing and demonstrating GWE capabilities (in addition to other internal tests that help verify the accuracy of GWE); however, additional changes to the code and input may be necessary in response to user needs and further testing. \item A new Particle Tracking (PRT) Model was added to simulate forward tracking of particles for Groundwater Flow (GWF) Models. Additional information for activating the PRT model type within a MODFLOW 6 simulation is available within the mf6io.pdf document. Technical details about the PRT Model are given in the supplemental technical information document (mf6suptechinfo) provided with the release. New example problems have been developed for testing and demonstrating PRT capabilities (in addition to other internal tests that help verify the accuracy of PRT); however, additional changes to the code and input may be necessary in response to user needs and further testing. \item A new capability has been introduced to optionally write user-provided input arrays to external ASCII files. In some cases, such as when the user provides binary files as input, it can be useful to inspect the text representation of that input. Exporting to external ASCII files can be turned on for supported packages by specifying the EXPORT\_ARRAY\_ASCII option. When activated supported variables will be written to files that are named based on the model, package, variable, and layer. Only those arrays specified for the model grid can be exported. \item Added capability to vary the hydraulic conductivity of the reach streambed (RHK) by stress period in the Streamflow Routing (SFR) package. RHK can be modified by stress period using the BEDK SFRSETTING. RHK can also be defined using a timeseries string in the PACKAGEDATA or PERIOD blocks. \item Extend binary input support to all list style input blocks that have a regular shape and don't contain string fields (e.g. BOUNDNAME). \item A special extended version of MODFLOW can be compiled to simulate multiple models in parallel. This extended version of MODFLOW 6 is based on the Message Passing Interface (MPI) and the Portable, Extensible Toolkit for Scientific Computation (PETSc) libraries. Testing of the extended version has been performed on laptops, desktops, and supercomputers. Information on the extended version of MODFLOW 6 is available through a dedicated page on the \href{https://github.com/MODFLOW-ORG/modflow6/wiki/Parallel-MODFLOW-User-Guide}{MODFLOW 6 repository}. There are several recent improvements to parallel capabilities. A new optional High Performance Computing (HPC) input file can be activated in the OPTION block in the simulation NAM file to configure the load balance for parallel simulations. The CSV convergence report in parallel mode has been improved by adding individual model data similar to those produced for serial simulations. A modified ILU preconditioner is now available in parallel simulations and can be configured through IMS parameters. Settings configured in the IMS input file are now used for parallel simulations. Simulations with multiple GWE Models can be parallelized. \end{itemize} \underline{EXAMPLES} \begin{itemize} \item Examples were added to demonstrate the new Groundwater Energy (GWE) Model. These examples include: danckwerts, geotherm, gwe-prt, and gwe-radial. \item Examples were added to demonstrate the new Particle Tracking (PRT) Model. These examples include two of the test problems used to demonstrate MODPATH Version 7. \end{itemize} \textbf{\underline{BUG FIXES AND OTHER CHANGES TO EXISTING FUNCTIONALITY}} \\ \underline{BASIC FUNCTIONALITY} \begin{itemize} \item When the Adaptive Time Step (ATS) Package was activated, and failed time steps were rerun successfully using a shorter time step, the cumulative budgets reported in the listing files were incorrect. Cumulative budgets included contributions from the failed time steps. The program was fixed so that cumulative budgets are not tallied until the time step is finalized. \item For multi-model groundwater flow simulations that use the Buoyancy (BUY) Package, variable-density terms were not included, in all cases, along the interface between two GWF models. The program was corrected so that flows between two GWF models include the variable-density terms when the BUY Package is active. % \item xxx \end{itemize} %\underline{INTERNAL FLOW PACKAGES} %\begin{itemize} % \item xxx % \item xxx % \item xxx %\end{itemize} \underline{STRESS PACKAGES} \begin{itemize} \item Floating point overflow errors would occur when negative conductance (COND) or auxiliary multiplier (AUXMULT) values were specified in the Drain, River, and General Head stress packages. This bug was fixed by checking if COND and AUXMULT values are greater than or equal to zero. The program will terminate with and error if negative COND or AUXMULT values are found. % \item xxx % \item xxx \end{itemize} \underline{ADVANCED STRESS PACKAGES} \begin{itemize} \item A divide by zero error would occur in the Streamflow Routing package when reaches were deactivated during a simulation. This bug was fixed by checking if the downstream reach is inactive before calculating the flow to the downstream reach. \item When using the mover transport (MVT) package with UZF and UZT, rejected infiltration was paired with the calculated concentration of the UZF object rather than the user-specified concentration assigned to the infiltration. This bug was fixed by instead pairing the rejected infiltration transferred by the MVR and MVT packages with the user-specified concentration assigned in UZTSETTING with the keyword ``INFILTRATION.'' With this change, MODFLOW 6 simulations that use UZF with the ``SIMULATE\_GWSEEP'' option will not transfer this particular source of water with the correct concentration. Instead, the DRN package should be used to simulate groundwater discharge to land surface. By simulating groundwater discharge to land surface with the DRN package and rejected infiltration with the UZF package, the correct concentrations will be assigned to the water transferred by the MVR package. \item The SIMULATE\_GWSEEP variable in the UZF package OPTIONS block will eventually be deprecated. The same functionality may be achieved using an option available within the DRN package called AUXDEPTHNAME. The details of the drainage option are given in the supplemental technical information document (mf6suptechinfo) provided with the release. Deprecation of the SIMULATE\_GWSEEP option is motivated by the potential for errors noted above. \item The capability to deactivate lakes (using the STATUS INACTIVE setting) did not work properly for the GWF Lake Package. The Lake Package was fixed so that inactive lakes have a zero flow value with connected GWF model cells and that the lake stage is assigned the inactive value (1.E30). The listing, budget, and observation files were modified to accurately report inactive lakes. \item The Streamflow Routing package would not calculate groundwater discharge to a reach in cases where the groundwater head is above the top of the reach and the inflow to the reach from upstream reaches, specified inflows, rainfall, and runoff is zero. This bug has been fixed by eliminating the requirement that the conductance calculated based on the initial calculated stage is greater than zero in order to solve for groundwater. As a result, differences in groundwater and surface-water exchange and groundwater heads in existing models may occur. \item The Streamflow Routing package stage tables written to the model listing file have been modified so that inactive reaches are identified to be INACTIVE and dry reaches are identified to be DRY. \item The Streamflow Routing package would not correctly report reach flow terms for unconnected reaches even though reach flows were correctly calculated. This bug has been fixed by modifying the budget routine so that it correctly reports unconnected reach flows in the model listing file and cell-by-cell budget files. Simulated groundwater flow results should not change but differences may be observed in post-processed results and transport simulations that rely on binary cell-by-cell data. % \item xxx \end{itemize} %\underline{SOLUTION} %\begin{itemize} % \item xxx % \item xxx % \item xxx %\end{itemize} \underline{EXCHANGES} \begin{itemize} \item In some cases, concentration instabilities appeared at the interface between two transport models. The artifacts were present for rare configurations connecting more than 2 transport models with identical grids in series. The problem was identified in the GWT-GWT Exchange and corrected. % \item xxx % \item xxx \end{itemize} \underline{PARALLEL} \begin{itemize} \item Several issues were fixed for parallel simulations that used the Buoyancy Package for the GWF model. When a simulation was run with the Buoyancy Package, irrelevant messages could be written to the screen. In some cases, the Buoyancy Package produced strange results at the interface between two models. These issues have been corrected. \item For parallel simulations, calculation of the residual norm used for pseudo-transient continuation (PTC) and backtracking was incorrect. The program was fixed to calculate the correct residual norm. \item Enabling XT3D on exchanges in a parallel simulation caused the program to hang for certain configurations. This issue has been corrected. \item GNC is not supported on flow exchanges when running in parallel or when the XT3D option is enabled on the exchange. The program terminates with an error if the user attempts to use GNC in these cases. \end{itemize}
TeX
:- module(descendent_selecter, []). :- use_module(structure_selecter). :- use_module(descendent_match). :- public amalgame_module/1. :- public selecter/5. :- public parameter/4. amalgame_module(amalgame:'DescendentSelecter'). parameter(steps, integer, 1, 'depth of search, defaults to 1, e.g. direct children only'). parameter(type, oneof([source, target, all]), all, 'Select all descendent matches or pick the best source/target.'). selecter(In, Sel, Dis, Und, Options) :- selecter(descendent_match, In, Sel, Dis, Und, Options).
Prolog
*---------------------------------------------------------------- * Modified by R.T. Jones, C.S. Gauthier to include Bethe-Heitler * muon-pair production by photons, weighted by (emmu/emass)**2 * for purposes of photon beam collimator simulation. * * Chris.S.Gauthier@uconn.edu * Richard.T.Jones@uconn.edu * Hall D Collaboration * June 25, 2002 *---------------------------------------------------------------- * * $Id$ * * $Log$ * Revision 1.2 2002/07/10 14:57:18 jonesrt * - fixed wierd problem with g77 compiler that wanted to interpret "slash star" * in a fortran comment line as a comment indicator a-la-c (complained about * unterminated comment) so I just removed the asterisk - rtj. * - corrected the statistics printout from gelh_last() -rtj. * - changed confusing use of VSCAN (card SCAP) to define the origin for single * particle generation; now gukine.F uses PKINE (card KINE) for both origin * and direction of single-particle generator, with the following format: * KINE kind energy theta phi vertex(1) vertex(2) vertex(3) * - fixed gelh_outp() to remove the BaBar-dependent code so that it correctly * updates the photo-hadronic statistics that get reported at gelh_last() -rtj. * - updated gelhad/Makefile to follow the above changes -rtj. * * Revision 1.1 2002/06/28 19:01:03 jonesrt * Major revision 1.1 -Richard Jones, Chris Gauthier, University of Connecticut * * 1. Added hadronic interactions for photons with the Gelhad package * http://www.slac.stanford.edu/BFROOT/www/Computing/Offline/Simulation/gelhad.html * Routines affected are: * - uginit.F : added new card GELH to set up gelhad parameters and * call to gelh_vrfy() to print out their values. * - uglast.F : added call to gelh_last() to print out summary info. * - gtgama.F : Gelhad replacement for standard Geant routine that adds * simulation of hadronic photoproduction processes. * - gelhad/ : contains a number of new functions (Fortran) and includes * to support the hadronic photoproduction simulation. * * 2. Added muon-pair production by stealing every (Melectron/Mmuon)**2 pair * production events and trying to convert to muon pairs. The deficit in * e+/e- events resulting from this theft is negligible. The angular * distribution of muon pairs is generated using the general Geant method * in gpairg.F with the electron mass replaced by the muon mass. * Routines affected are: * - gpairg.F : added a switch to replace e+/e- with mu+/mu- in a small * fraction of the pair-production vertices. * * Revision 1.5 1998/02/09 15:59:47 japost * Fixed a problem on AIX 4 xlf, caused by max(double,float). * * Revision 1.4 1998/02/06 16:46:57 japost * Fix a wrong parenthesis. * * Revision 1.3 1998/02/06 16:22:24 japost * Protected a square root from a negative argument. * This root was added there in previous changes, and not deleted from its * old position. In its old position it was protected from being negative, but in * its new position it was not. * * Deleted the same square root from its old position, as it was redundant. * * Revision 1.2 1996/03/13 12:03:24 ravndal * Tranverse momentum conservation * * Revision 1.1.1.1 1995/10/24 10:21:28 cernlib * Geant * * #include "geant321/pilot.h" *CMZ : 3.21/04 21/02/95 11.53.59 by S.Giani *-- Author : #if defined(CERNLIB_HPUX) $OPTIMIZE OFF #endif SUBROUTINE GPAIRG C. C. ****************************************************************** C. * * C. * Simulates e+e- pair production by photons. * C. * * C. * The secondary electron energies are sampled using the * C. * Coulomb corrected BETHE-HEITLER cross-sections.For this the * C. * modified version of the random number techniques of * C. * BUTCHER and MESSEL (NUCL.PHYS,20(1960),15) are employed. * C. * * C. * NOTE : * C. * (1) Effects due to the breakdown of the BORN approximation at * C. * low energies are ignored. * C. * (2) The differential cross-section implicitly takes account * C. * of pair production in both nuclear and atomic electron * C. * fields. However, triplet production is not generated. * C. * * C. * ==>Called by : GTGAMA * C. * Authors G.Patrick, L.Urban ********* * C. * * C. ****************************************************************** C. #include "geant321/gcbank.inc" #include "geant321/gcjloc.inc" #include "geant321/gconsp.inc" #include "geant321/gctrak.inc" #include "geant321/gcking.inc" #include "geant321/gcphys.inc" #include "geant321/gccuts.inc" DIMENSION NTYPEL(2) DIMENSION RNDM(2) LOGICAL ROTATE PARAMETER (ONE=1,ONETHR=ONE/3,EMAS2=REAL(2*EMASS)) c c Here we take over the standard Geant3 e+e- pair production cross section c as a good approximation to the total l+l- lepton pair production cross c section. The only change is to convert a fraction (emmu/emass)**2 from c electron to muon pairs, if allowed by energy conservation. c real xsratio parameter (xsratio=REAL((emass/emmu)**2)) real mlepton integer lepton call grndm(rndm,1) if (rndm(1).lt.xsratio) then lepton = 5 mlepton = REAL(EMMU) else lepton = 2 mlepton = REAL(EMASS) endif C. C. ------------------------------------------------------------------ C. C If not enough energy : no pair production C EGAM = VECT(7) IF (EGAM.LT.mlepton*2) GO TO 999 C KCASE = NAMEC(6) IF(IPAIR.NE.1) THEN ISTOP = 2 NGKINE = 0 DESTEP = DESTEP + EGAM VECT(7)= 0. GEKIN = 0. GETOT = 0. GO TO 999 ENDIF C C For low energy photons approximate the electron energy by C sampling from a uniform distribution in the interval C EMASS -> EGAM/2. C IF (EGAM.LE.mlepton*4)THEN CALL GRNDM(RNDM,1) EEL1 = mlepton + (RNDM(1)*(0.5*EGAM - mlepton)) X=EEL1/EGAM GO TO 20 ENDIF C Z3=Q(JPROB+2) F=8.*Q(JPROB+3) IF(EGAM.GT.mlepton*10) F=F+8.*Q(JPROB+4) X0=mlepton/EGAM DX=0.5-X0 DMIN=544.*X0/Z3 DMIN2=DMIN*DMIN IF(DMIN.LE.1.)THEN F10=42.392-7.796*DMIN+1.961*DMIN2-F F20=41.405-5.828*DMIN+0.8945*DMIN2-F ELSE F10=42.24-8.368*LOG(DMIN+0.952)-F F20=F10 ENDIF C C Calculate limit for screening variable,DELTA, to ensure C that screening rejection functions always remain C positive. C DMAX=EXP((42.24-F)/8.368)-0.952 C C Differential cross-section factors which form C the coefficients of the screening functions. C DSIG1=DX*DX*F10/3. DSIG2=0.5*F20 BPAR = DSIG1 / (DSIG1 + DSIG2) C C Decide which screening rejection function to use and C sample the electron/photon fractional energy BR. C 10 CALL GRNDM(RNDM,2) IF(RNDM(1).LT.BPAR)THEN X=0.5-DX*RNDM(2)**ONETHR IREJ=1 ELSE X=X0+DX*RNDM(2) IREJ = 2 ENDIF C C Calculate DELTA ensuring positivity. C D=0.25*DMIN/(X*(1.-X)) IF(D.GE.DMAX) GOTO 10 D2=D*D C C Calculate F1 and F2 functions using approximations. C F10 and F20 are the F1 and F2 functions calculated for the C DELTA=DELTA minimum. C IF(D.LE.1.)THEN F1=42.392-7.796*D+1.961*D2-F F2=41.405-5.828*D+0.8945*D2-F ELSE F1=42.24-8.368*LOG(D+0.952)-F F2=F1 ENDIF IF(IREJ.NE.2)THEN SCREJ=F1/F10 ELSE SCREJ=F2/F20 ENDIF C C Accept or reject on basis of random variate. C CALL GRNDM(RNDM,1) IF(RNDM(1).GT.SCREJ) GOTO 10 EEL1=X*EGAM C C Successful sampling of first electron energy. C C Select charges randomly. C 20 NTYPEL(1) = lepton CALL GRNDM(RNDM,2) IF (RNDM(1).GT.0.5) NTYPEL(1) = lepton+1 NTYPEL(2) = 2*lepton+1 - NTYPEL(1) C C Generate electron decay angles with respect to a Z-axis C defined along the parent photon. C PHI is generated isotropically and THETA is assigned C a universal angular distribution C EMASS1 = mlepton THETA = GBTETH(EEL1, EMASS1, X)*mlepton/EEL1 SINTH = SIN(THETA) COSTH = COS(THETA) PHI = REAL(TWOPI*RNDM(2)) COSPHI = COS(PHI) SINPHI = SIN(PHI) C C Rotate tracks into GEANT system C CALL GFANG(VECT(4),COSAL,SINAL,COSBT,SINBT,ROTATE) C C Polar co-ordinates to momentum components. C NGKINE = 0 TEL1 = EEL1 - mlepton PEL1 = SQRT(MAX((EEL1+REAL(mlepton))*TEL1,0.)) IF(TEL1.GT.CUTELE) THEN NGKINE = NGKINE + 1 GKIN(1,NGKINE) = PEL1 * SINTH * COSPHI GKIN(2,NGKINE) = PEL1 * SINTH * SINPHI GKIN(3,NGKINE) = PEL1 * COSTH GKIN(4,NGKINE) = EEL1 GKIN(5,NGKINE) = NTYPEL(1) TOFD(NGKINE)=0. GPOS(1,NGKINE) = VECT(1) GPOS(2,NGKINE) = VECT(2) GPOS(3,NGKINE) = VECT(3) IF(ROTATE) + CALL GDROT(GKIN(1,NGKINE),COSAL,SINAL,COSBT,SINBT) ELSE DESTEP = DESTEP + TEL1 IF(NTYPEL(1).EQ.2) CALL GANNI2 ENDIF C C Momentum vector of second electron. Recoil momentum of C target nucleus/electron ignored. C EEL2=EGAM-EEL1 TEL2=EEL2-mlepton IF(TEL2.GT.CUTELE) THEN PEL2 = SQRT((EEL2+mlepton)*TEL2) NGKINE = NGKINE + 1 SINTH=SINTH*PEL1/PEL2 COSTH=SQRT(MAX(0.,1.-SINTH**2)) GKIN(1,NGKINE)=-PEL2*SINTH*COSPHI GKIN(2,NGKINE)=-PEL2*SINTH*SINPHI GKIN(3,NGKINE)=PEL2*COSTH GKIN(4,NGKINE)=EEL2 GKIN(5,NGKINE) = NTYPEL(2) TOFD(NGKINE)=0. GPOS(1,NGKINE) = VECT(1) GPOS(2,NGKINE) = VECT(2) GPOS(3,NGKINE) = VECT(3) IF(ROTATE) + CALL GDROT(GKIN(1,NGKINE),COSAL,SINAL,COSBT,SINBT) ELSE DESTEP = DESTEP + TEL2 IF(NTYPEL(2).EQ.2) CALL GANNI2 ENDIF ISTOP = 1 IF(NGKINE.EQ.0) ISTOP = 2 999 END #if defined(CERNLIB_HPUX) $OPTIMIZE ON #endif
Fortran Free Form
-module(catch_expr_fail). -export([foo/1]). -spec foo(nok) -> ok. foo(X) -> A = (catch X), A.
Erlang
Bugfix: Fix missing quotes on OCIS-Storage Etags have to be enclosed in quotes ". Return correct etags on OCIS-Storage. https://github.com/owncloud/product/issues/237 https://github.com/cs3org/reva/pull/1232
GCC Machine Description
[ { "id": "1", "minute": "0", "hour": "7", "day_of_month": "*", "month": "*", "day_of_week": "*", "week_num": "*", "message": "おはよう!\n朝だよ!", "base_minute_duration": "5", "time": "2018-07-12 07:00:00", "expected": "true" }, { "id": "2", "minute": "0", "hour": "23", "day_of_month": "*", "month": "*", "day_of_week": "1", "week_num": "*", "message": "明日は火曜日!", "base_minute_duration": "5", "time": "2018-07-09 23:01:00", "expected": "true" }, { "id": "3", "minute": "0", "hour": "23", "day_of_month": "*", "month": "*", "day_of_week": "3", "week_num": "*", "message": "明日は木曜日!", "base_minute_duration": "5", "time": "2018-07-11 23:02:00", "expected": "true" }, { "id": "4", "minute": "0", "hour": "23", "day_of_month": "*", "month": "*", "day_of_week": "2", "week_num": "2", "message": "明日は第二水曜日!", "base_minute_duration": "5", "time": "2018-07-10 23:03:00", "expected": "true" }, { "id": "5", "minute": "0", "hour": "23", "day_of_month": "*", "month": "*", "day_of_week": "3", "week_num": "*", "message": "明日は木曜日!", "base_minute_duration": "5", "time": "2018-07-11 23:04:00", "expected": "true" }, { "id": "6", "minute": "0", "hour": "23", "day_of_month": "*", "month": "*", "day_of_week": "2", "week_num": "*", "message": "明日は水曜日!", "base_minute_duration": "5", "time": "2018-07-10 23:05:00", "expected": "false" }, { "id": "7", "minute": "0", "hour": "23", "day_of_month": "*", "month": "*", "day_of_week": "0", "week_num": "*", "message": "明日は月曜日!", "base_minute_duration": "5", "time": "2018-07-08 22:00:00", "expected": "false" }, { "id": "8", "minute": "0", "hour": "23", "day_of_month": "*", "month": "*", "day_of_week": "2", "week_num": "4", "message": "明日は第四水曜日!", "base_minute_duration": "5", "time": "2018-07-10 23:00:00", "expected": "false" }, { "id": "9", "minute": "0", "hour": "23", "day_of_month": "*", "month": "*", "day_of_week": "*", "week_num": "*", "message": "にゃーん", "base_minute_duration": "5", "time": "2018-07-12 23:00:00", "expected": "true" }, { "id": "10", "minute": "0", "hour": "23", "day_of_month": "*", "month": "*", "day_of_week": "*", "week_num": "*", "message": "にゃーん", "base_minute_duration": "5", "time": "2018-07-12 23:05:00", "expected": "false" } ]
JSON
#!/usr/bin/env bash #---------------------------------------------------------------- # thredds_download.sh # # download scenario data from thredds #---------------------------------------------------------------- # Copyright(C) 2021 Jason Fleming # # This file is part of the ADCIRC Surge Guidance System (ASGS). # # The ASGS 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. # # ASGS 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 the ASGS. If not, see <http://www.gnu.org/licenses/>. #---------------------------------------------------------------- #http://tds.renci.org:8080/thredds/fileServer/2021/nam/2021020700/hsofs/hatteras.renci.org/hsofs-nam-bob-2021/nowcast/fort.61.nc meteorology="nam" server="tds.renci.org:8080" mesh="hsofs" hpcenv="hatteras.renci.org" instancename="hsofs-nam-bob-2021" files=( "fort.61.nc" "fort.15" "run.properties" ) scenarios=( "nowcast" "namforecast" ) for year in 2021; do #echo "year is $year" for month in 01 02 ; do day=1 # find the number of days in the month (including leap days) month_days=`cal $month $year | egrep -v [a-z] | wc -w` while [[ $day -le $month_days ]]; do daystring=`printf "%02d" $day` #echo "daystring is $daystring" for hour in 00 06 12 18 ; do #echo "hour is $hour" for scenario in "${scenarios[@]}" ; do #echo "scenario is $scenario" dir="$year/$meteorology/$year$month$daystring$hour/$mesh/$hpcenv/$instancename/$scenario" #echo "dir is $dir" localdir="./$dir" #echo "localdir is $localdir" mkdir -p $localdir for f in "${files[@]}" ; do echo "f is $f" url="http://$server//thredds/fileServer/$dir/$f" echo "url is $url" curl -O $url # if this is a netcdf file, check to see if we downloaded a real netcdf file successfully echo "checking to see if this is a netcdf file" if [[ ${f##*.} == "nc" ]]; then echo "this is a netcdf file" l=`ncdump -k $f 2>&1` echo $l if [[ $l == *"NetCDF: Unknown file format"* ]]; then echo "unknown" rm $f break fi else echo "not a netcdf file" fi # copy the file into a local directory echo "moving $f to $localdir" mv $f $localdir done done done day=`expr $day + 1` done done done
Shell
#!/usr/bin/env python # encoding: utf-8 r""" Run diff on all files in two directories, primarily used for comparing libraries. This is not quite done yet! Use at your own risk... """ import sys import getopt import glob import os import time help_message = ''' Run diff on all files in two directories, primarily used for comparing libraries. Arguments - compare_lib dir1 dir2 [-p --pattern match pattern] [-d --diff diff program] ''' class Usage(Exception): def __init__(self, msg): self.msg = msg def main(argv=None): if argv is None: argv = sys.argv try: try: opts, args = getopt.getopt(argv[3:], "hp:d:", ["help", "pattern=","diff="]) except getopt.error, msg: raise Usage(msg) # Defaults pattern = "*.f" diff = "diff" # These are required dir1 = argv[1] dir2 = argv[2] # option processing for option, value in opts: if option in ("-h", "--help"): raise Usage(help_message) if option in ("-p", "--pattern"): pattern = value if option in ("-d", "--diff"): diff = value except Usage, err: print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg) print >> sys.stderr, "\t for help use --help" return 2 os.chdir(dir1) print "In directory ",dir1 for fname in glob.glob(pattern): f2 = dir2 + '/' + fname[:-6] + '.f' if os.path.isfile(f2): print 'comparing %s to %s' % (fname,f2) os.system('%s -w %s %s' % (diff,fname,f2)) else: print 'no file %s ' % f2 time.sleep(1) if __name__ == "__main__": sys.exit(main())
Python
# Makefile for CUDA test programs # Makefile gfortran compiler with MacOS X CARBON = /System/Library/Frameworks/Carbon.framework/Carbon #FC90 = gfortran #CC = gcc #OPTS90 = -O3 #CCOPTS = -O3 #CUDA #LOPTS = -L/usr/lib/gcc/i686-apple-darwin9/4.0.1 -lstdc++ #LOPTS = -L/usr/lib/gcc/i686-apple-darwin9/4.2.1 -lstdc++ #LOPTS = -L/usr/lib/gcc/i686-apple-darwin10/4.2.1 -lstdc++ #LOPTS = -L/usr/lib/gcc/i686-apple-darwin10/4.2.1/x86_64 -lstdc++ #CULIBS = $(CARBON) -lSystemStubs -L/usr/local/cuda/lib -lcuda -lcudart #normal CUDA #NVOPTS = -O3 #NVOPTS = -O3 -m64 #debug CUDA #NVOPTS = -O -deviceemu # Makefile gfortran compiler with Linux FC90 = gfortran CC = gcc OPTS90 = -O3 CCOPTS = -O3 #CUDA LOPTS = CULIBS = -L/usr/local/cuda/lib64 -lcuda -lcudart #CULIBS = -L/usr/local/cuda/lib -lcuda -lcudart #CULIBS = -L/u/local/cuda/4.0.17/lib64 -lcuda -lcudart #normal CUDA NVOPTS = -O3 #debug CUDA #NVOPTS = -O -deviceemu # CUOBJS = gpumain_cu.o dtimer.o FCUOBJS = gpumain_cuf.o dtimer.o # Linkage rules all: cuda cuda: cgputest_cu fgputest_cu #CUDA cgputest_cu : cgputest_cu.o $(CUOBJS) $(CC) $(CCOPTS) $(LOPTS) -o cgputest_cu cgputest_cu.o \ $(CUOBJS) $(CULIBS) fgputest_cu : fgputest_cu.o $(CUOBJS) $(FC90) $(OPTS90) $(LOPTS) -o fgputest_cu fgputest_cu.o \ $(CUOBJS) $(CULIBS) # Compilation rules dtimer.o : dtimer.c $(CC) $(CCOPTS) -c dtimer.c #CUDA gpumain_cu.o : gpumain_cu.cu nvcc $(NVOPTS) -c gpumain_cu.cu -I/usr/local/cuda/include cgputest_cu.o : cgputest_cu.c $(CC) $(CCOPTS) -c cgputest_cu.c fgputest_cu.o : fgputest_cu.f90 $(FC90) $(OPTS90) -c fgputest_cu.f90 clean: rm -f *.o *.mod clobber: clean rm -f *gputest_cu
Makefile
module tb_mplieru8x8; integer test_vector; wire [15:0] raw_product; integer product; mplieru8x8 unit(raw_product, test_vector[15:8], test_vector[7:0]); initial begin $display("begin"); for(test_vector = 16'h0000; test_vector[16] != 1; test_vector = test_vector + 1) begin product = test_vector[15:8] * test_vector[7:0]; #10; if(product != raw_product && product < 17'h10000) $display("ERROR: %dx%d != %d, %d", test_vector[15:8], test_vector[7:0], raw_product, product); $display("%dx%d=%d, %d", test_vector[15:8], test_vector[7:0], raw_product, product); end $display("end"); end endmodule
Coq
package br.com.nglauber.marvel.model.api import br.com.nglauber.marvel.extensions.md5 import br.com.nglauber.marvel.model.api.entity.API_KEY import br.com.nglauber.marvel.model.api.entity.PRIVATE_KEY import br.com.nglauber.marvel.model.api.entity.Response import com.google.gson.GsonBuilder import io.reactivex.Observable import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Query import java.util.* interface MarvelApi { @GET("characters") fun allCharacters(@Query("offset") offset: Int? = 0): Observable<Response> companion object { fun getService(): MarvelApi { val logging = HttpLoggingInterceptor() logging.level = HttpLoggingInterceptor.Level.BODY val httpClient = OkHttpClient.Builder() httpClient.addInterceptor(logging) httpClient.addInterceptor { chain -> val original = chain.request() val originalHttpUrl = original.url() val ts = (Calendar.getInstance(TimeZone.getTimeZone("UTC")).timeInMillis / 1000L).toString() val url = originalHttpUrl.newBuilder() .addQueryParameter("apikey", API_KEY) .addQueryParameter("ts", ts) .addQueryParameter("hash", "$ts$PRIVATE_KEY$API_KEY".md5()) .build() chain.proceed(original.newBuilder().url(url).build()) } val gson = GsonBuilder().setLenient().create() val retrofit = Retrofit.Builder() .baseUrl("http://gateway.marvel.com/v1/public/") .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .client(httpClient.build()) .build() return retrofit.create<MarvelApi>(MarvelApi::class.java) } } }
Kotlin
H.mean<-function(x){ x<-na.omit(x) n<-nrow(as.matrix(x)) ((1/n)*sum(1/x))^-1}
R
import { Component, OnInit } from '@angular/core'; import { HttpClient,HttpHeaders, HttpRequest, HttpParams, HttpResponse } from '@angular/common/http'; import { Router, ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-menu', templateUrl: './menu.page.html', styleUrls: ['./menu.page.scss'], }) export class MenuPage implements OnInit { constructor(private http: HttpClient, private route: Router, private param: ActivatedRoute) { } cat = []; recette = []; categorie = " "; ngOnInit() { console.log(this.param.snapshot.paramMap.get('nom')); this.get(this.param.snapshot.paramMap.get('nom')); this.getCat(this.param.snapshot.paramMap.get('nom')); } get(nom){ this.http.get('http://localhost:4000/categorie/' +nom).subscribe((response) => { console.log(response['result']); this.recette = response['result']; }); } // recuperer la categorie de la recette getCat(nom){ this.http.get('http://localhost:4000/categorie/seul/' +nom).subscribe((response) => { console.log(response['result'][0]); this.categorie = response['result'][0]['categorie']; }); } // creation de la fonction choix Choix(id){ this.route.navigate(['/details/' + id]); } }
TypeScript
[package] org = "wso2" name = "foo" version = "0.1.0"
TOML
!-----------------------------egs5_lshell.f----------------------------- ! Version: 051219-1435 ! Reference: SLAC-R-730/KEK-2005-8 !----------------------------------------------------------------------- !23456789|123456789|123456789|123456789|123456789|123456789|123456789|12 subroutine lshell(ll) implicit none include 'include/egs5_h.f' ! Main EGS5 "header" file include 'include/egs5_bounds.f' ! COMMONs required by EGS5 code include 'include/egs5_edge.f' include 'include/egs5_epcont.f' include 'include/egs5_media.f' include 'include/egs5_misc.f' include 'include/egs5_photin.f' include 'include/egs5_stack.f' include 'include/egs5_uphiot.f' include 'include/egs5_useful.f' include 'include/counters.f' ! Additional (non-EGS5) COMMONs real*8 rnnow ! Arguments integer ll integer ickflg ! Local variables ilshell = ilshell + 1 ! Count entry into subroutine ickflg = 0 if (ll .eq. 2) go to 1 if (ll .eq. 3) go to 2 call randomset(rnnow) ebind = eedge(2,iz)*1.E-3 if (rnnow .gt. omegal1(iz)) then if (rnnow .le. omegal1(iz) + f12(iz)) then ickflg = 1 go to 1 else if (rnnow .le. omegal1(iz) + f12(iz) + f13(iz)) then ickflg = 1 go to 2 else ! ============== call lauger(1) ! ============== end if else ! ============= call lxray(1) ! ============= end if return 1 continue call randomset(rnnow) if (ickflg .eq. 0) then ebind = eedge(3,iz)*1.E-3 end if if (rnnow .gt. omegal2(iz)) then if (rnnow .le. omegal2(iz) + f23(iz)) then ickflg = 1 go to 2 else ! ============== call lauger(2) ! ============== end if else ! ============= call lxray(2) ! ============= end if return 2 continue if (ickflg .eq. 0) ebind = eedge(4,iz)*1.E-3 call randomset(rnnow) if (rnnow .gt. omegal3(iz)) then ! ============== call lauger(3) ! ============== else ! ============= call lxray(3) ! ============= end if return end !-----------------------last line of egs5_lshell.f----------------------
Fortran Free Form
%% Copyright (c) 2017, Loïc Hoguin <essen@ninenines.eu> %% %% Permission to use, copy, modify, and/or distribute this software for any %% purpose with or without fee is hereby granted, provided that the above %% copyright notice and this permission notice appear in all copies. %% %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -module(rest_handler_SUITE). -compile(export_all). -compile(nowarn_export_all). -import(ct_helper, [config/2]). -import(ct_helper, [doc/1]). -import(cowboy_test, [gun_open/1]). %% ct. all() -> cowboy_test:common_all(). groups() -> cowboy_test:common_groups(ct_helper:all(?MODULE)). init_per_group(Name, Config) -> cowboy_test:init_common_groups(Name, Config, ?MODULE). end_per_group(Name, _) -> cowboy:stop_listener(Name). %% Dispatch configuration. init_dispatch(_) -> cowboy_router:compile([{'_', [ {"/switch_handler", switch_handler_h, run}, {"/switch_handler_opts", switch_handler_h, hibernate} ]}]). %% Internal. do_decode(Headers, Body) -> case lists:keyfind(<<"content-encoding">>, 1, Headers) of {_, <<"gzip">>} -> zlib:gunzip(Body); _ -> Body end. %% Tests. switch_handler(Config) -> doc("Switch REST to loop handler for streaming the response body."), ConnPid = gun_open(Config), Ref = gun:get(ConnPid, "/switch_handler", [{<<"accept-encoding">>, <<"gzip">>}]), {response, nofin, 200, Headers} = gun:await(ConnPid, Ref), {ok, Body} = gun:await_body(ConnPid, Ref), <<"Hello\nstreamed\nworld!\n">> = do_decode(Headers, Body), ok. switch_handler_opts(Config) -> doc("Switch REST to loop handler for streaming the response body; with options."), ConnPid = gun_open(Config), Ref = gun:get(ConnPid, "/switch_handler_opts", [{<<"accept-encoding">>, <<"gzip">>}]), {response, nofin, 200, Headers} = gun:await(ConnPid, Ref), {ok, Body} = gun:await_body(ConnPid, Ref), <<"Hello\nstreamed\nworld!\n">> = do_decode(Headers, Body), ok.
Erlang
package com.simplemobiletools.calendar.fragments import android.content.Intent import android.content.res.Resources import android.graphics.PorterDuff import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.app.AlertDialog import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.DatePicker import android.widget.RelativeLayout import android.widget.TextView import com.simplemobiletools.calendar.R import com.simplemobiletools.calendar.activities.DayActivity import com.simplemobiletools.calendar.extensions.config import com.simplemobiletools.calendar.extensions.getAppropriateTheme import com.simplemobiletools.calendar.helpers.* import com.simplemobiletools.calendar.interfaces.MonthlyCalendar import com.simplemobiletools.calendar.interfaces.NavigationListener import com.simplemobiletools.calendar.models.Day import com.simplemobiletools.commons.extensions.adjustAlpha import com.simplemobiletools.commons.extensions.beGone import com.simplemobiletools.commons.extensions.beVisibleIf import com.simplemobiletools.commons.extensions.setupDialogStuff import kotlinx.android.synthetic.main.first_row.* import kotlinx.android.synthetic.main.fragment_month.view.* import kotlinx.android.synthetic.main.top_navigation.view.* import org.joda.time.DateTime class MonthFragment : Fragment(), MonthlyCalendar { private var mPackageName = "" private var mTextColor = 0 private var mWeakTextColor = 0 private var mSundayFirst = false private var mDayCode = "" private var mListener: NavigationListener? = null lateinit var mRes: Resources lateinit var mHolder: RelativeLayout lateinit var mConfig: Config lateinit var mCalendar: MonthlyCalendarImpl override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater!!.inflate(R.layout.fragment_month, container, false) mRes = resources mHolder = view.calendar_holder mDayCode = arguments.getString(DAY_CODE) mConfig = context.config mSundayFirst = mConfig.isSundayFirst setupButtons() mPackageName = activity.packageName setupLabels() mCalendar = MonthlyCalendarImpl(this, context) val padding = resources.getDimension(R.dimen.activity_margin).toInt() view.calendar_holder.setPadding(padding, padding, padding, padding) return view } override fun onResume() { super.onResume() if (mConfig.isSundayFirst != mSundayFirst) { mSundayFirst = mConfig.isSundayFirst setupLabels() } mCalendar.apply { mTargetDate = Formatter.getDateTimeFromCode(mDayCode) getDays() // prefill the screen asap, even if without events } updateCalendar() } fun updateCalendar() { mCalendar.updateMonthlyCalendar(Formatter.getDateTimeFromCode(mDayCode)) } override fun updateMonthlyCalendar(month: String, days: List<Day>) { activity?.runOnUiThread { mHolder.top_value.text = month mHolder.top_value.setTextColor(mConfig.textColor) updateDays(days) } } fun setListener(listener: NavigationListener) { mListener = listener } private fun setupButtons() { val baseColor = mConfig.textColor mTextColor = baseColor mWeakTextColor = baseColor.adjustAlpha(LOW_ALPHA) mHolder.apply { top_left_arrow.drawable.mutate().setColorFilter(mTextColor, PorterDuff.Mode.SRC_ATOP) top_right_arrow.drawable.mutate().setColorFilter(mTextColor, PorterDuff.Mode.SRC_ATOP) top_left_arrow.background = null top_right_arrow.background = null top_left_arrow.setOnClickListener { mListener?.goLeft() } top_right_arrow.setOnClickListener { mListener?.goRight() } top_value.setOnClickListener { showMonthDialog() } } } fun showMonthDialog() { activity.setTheme(context.getAppropriateTheme()) val view = getLayoutInflater(arguments).inflate(R.layout.date_picker, null) val datePicker = view.findViewById(R.id.date_picker) as DatePicker datePicker.findViewById(Resources.getSystem().getIdentifier("day", "id", "android")).beGone() val dateTime = DateTime(mCalendar.mTargetDate.toString()) datePicker.init(dateTime.year, dateTime.monthOfYear - 1, 1, null) AlertDialog.Builder(context) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.ok) { dialog, which -> positivePressed(dateTime, datePicker) } .create().apply { context.setupDialogStuff(view, this) } } private fun positivePressed(dateTime: DateTime, datePicker: DatePicker) { val month = datePicker.month + 1 val year = datePicker.year val newDateTime = dateTime.withDate(year, month, 1) mListener?.goToDateTime(newDateTime) } private fun setupLabels() { val letters = letterIDs for (i in 0..6) { var index = i if (!mSundayFirst) index = (index + 1) % letters.size (mHolder.findViewById(mRes.getIdentifier("label_$i", "id", mPackageName)) as TextView).apply { setTextColor(mTextColor) text = getString(letters[index]) } } } private fun updateDays(days: List<Day>) { val displayWeekNumbers = mConfig.displayWeekNumbers val len = days.size if (week_num == null) return week_num.setTextColor(mTextColor) week_num.beVisibleIf(displayWeekNumbers) for (i in 0..5) { (mHolder.findViewById(mRes.getIdentifier("week_num_$i", "id", mPackageName)) as TextView).apply { text = "${days[i * 7 + 3].weekOfYear}:" setTextColor(mTextColor) beVisibleIf(displayWeekNumbers) } } val weakerText = mTextColor.adjustAlpha(MEDIUM_ALPHA) val todayCircle = resources.getDrawable(R.drawable.circle_empty) todayCircle.setColorFilter(weakerText, PorterDuff.Mode.SRC_IN) val eventDot = resources.getDrawable(R.drawable.monthly_day_dot) eventDot.setColorFilter(weakerText, PorterDuff.Mode.SRC_IN) val todayWithEvent = resources.getDrawable(R.drawable.monthly_day_with_event_today) todayWithEvent.setColorFilter(weakerText, PorterDuff.Mode.SRC_IN) for (i in 0..len - 1) { val day = days[i] var curTextColor = mWeakTextColor if (day.isThisMonth) { curTextColor = mTextColor } (mHolder.findViewById(mRes.getIdentifier("day_$i", "id", mPackageName)) as TextView).apply { text = day.value.toString() setTextColor(curTextColor) setOnClickListener { openDay(day.code) } background = if (!day.isThisMonth) { null } else if (day.isToday && day.hasEvent) { todayWithEvent } else if (day.isToday) { todayCircle } else if (day.hasEvent) { eventDot } else { null } } } } private fun openDay(code: String) { if (code.isEmpty()) return Intent(context, DayActivity::class.java).apply { putExtra(DAY_CODE, code) startActivity(this) } } }
Kotlin
defmodule MemoryWeb.GamesChannelTest do use MemoryWeb.ChannelCase setup do {:ok, _, socket} = socket(MemoryWeb.UserSocket, "user_id", %{some: :assign}) |> subscribe_and_join(MemoryWeb.GamesChannel, "games:lobby") {:ok, socket: socket} end test "ping replies with status ok", %{socket: socket} do ref = push socket, "ping", %{"hello" => "there"} assert_reply ref, :ok, %{"hello" => "there"} end test "shout broadcasts to games:lobby", %{socket: socket} do push socket, "shout", %{"hello" => "all"} assert_broadcast "shout", %{"hello" => "all"} end test "broadcasts are pushed to the client", %{socket: socket} do broadcast_from! socket, "broadcast", %{"some" => "data"} assert_push "broadcast", %{"some" => "data"} end end
Elixir
#Energy, Pressure 143.71066557412786, 3.2658643639986167 155.65346067061978, 5.7039530758374895 163.18455160833292, 13.548212505341212 162.60523692081654, 0.9688078621279601 191.57097129663646, 28.37904468412944 204.3158944219972, 34.02548199557168 211.26767067219396, 35.56217063096426 239.0747756729811, 51.60805894006296 251.81969879834185, 57.64760264660572 285.419950674293, 75.69475987621547 298.1648737996537, 81.87725136279471 332.9237550506376, 100.74635832761453 345.66867817599837, 107.14327148424854 379.2689300519494, 125.79795677901359 392.01385317731024, 132.33781771568414 426.77273442829403, 152.02887441571391 439.5176575536549, 158.74742007743004 473.1179094296059, 178.1168442723777 485.86283255496664, 184.90686382411212 520.6217138059505, 205.0267638642514 533.3666369313113, 212.0312050860406 566.9668888072624, 232.11536818117077 579.7118119326232, 239.15554634796905 614.4706931836071, 259.8115005632453 627.2156163089678, 266.8516787300436 660.8158681849189, 287.32894822027424 673.5607913102797, 294.4763372220999 707.1610431862308, 315.2037653273944 719.9059663115916, 322.315417384211 754.6648475625755, 343.61463660965154 767.4097706879361, 350.7262886664681 958.0043028808311, 468.76541803161933 960.9008763184131, 459.3308645492094 988.7079813192004, 488.49221167665826 997.9770163194626, 493.9242273180458
CSV
import "compactor" import "config" local task = require "cbclua.task" local time_full = 25 --open, then extend function tribbles() --need to alter when i find if motor or servo commands are blocking open() extend_full() close_half() close({wait = true}) retract_full() end function tribbles_pvc() close_half() close() end function tribbles_pvc_full() tribbles_pvc() task.sleep(0.5) extend(0.5) end function tribbles_pvc_bk(inches) close_half({wait = true}) drive:bk{inches = inches} close() end function botguy_pvc() extend_full() close_half() drive:bk{inches = 2.5} close() retract() end function release() open() drive:bk{inches = 3} end
Lua
/***************************************************************************** Copyright (c) 2014, Intel Corp. All rights reserved. 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 Intel Corporation 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. ***************************************************************************** * Contents: Native middle-level C interface to LAPACK function dgttrs * Author: Intel Corporation * Generated November 2015 *****************************************************************************/ #include "lapacke_utils.h" lapack_int LAPACKE_dgttrs_work( int matrix_layout, char trans, lapack_int n, lapack_int nrhs, const double* dl, const double* d, const double* du, const double* du2, const lapack_int* ipiv, double* b, lapack_int ldb ) { lapack_int info = 0; if( matrix_layout == LAPACK_COL_MAJOR ) { /* Call LAPACK function and adjust info */ LAPACK_dgttrs( &trans, &n, &nrhs, dl, d, du, du2, ipiv, b, &ldb, &info ); if( info < 0 ) { info = info - 1; } } else if( matrix_layout == LAPACK_ROW_MAJOR ) { lapack_int ldb_t = MAX(1,n); double* b_t = NULL; /* Check leading dimension(s) */ if( ldb < nrhs ) { info = -11; LAPACKE_xerbla( "LAPACKE_dgttrs_work", info ); return info; } /* Allocate memory for temporary array(s) */ b_t = (double*)LAPACKE_malloc( sizeof(double) * ldb_t * MAX(1,nrhs) ); if( b_t == NULL ) { info = LAPACK_TRANSPOSE_MEMORY_ERROR; goto exit_level_0; } /* Transpose input matrices */ LAPACKE_dge_trans( matrix_layout, n, nrhs, b, ldb, b_t, ldb_t ); /* Call LAPACK function and adjust info */ LAPACK_dgttrs( &trans, &n, &nrhs, dl, d, du, du2, ipiv, b_t, &ldb_t, &info ); if( info < 0 ) { info = info - 1; } /* Transpose output matrices */ LAPACKE_dge_trans( LAPACK_COL_MAJOR, n, nrhs, b_t, ldb_t, b, ldb ); /* Release memory and exit */ LAPACKE_free( b_t ); exit_level_0: if( info == LAPACK_TRANSPOSE_MEMORY_ERROR ) { LAPACKE_xerbla( "LAPACKE_dgttrs_work", info ); } } else { info = -1; LAPACKE_xerbla( "LAPACKE_dgttrs_work", info ); } return info; }
C
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Exercise3 where import Data.Monoid import Data.Char import JoinList newtype Score = Score Int deriving (Eq, Ord, Show, Num) instance Monoid Score where mempty = Score 0 mappend = (+) score :: Char -> Score score c | isLower c = score . toUpper $ c | elem c "EAIONRTLSU" = Score 1 | elem c "DG" = Score 2 | elem c "BCMP" = Score 3 | elem c "FHVWY" = Score 4 | elem c "K" = Score 5 | elem c "JX" = Score 8 | elem c "QZ" = Score 10 | otherwise = mempty scoreString :: String -> Score scoreString = foldr (\a b -> (score a) <> b) mempty scoreLine :: String -> JoinList Score String scoreLine "" = Empty scoreLine x = Single (scoreString x) x
Haskell
\documentclass[12pt]{article} \begin{document} $$ \rho = \displaystyle\sum\limits_{i} f_i $$ $$ \rho u_{\alpha} = \displaystyle\sum\limits_{i} f_i e_{i\alpha} $$ \end{document}
TeX
package ru.pavkin.ihavemoney.frontend.styles import scalacss.Defaults._ import scala.language.postfixOps object Global extends StyleSheet.Standalone { import dsl._ "body" - ( paddingTop(80 px) ) ".form-group" -( &("button") - ( marginRight(15 px) ), &(".form-control") - ( marginBottom(10 px) ) ) }
Scala
!vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvC ! C ! Module name: SET_INDEX1A3(I, J, K, IJK, IMJK, IPJK, IJMK, IJPK, C ! IJKM, IJKP, IJKW, IJKE, IJKS, IJKN, C ! IJKB, IJKT) C ! Purpose: Set the indices of the neighbors of cell ijk (brute force) C ! C ! Author: M. Syamlal Date: 21-JAN-92 C ! Reviewer:M. Syamlal, S. Venkatesan, P. Nicoletti, Date: 29-JAN-92 C ! W. Rogers C ! C ! Revision Number: 1 C ! Purpose: Modify index computations for K for setting periodic C ! boundary conditions in a cylindrical geometry where z goes C ! from 0 to 2 pi C ! Author: M. Syamlal Date: 10-MAR-92 C ! Revision Number: 2 C ! Purpose: Calculate only the nearest neighbor indices.( for code C ! optimization) C ! Author: M. Syamlal Date: 23-SEP-92 C ! Reviewer: M. Syamlal Date: 11-DEC-92 C ! C ! Literature/Document References: C ! C ! Variables referenced: I, J, K, IJK C ! C ! Variables modified: IJKM, IJMK, IMJK, IPJK, IJPK, IJKP, IJKW, IJKE, C ! IJKS, IJKN, IJKB, IJKT C ! C ! Local variables: None C ! C !^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^C ! SUBROUTINE SET_INDEX1A3(I, J, K, IJK, IMJK, IPJK, IJMK, IJPK, IJKM, IJKP, & IJKW, IJKE, IJKS, IJKN, IJKB, IJKT) !...Translated by Pacific-Sierra Research VAST-90 2.06G5 12:17:31 12/09/98 !...Switches: -xf ! ! Include param.inc file to specify parameter values ! !----------------------------------------------- ! M o d u l e s !----------------------------------------------- USE param USE param1 USE physprop USE geometry USE compar USE fldvar USE indices USE functions USE function3 IMPLICIT NONE !----------------------------------------------- ! G l o b a l P a r a m e t e r s !----------------------------------------------- !----------------------------------------------- ! D u m m y A r g u m e n t s !----------------------------------------------- INTEGER I, J, K, IJK, IMJK, IPJK, IJMK, IJPK, IJKM, IJKP, IJKW, IJKE, & IJKS, IJKN, IJKB, IJKT !----------------------------------------------- ! L o c a l P a r a m e t e r s !----------------------------------------------- !----------------------------------------------- IMJK = UNDEFINED_I IPJK = UNDEFINED_I IJMK = UNDEFINED_I IJPK = UNDEFINED_I IJKM = UNDEFINED_I IJKP = UNDEFINED_I IF(IM1_3(I).NE.UNDEFINED_I) THEN IMJK = BOUND_FUNIJK3(IM1_3(I),J,K) ENDIF IF(IP1_3(I).NE.UNDEFINED_I) THEN IPJK = BOUND_FUNIJK3(IP1_3(I),J,K) ENDIF IF(JM1_3(J).NE.UNDEFINED_I) THEN IJMK = BOUND_FUNIJK3(I,JM1_3(J),K) ENDIF IF(JP1_3(J).NE.UNDEFINED_I) THEN IJPK = BOUND_FUNIJK3(I,JP1_3(J),K) ENDIF IF(KM1_3(K).NE.UNDEFINED_I) THEN IJKM = BOUND_FUNIJK3(I,J,KM1_3(K)) ENDIF IF(KP1_3(K).NE.UNDEFINED_I) THEN IJKP = BOUND_FUNIJK3(I,J,KP1_3(K)) ENDIF ! RETURN END SUBROUTINE SET_INDEX1A3 !// Comments on the modifications for DMP version implementation !// Modified calls to BOUND_FUNIJK to have a self consistent formulation
Fortran Free Form
Public Class HelpDeskRegistro Inherits System.Web.UI.Page Dim ObjHelpDesk As New clsHelpDesk Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Try If Session("permisos") Is Nothing Then Response.Redirect("~/entrada.aspx?ReturnUrl=" & Request.RawUrl) End If Pnl_Message.CssClass = Nothing lblmsg.Text = Nothing If Not IsPostBack Then Session("Formulario") = "Registro Help Desk" With drlCanal .DataSource = ObjHelpDesk.Consulta_Canal .DataTextField = "Nombre" .DataValueField = "Cod_HelpDesk_Canal" .DataBind() End With With drlArea .DataSource = ObjHelpDesk.Consulta_Area .DataTextField = "Nombre" .DataValueField = "Cod_HelpDesk_Complemento" .DataBind() End With End If Catch ex As Exception Pnl_Message.CssClass = "alert alert-danger" lblmsg.Text = "<span class='glyphicon glyphicon-remove-sign'></span>" & ex.Message End Try End Sub Protected Sub BtnNuevoTicket_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnNuevoTicket.Click Limpiar() ScriptManager.RegisterStartupScript(Page, GetType(Page), "P", "Plegar_panel();", True) Pnl_Message.CssClass = Nothing lblmsg.Text = Nothing End Sub Protected Sub BtnConsultaTicket_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnConsultaTicket.Click Limpiar() PanelConsulta.Visible = True Pnl_Message.CssClass = Nothing lblmsg.Text = Nothing End Sub Protected Sub btnConsultaCaso_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnConsultaCaso.Click Try Consultar_Tickets() Catch ex As Exception Pnl_Message.CssClass = "alert alert-danger" lblmsg.Text = "<span class='glyphicon glyphicon-remove-sign'></span>" & ex.Message Finally ScriptManager.RegisterStartupScript(Page, GetType(Page), "P", "Pleg_Loading();", True) End Try End Sub 'Public Sub EnviarCorreo() ' Try ' Dim correo As New System.Net.Mail.MailMessage ' ''De ' correo.From = New System.Net.Mail.MailAddress(CType(Session("permisos"), clsusuario).usuario + "@comunicaciones-moviles.com") ' ''Para ' correo.To.Add("helpdesk@comunicaciones-moviles.com") ' ''Asunto ' correo.Subject = TxtTema.Text ' ''Cometarios ' correo.Body = "OBSERVACION: " + txtObservacion.Text + ". PERSONA REPORTA: " + TxtPersona_Reporta.Text + ". MODULO: " + drlLetraModulo.SelectedItem.ToString + TxtNumeroModulo.Text ' correo.IsBodyHtml = False ' correo.Priority = System.Net.Mail.MailPriority.Normal ' ''Hots para enviar el correo ' Dim smtp As New System.Net.Mail.SmtpClient ' smtp.Host = "smtp.comunicaciones-moviles.com" ' ''Autenticacion o credenciales del correo que recive el mensaje ' smtp.Credentials = New System.Net.NetworkCredential("helpdesk@comunicaciones-moviles.com", "Helpk2014*") ' smtp.Send(correo) ' Catch ex As Exception ' Pnl_Message.CssClass = "alert alert-danger" ' lblmsg.Text = "<span class='glyphicon glyphicon-remove-sign'></span>" & ex.Message ' End Try 'End Sub Public Sub AutoAsignacion() Try ObjHelpDesk.Cod_HelpDesk_Registro = ObjHelpDesk.Cod_HelpDesk_Registro ObjHelpDesk.Asignado = CType(Session("permisos"), clsusuario).usuario ObjHelpDesk.Asigna = CType(Session("permisos"), clsusuario).usuario ObjHelpDesk.ObservacionAsigna = "Auto Asignacion" ObjHelpDesk.Prioridad = Nothing ObjHelpDesk.Fk_Cod_Categoria = Nothing ObjHelpDesk.Fk_Cod_Tipo = Nothing ObjHelpDesk.UpdateTicketAsignado() Catch ex As Exception Pnl_Message.CssClass = "alert alert-danger" lblmsg.Text = "<span class='glyphicon glyphicon-remove-sign'></span>" & ex.Message End Try End Sub Protected Sub BtnEnviar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnEnviar.Click Try If TxtTema.Text = "" Then Pnl_Message.CssClass = "alert alert-warning" lblmsg.Text = "<span class='glyphicon glyphicon-warning-sign'></span> Ingrese un Tema" Exit Sub End If If txtObservacion.Text = "" Then Pnl_Message.CssClass = "alert alert-warning" lblmsg.Text = "<span class='glyphicon glyphicon-warning-sign'></span> Ingrese una Observacion" Exit Sub End If If drlPrioridad.Text = "1" Then Pnl_Message.CssClass = "alert alert-warning" lblmsg.Text = "<span class='glyphicon glyphicon-warning-sign'></span> Elija una priorodad" Exit Sub End If If drlCanal.Text = "1" Then Pnl_Message.CssClass = "alert alert-warning" lblmsg.Text = "<span class='glyphicon glyphicon-warning-sign'></span> Elija un canal" Exit Sub End If If drlLetraModulo.Text = "1" Then ObjHelpDesk.Modulo = "" Else If TxtNumeroModulo.Text = "" Then Pnl_Message.CssClass = "alert alert-warning" lblmsg.Text = "<span class='glyphicon glyphicon-warning-sign'></span> Ingrese el numero del modulo o cambie la letra del modulo a seleccion" Exit Sub Else ObjHelpDesk.Modulo = drlLetraModulo.Text + TxtNumeroModulo.Text End If End If If TxtPersona_Reporta.Text = "" Then Pnl_Message.CssClass = "alert alert-warning" lblmsg.Text = "<span class='glyphicon glyphicon-warning-sign'></span> Ingrese el Nombre de quien reporta el ticket" Exit Sub End If If drlArea.SelectedItem.ToString = "- Seleccione -" Then Pnl_Message.CssClass = "alert alert-warning" lblmsg.Text = "<span class='glyphicon glyphicon-warning-sign'></span> Elija un Area" Exit Sub End If ObjHelpDesk.Id_Usuario = CType(Session("permisos"), clsusuario).usuario ObjHelpDesk.Prioridad = drlPrioridad.Text ObjHelpDesk.Tema = TxtTema.Text ObjHelpDesk.Observacion = txtObservacion.Text ObjHelpDesk.Estado = "Abierto" ObjHelpDesk.Fk_Cod_Canal = drlCanal.Text ObjHelpDesk.Persona_Reporta = TxtPersona_Reporta.Text ObjHelpDesk.Fk_Cod_Complemento_Area = drlArea.Text ObjHelpDesk.IngresarTicket() Dim A As DataSet A = ObjHelpDesk.Codigo_Registro() Pnl_Message.CssClass = "alert alert-success" lblmsg.Text = "<span class='glyphicon glyphicon-ok-sign'></span> El ticket se a registrado con el codigo: " + ObjHelpDesk.Cod_HelpDesk_Registro.ToString ObjHelpDesk.Id_Usuario = CType(Session("permisos"), clsusuario).usuario Dim dts As New DataSet dts = ObjHelpDesk.Consulta_Tecnico_AutoAsigna() If dts.Tables(0).Rows.Count > 0 Then AutoAsignacion() End If 'EnviarCorreo() Limpiar() Catch ex As Exception Pnl_Message.CssClass = "alert alert-danger" lblmsg.Text = "<span class='glyphicon glyphicon-remove-sign'></span>" & ex.Message Finally ScriptManager.RegisterStartupScript(Page, GetType(Page), "P", "Pleg_Loading();", True) End Try End Sub Protected Sub dtgTicket_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles dtgTicket.PageIndexChanging Try dtgTicket.DataSource = Session("DtT_Tickets") dtgTicket.PageIndex = e.NewPageIndex dtgTicket.DataBind() Catch ex As Exception Pnl_Message.CssClass = "alert alert-danger" lblmsg.Text = "<span class='glyphicon glyphicon-remove-sign'></span> Se produjo error " + ex.Message End Try End Sub Protected Sub dtgProceso_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles dtgProceso.PageIndexChanging Try If TxtCodTicket.Text = "" Then Pnl_Message.CssClass = "alert alert-warning" lblmsg.Text = "<span class='glyphicon glyphicon-warning-sign'></span> Ingrese alguna opcion de filtro antes de consultar" Exit Sub End If Pnl_Message.CssClass = Nothing lblmsg.Text = Nothing If TxtCodTicket.Text <> Nothing Then ObjHelpDesk.Cod_HelpDesk_Registro = TxtCodTicket.Text dtgProceso.DataSource = ObjHelpDesk.Consulta_Proceso() dtgProceso.DataBind() lblCuentaProceso.Text = ObjHelpDesk.Cantidad End If dtgProceso.DataSource = ObjHelpDesk.Consulta_Proceso() dtgProceso.PageIndex = e.NewPageIndex dtgProceso.DataBind() Catch ex As Exception Pnl_Message.CssClass = "alert alert-danger" lblmsg.Text = "<span class='glyphicon glyphicon-remove-sign'></span>" & ex.Message End Try End Sub Protected Sub dtgTicket_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles dtgTicket.RowCommand Try Dim index As Integer = Convert.ToInt32(e.CommandArgument) If e.CommandName = "Calificar" Then If dtgTicket.Rows(index).Cells(dtgTicket.Columns.Count - 3).Text <> "&nbsp;" Then Pnl_Message.CssClass = "alert alert-info" lblmsg.Text = "<span class='glyphicon glyphicon-info-sign'></span> El ticket ya se encuentra calificado!" Else Session("Cod_Ticket") = dtgTicket.Rows(index).Cells(0).Text Cargar_Drl_Calificacion() ScriptManager.RegisterStartupScript(Page, GetType(Page), "Plegar", "PlegDes_Dinamico('#Desp_Calif', 'slide', '', '', '');", True) End If End If Catch ex As Exception Pnl_Message.CssClass = "alert alert-danger" lblmsg.Text = "<span class='glyphicon glyphicon-remove-sign'></span>" & ex.Message End Try End Sub Protected Sub Btn_Calificar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Btn_Calificar.Click Try ObjHelpDesk.Cod_Calificacion = Drl_Calificacion.SelectedValue ObjHelpDesk.Descripcion = Txb_Observacion.Text ObjHelpDesk.Cod_HelpDesk_Registro = Session("Cod_Ticket") ObjHelpDesk.Actualizar_Ticket() ScriptManager.RegisterStartupScript(Page, GetType(Page), "Plegar", "PlegDes_Dinamico('#Desp_Calif', 'show', '', '', '');PlegDes_Dinamico('#Desp_Calif', 'slide', '', '', '');", True) ObjHelpDesk.Cod_HelpDesk_Registro = Nothing Consultar_Tickets() Pnl_Message.CssClass = "alert alert-success" lblmsg.Text = "<span class='glyphicon glyphicon-ok-sign'></span> Calificación exitosa" Catch ex As Exception Pnl_Message.CssClass = "alert alert-danger" lblmsg.Text = "<span class='glyphicon glyphicon-remove-sign'></span> Ha ocurrido un error durante o despues de calificar!" End Try End Sub Protected Sub Cargar_Drl_Calificacion() With Drl_Calificacion .DataSource = ObjHelpDesk.Consultar_Complementos(Nothing, Nothing, "Calificacion") .DataTextField = "Nombre" .DataValueField = "Cod_HelpDesk_Complemento" .DataBind() End With End Sub Protected Sub Consultar_Tickets() Session("DtT_Tickets") = New DataTable Session("DtT_Gestiones") = New DataTable Try ObjHelpDesk.Id_Usuario = CType(Session("permisos"), clsusuario).usuario ObjHelpDesk.Cod_Ticket = TxtCodTicket.Text If TxtCodTicket.Text <> Nothing Then Consultar_Gestiones() End If ObjHelpDesk.Fecha_Inicio = TxtFecha_Inicio.Text ObjHelpDesk.Fecha_Fin = TxtFecha_Fin.Text Session("DtT_Tickets") = ObjHelpDesk.Consultar_Tickets("").Tables(0) lblCuentaTicket.Text = Session("DtT_Tickets").Rows.Count dtgTicket.DataSource = Session("DtT_Tickets") dtgTicket.DataBind() If Session("DtT_Tickets").Rows.Count > 0 Then PanelConsulta2.Visible = True Else PanelConsulta2.Visible = False Pnl_Message.CssClass = "alert alert-info" lblmsg.Text = "<span class='glyphicon glyphicon-info-sign'></span> No se encontraron registros que coincidan con su criterio de busqueda!" End If Catch ex As Exception Pnl_Message.CssClass = "alert alert-danger" lblmsg.Text = "<span class='glyphicon glyphicon-remove-sign'></span>" & ex.Message End Try End Sub Private Sub Consultar_Gestiones() Try Session("Dts_Gestiones") = ObjHelpDesk.Consultar_Gestiones().Tables(0) dtgProceso.DataSource = Session("Dts_Gestiones") dtgProceso.DataBind() lblCuentaProceso.Text = Session("Dts_Gestiones").rows.count Catch ex As Exception Pnl_Message.CssClass = "alert alert-danger" lblmsg.Text = "<span class='glyphicon glyphicon-remove-sign'></span> Se presento error consultando las gestiones" & ex.Message End Try End Sub Public Sub Limpiar() 'PanelConsulta TxtFecha_Inicio.Text = Nothing TxtFecha_Fin.Text = Nothing TxtCodTicket.Text = Nothing lblCuentaTicket.Text = Nothing lblCuentaProceso.Text = Nothing dtgTicket.DataSource = Nothing dtgTicket.DataBind() dtgProceso.DataSource = Nothing dtgProceso.DataBind() PanelConsulta2.Visible = False 'PanelRegistro TxtTema.Text = Nothing drlPrioridad.SelectedIndex = 0 drlLetraModulo.SelectedIndex = 0 drlArea.SelectedIndex = 0 txtObservacion.Text = Nothing drlCanal.SelectedIndex = 0 TxtNumeroModulo.Text = Nothing TxtPersona_Reporta.Text = Nothing End Sub End Class
VBA
// // AppDelegate.swift // MultiViews // // Created by Administrator on 7/15/14. // Copyright (c) 2014 Administrator. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
Swift
//This file was auto-corrected by findeclaration.exe on 25.5.2012 20:42:31 /obj/machinery/computer/med_data//TODO:SANITY name = "medical records console" desc = "This can be used to check medical records." icon_keyboard = "med_key" icon_screen = "medcomp" req_one_access = list(access_medical, access_forensics_lockers) circuit = /obj/item/weapon/circuitboard/med_data var/obj/item/weapon/card/id/scan = null var/authenticated = null var/rank = null var/screen = null var/datum/data/record/active1 = null var/datum/data/record/active2 = null var/a_id = null var/temp = null var/printing = null light_color = LIGHT_COLOR_DARKBLUE /obj/machinery/computer/med_data/attack_ai(user as mob) return src.attack_hand(user) /obj/machinery/computer/med_data/attack_hand(mob/user as mob) if(..()) return var/dat if(src.temp) dat = text("<TT>[src.temp]</TT><BR><BR><A href='?src=[UID()];temp=1'>Clear Screen</A>") else dat = text("Confirm Identity: <A href='?src=[UID()];scan=1'>[]</A><HR>", (src.scan ? text("[]", src.scan.name) : "----------")) if(src.authenticated) switch(src.screen) if(1.0) dat += {" <A href='?src=[UID()];search=1'>Search Records</A> <BR><A href='?src=[UID()];screen=2'>List Records</A> <BR> <BR><A href='?src=[UID()];screen=5'>Virus Database</A> <BR><A href='?src=[UID()];screen=6'>Medbot Tracking</A> <BR> <BR><A href='?src=[UID()];screen=3'>Record Maintenance</A> <BR><A href='?src=[UID()];logout=1'>{Log Out}</A><BR> "} if(2.0) dat += "<B>Record List</B>:<HR>" if(!isnull(data_core.general)) for(var/datum/data/record/R in sortRecord(data_core.general)) dat += text("<A href='?src=[UID()];d_rec=\ref[]'>[]: []</A><BR>", R, R.fields["id"], R.fields["name"]) //Foreach goto(132) dat += "<HR><A href='?src=[UID()];screen=1'>Back</A>" if(3.0) dat += "<B>Records Maintenance</B><HR>\n<A href='?src=[UID()];back=1'>Backup To Disk</A><BR>\n<A href='?src=[UID()];u_load=1'>Upload From disk</A><BR>\n<A href='?src=[UID()];del_all=1'>Delete All Records</A><BR>\n<BR>\n<A href='?src=[UID()];screen=1'>Back</A>" if(4.0) dat += "<CENTER><B>Medical Record</B></CENTER><BR>" if((istype(src.active1, /datum/data/record) && data_core.general.Find(src.active1))) dat += "<table><tr><td>Name: [active1.fields["name"]] \ ID: [active1.fields["id"]]<BR>\n \ Sex: <A href='?src=[UID()];field=sex'>[active1.fields["sex"]]</A><BR>\n \ Age: <A href='?src=[UID()];field=age'>[active1.fields["age"]]</A><BR>\n \ Fingerprint: <A href='?src=[UID()];field=fingerprint'>[active1.fields["fingerprint"]]</A><BR>\n \ Physical Status: <A href='?src=[UID()];field=p_stat'>[active1.fields["p_stat"]]</A><BR>\n \ Mental Status: <A href='?src=[UID()];field=m_stat'>[active1.fields["m_stat"]]</A><BR></td><td align = center valign = top> \ Photo:<br><img src=[active1.fields["photo-south"]] height=64 width=64 border=5> \ <img src=[active1.fields["photo-west"]] height=64 width=64 border=5></td></tr></table>" else dat += "<B>General Record Lost!</B><BR>" if((istype(src.active2, /datum/data/record) && data_core.medical.Find(src.active2))) dat += text("<BR>\n<CENTER><B>Medical Data</B></CENTER><BR>\nBlood Type: <A href='?src=[UID()];field=b_type'>[]</A><BR>\nDNA: <A href='?src=[UID()];field=b_dna'>[]</A><BR>\n<BR>\nMinor Disabilities: <A href='?src=[UID()];field=mi_dis'>[]</A><BR>\nDetails: <A href='?src=[UID()];field=mi_dis_d'>[]</A><BR>\n<BR>\nMajor Disabilities: <A href='?src=[UID()];field=ma_dis'>[]</A><BR>\nDetails: <A href='?src=[UID()];field=ma_dis_d'>[]</A><BR>\n<BR>\nAllergies: <A href='?src=[UID()];field=alg'>[]</A><BR>\nDetails: <A href='?src=[UID()];field=alg_d'>[]</A><BR>\n<BR>\nCurrent Diseases: <A href='?src=[UID()];field=cdi'>[]</A> (per disease info placed in log/comment section)<BR>\nDetails: <A href='?src=[UID()];field=cdi_d'>[]</A><BR>\n<BR>\nImportant Notes:<BR>\n\t<A href='?src=[UID()];field=notes'>[]</A><BR>\n<BR>\n<CENTER><B>Comments/Log</B></CENTER><BR>", src.active2.fields["b_type"], src.active2.fields["b_dna"], src.active2.fields["mi_dis"], src.active2.fields["mi_dis_d"], src.active2.fields["ma_dis"], src.active2.fields["ma_dis_d"], src.active2.fields["alg"], src.active2.fields["alg_d"], src.active2.fields["cdi"], src.active2.fields["cdi_d"], src.active2.fields["notes"]) var/counter = 1 while(src.active2.fields[text("com_[]", counter)]) dat += text("[]<BR><A href='?src=[UID()];del_c=[]'>Delete Entry</A><BR><BR>", src.active2.fields[text("com_[]", counter)], counter) counter++ dat += "<A href='?src=[UID()];add_c=1'>Add Entry</A><BR><BR>" dat += "<A href='?src=[UID()];del_r=1'>Delete Record (Medical Only)</A><BR><BR>" else dat += "<B>Medical Record Lost!</B><BR>" dat += text("<A href='?src=[UID()];new=1'>New Record</A><BR><BR>") dat += "\n<A href='?src=[UID()];print_p=1'>Print Record</A><BR>\n<A href='?src=[UID()];screen=2'>Back</A><BR>" if(5.0) dat += "<CENTER><B>Virus Database</B></CENTER>" for(var/Dt in typesof(/datum/disease/)) var/datum/disease/Dis = new Dt(0) if(istype(Dis, /datum/disease/advance)) continue // TODO (tm): Add advance diseases to the virus database which no one uses. if(!Dis.desc) continue dat += "<br><a href='?src=[UID()];vir=[Dt]'>[Dis.name]</a>" dat += "<br><a href='?src=[UID()];screen=1'>Back</a>" if(6.0) dat += "<center><b>Medical Robot Monitor</b></center>" dat += "<a href='?src=[UID()];screen=1'>Back</a>" dat += "<br><b>Medical Robots:</b>" var/bdat = null for(var/mob/living/simple_animal/bot/medbot/M in world) if(M.z != src.z) continue //only find medibots on the same z-level as the computer var/turf/bl = get_turf(M) if(bl) //if it can't find a turf for the medibot, then it probably shouldn't be showing up bdat += "[M.name] - <b>\[[bl.x],[bl.y]\]</b> - [M.on ? "Online" : "Offline"]<br>" if((!isnull(M.reagent_glass)) && M.use_beaker) bdat += "Reservoir: \[[M.reagent_glass.reagents.total_volume]/[M.reagent_glass.reagents.maximum_volume]\]<br>" else bdat += "Using Internal Synthesizer.<br>" if(!bdat) dat += "<br><center>None detected</center>" else dat += "<br>[bdat]" else else dat += "<A href='?src=[UID()];login=1'>{Log In}</A>" var/datum/browser/popup = new(user, "med_rec", name, 400, 400) popup.set_content(dat) popup.open(0) onclose(user, "med_rec") return /obj/machinery/computer/med_data/Topic(href, href_list) if(..()) return 1 if(!( data_core.general.Find(src.active1) )) src.active1 = null if(!( data_core.medical.Find(src.active2) )) src.active2 = null if((usr.contents.Find(src) || (in_range(src, usr) && istype(src.loc, /turf))) || (istype(usr, /mob/living/silicon))) usr.set_machine(src) if(href_list["temp"]) src.temp = null if(href_list["scan"]) if(src.scan) if(ishuman(usr)) scan.loc = usr.loc if(!usr.get_active_hand()) usr.put_in_hands(scan) scan = null else src.scan.loc = src.loc src.scan = null else var/obj/item/I = usr.get_active_hand() if(istype(I, /obj/item/weapon/card/id)) usr.drop_item() I.loc = src src.scan = I else if(href_list["logout"]) src.authenticated = null src.screen = null src.active1 = null src.active2 = null else if(href_list["login"]) if(istype(usr, /mob/living/silicon/ai)) src.active1 = null src.active2 = null src.authenticated = usr.name src.rank = "AI" src.screen = 1 else if(istype(usr, /mob/living/silicon/robot)) src.active1 = null src.active2 = null src.authenticated = usr.name var/mob/living/silicon/robot/R = usr src.rank = "[R.modtype] [R.braintype]" src.screen = 1 else if(istype(src.scan, /obj/item/weapon/card/id)) src.active1 = null src.active2 = null if(src.check_access(src.scan)) src.authenticated = src.scan.registered_name src.rank = src.scan.assignment src.screen = 1 if(src.authenticated) if(href_list["screen"]) src.screen = text2num(href_list["screen"]) if(src.screen < 1) src.screen = 1 src.active1 = null src.active2 = null if(href_list["vir"]) var/type = href_list["vir"] var/datum/disease/Dis = new type(0) var/AfS = "" for(var/mob/M in Dis.viable_mobtypes) AfS += " [initial(M.name)];" src.temp = {"<b>Name:</b> [Dis.name] <BR><b>Number of stages:</b> [Dis.max_stages] <BR><b>Spread:</b> [Dis.spread_text] Transmission <BR><b>Possible Cure:</b> [(Dis.cure_text||"none")] <BR><b>Affected Lifeforms:</b>[AfS] <BR> <BR><b>Notes:</b> [Dis.desc] <BR> <BR><b>Severity:</b> [Dis.severity]"} if(href_list["del_all"]) src.temp = "Are you sure you wish to delete all records?<br>\n\t<A href='?src=[UID()];temp=1;del_all2=1'>Yes</A><br>\n\t<A href='?src=[UID()];temp=1'>No</A><br>" if(href_list["del_all2"]) for(var/datum/data/record/R in data_core.medical) //R = null qdel(R) //Foreach goto(494) src.temp = "All records deleted." if(href_list["field"]) var/a1 = src.active1 var/a2 = src.active2 switch(href_list["field"]) if("fingerprint") if(istype(src.active1, /datum/data/record)) var/t1 = copytext(trim(sanitize(input("Please input fingerprint hash:", "Med. records", src.active1.fields["fingerprint"], null) as text)),1,MAX_MESSAGE_LEN) if((!( t1 ) || !( src.authenticated ) || usr.stat || usr.restrained() || (!in_range(src, usr) && (!istype(usr, /mob/living/silicon))) || src.active1 != a1)) return src.active1.fields["fingerprint"] = t1 if("sex") if(istype(src.active1, /datum/data/record)) if(src.active1.fields["sex"] == "Male") src.active1.fields["sex"] = "Female" else src.active1.fields["sex"] = "Male" if("age") if(istype(src.active1, /datum/data/record)) var/t1 = input("Please input age:", "Med. records", src.active1.fields["age"], null) as num if((!( t1 ) || !( src.authenticated ) || usr.stat || usr.restrained() || (!in_range(src, usr) && (!istype(usr, /mob/living/silicon))) || src.active1 != a1)) return src.active1.fields["age"] = t1 if("mi_dis") if(istype(src.active2, /datum/data/record)) var/t1 = copytext(trim(sanitize(input("Please input minor disabilities list:", "Med. records", src.active2.fields["mi_dis"], null) as text)),1,MAX_MESSAGE_LEN) if((!( t1 ) || !( src.authenticated ) || usr.stat || usr.restrained() || (!in_range(src, usr) && (!istype(usr, /mob/living/silicon))) || src.active2 != a2)) return src.active2.fields["mi_dis"] = t1 if("mi_dis_d") if(istype(src.active2, /datum/data/record)) var/t1 = copytext(trim(sanitize(input("Please summarize minor dis.:", "Med. records", src.active2.fields["mi_dis_d"], null) as message)),1,MAX_MESSAGE_LEN) if((!( t1 ) || !( src.authenticated ) || usr.stat || usr.restrained() || (!in_range(src, usr) && (!istype(usr, /mob/living/silicon))) || src.active2 != a2)) return src.active2.fields["mi_dis_d"] = t1 if("ma_dis") if(istype(src.active2, /datum/data/record)) var/t1 = copytext(trim(sanitize(input("Please input major diabilities list:", "Med. records", src.active2.fields["ma_dis"], null) as text)),1,MAX_MESSAGE_LEN) if((!( t1 ) || !( src.authenticated ) || usr.stat || usr.restrained() || (!in_range(src, usr) && (!istype(usr, /mob/living/silicon))) || src.active2 != a2)) return src.active2.fields["ma_dis"] = t1 if("ma_dis_d") if(istype(src.active2, /datum/data/record)) var/t1 = copytext(trim(sanitize(input("Please summarize major dis.:", "Med. records", src.active2.fields["ma_dis_d"], null) as message)),1,MAX_MESSAGE_LEN) if((!( t1 ) || !( src.authenticated ) || usr.stat || usr.restrained() || (!in_range(src, usr) && (!istype(usr, /mob/living/silicon))) || src.active2 != a2)) return src.active2.fields["ma_dis_d"] = t1 if("alg") if(istype(src.active2, /datum/data/record)) var/t1 = copytext(trim(sanitize(input("Please state allergies:", "Med. records", src.active2.fields["alg"], null) as text)),1,MAX_MESSAGE_LEN) if((!( t1 ) || !( src.authenticated ) || usr.stat || usr.restrained() || (!in_range(src, usr) && (!istype(usr, /mob/living/silicon))) || src.active2 != a2)) return src.active2.fields["alg"] = t1 if("alg_d") if(istype(src.active2, /datum/data/record)) var/t1 = copytext(trim(sanitize(input("Please summarize allergies:", "Med. records", src.active2.fields["alg_d"], null) as message)),1,MAX_MESSAGE_LEN) if((!( t1 ) || !( src.authenticated ) || usr.stat || usr.restrained() || (!in_range(src, usr) && (!istype(usr, /mob/living/silicon))) || src.active2 != a2)) return src.active2.fields["alg_d"] = t1 if("cdi") if(istype(src.active2, /datum/data/record)) var/t1 = copytext(trim(sanitize(input("Please state diseases:", "Med. records", src.active2.fields["cdi"], null) as text)),1,MAX_MESSAGE_LEN) if((!( t1 ) || !( src.authenticated ) || usr.stat || usr.restrained() || (!in_range(src, usr) && (!istype(usr, /mob/living/silicon))) || src.active2 != a2)) return src.active2.fields["cdi"] = t1 if("cdi_d") if(istype(src.active2, /datum/data/record)) var/t1 = copytext(trim(sanitize(input("Please summarize diseases:", "Med. records", src.active2.fields["cdi_d"], null) as message)),1,MAX_MESSAGE_LEN) if((!( t1 ) || !( src.authenticated ) || usr.stat || usr.restrained() || (!in_range(src, usr) && (!istype(usr, /mob/living/silicon))) || src.active2 != a2)) return src.active2.fields["cdi_d"] = t1 if("notes") if(istype(src.active2, /datum/data/record)) var/t1 = copytext(html_encode(trim(input("Please summarize notes:", "Med. records", html_decode(src.active2.fields["notes"]), null) as message)),1,MAX_MESSAGE_LEN) if((!( t1 ) || !( src.authenticated ) || usr.stat || usr.restrained() || (!in_range(src, usr) && (!istype(usr, /mob/living/silicon))) || src.active2 != a2)) return src.active2.fields["notes"] = t1 if("p_stat") if(istype(src.active1, /datum/data/record)) src.temp = "<B>Physical Condition:</B><BR>\n\t<A href='?src=[UID()];temp=1;p_stat=deceased'>*Deceased*</A><BR>\n\t<A href='?src=[UID()];temp=1;p_stat=ssd'>*SSD*</A><BR>\n\t<A href='?src=[UID()];temp=1;p_stat=active'>Active</A><BR>\n\t<A href='?src=[UID()];temp=1;p_stat=unfit'>Physically Unfit</A><BR>\n\t<A href='?src=[UID()];temp=1;p_stat=disabled'>Disabled</A><BR>" if("m_stat") if(istype(src.active1, /datum/data/record)) src.temp = "<B>Mental Condition:</B><BR>\n\t<A href='?src=[UID()];temp=1;m_stat=insane'>*Insane*</A><BR>\n\t<A href='?src=[UID()];temp=1;m_stat=unstable'>*Unstable*</A><BR>\n\t<A href='?src=[UID()];temp=1;m_stat=watch'>*Watch*</A><BR>\n\t<A href='?src=[UID()];temp=1;m_stat=stable'>Stable</A><BR>" if("b_type") if(istype(src.active2, /datum/data/record)) src.temp = "<B>Blood Type:</B><BR>\n\t<A href='?src=[UID()];temp=1;b_type=an'>A-</A> <A href='?src=[UID()];temp=1;b_type=ap'>A+</A><BR>\n\t<A href='?src=[UID()];temp=1;b_type=bn'>B-</A> <A href='?src=[UID()];temp=1;b_type=bp'>B+</A><BR>\n\t<A href='?src=[UID()];temp=1;b_type=abn'>AB-</A> <A href='?src=[UID()];temp=1;b_type=abp'>AB+</A><BR>\n\t<A href='?src=[UID()];temp=1;b_type=on'>O-</A> <A href='?src=[UID()];temp=1;b_type=op'>O+</A><BR>" if("b_dna") if(istype(src.active1, /datum/data/record)) var/t1 = copytext(trim(sanitize(input("Please input DNA hash:", "Med. records", src.active1.fields["dna"], null) as text)),1,MAX_MESSAGE_LEN) if((!( t1 ) || !( src.authenticated ) || usr.stat || usr.restrained() || (!in_range(src, usr) && (!istype(usr, /mob/living/silicon))) || src.active1 != a1)) return src.active1.fields["dna"] = t1 if("vir_name") var/datum/data/record/v = locate(href_list["edit_vir"]) if(v) var/t1 = copytext(trim(sanitize(input("Please input pathogen name:", "VirusDB", v.fields["name"], null) as text)),1,MAX_MESSAGE_LEN) if((!( t1 ) || !( src.authenticated ) || usr.stat || usr.restrained() || (!in_range(src, usr) && (!istype(usr, /mob/living/silicon))) || src.active1 != a1)) return v.fields["name"] = t1 if("vir_desc") var/datum/data/record/v = locate(href_list["edit_vir"]) if(v) var/t1 = copytext(trim(sanitize(input("Please input information about pathogen:", "VirusDB", v.fields["description"], null) as message)),1,MAX_MESSAGE_LEN) if((!( t1 ) || !( src.authenticated ) || usr.stat || usr.restrained() || (!in_range(src, usr) && (!istype(usr, /mob/living/silicon))) || src.active1 != a1)) return v.fields["description"] = t1 else if(href_list["p_stat"]) if(src.active1) switch(href_list["p_stat"]) if("deceased") src.active1.fields["p_stat"] = "*Deceased*" if("ssd") src.active1.fields["p_stat"] = "*SSD*" if("active") src.active1.fields["p_stat"] = "Active" if("unfit") src.active1.fields["p_stat"] = "Physically Unfit" if("disabled") src.active1.fields["p_stat"] = "Disabled" if(href_list["m_stat"]) if(src.active1) switch(href_list["m_stat"]) if("insane") src.active1.fields["m_stat"] = "*Insane*" if("unstable") src.active1.fields["m_stat"] = "*Unstable*" if("watch") src.active1.fields["m_stat"] = "*Watch*" if("stable") src.active1.fields["m_stat"] = "Stable" if(href_list["b_type"]) if(src.active2) switch(href_list["b_type"]) if("an") src.active2.fields["b_type"] = "A-" if("bn") src.active2.fields["b_type"] = "B-" if("abn") src.active2.fields["b_type"] = "AB-" if("on") src.active2.fields["b_type"] = "O-" if("ap") src.active2.fields["b_type"] = "A+" if("bp") src.active2.fields["b_type"] = "B+" if("abp") src.active2.fields["b_type"] = "AB+" if("op") src.active2.fields["b_type"] = "O+" if(href_list["del_r"]) if(src.active2) src.temp = "Are you sure you wish to delete the record (Medical Portion Only)?<br>\n\t<A href='?src=[UID()];temp=1;del_r2=1'>Yes</A><br>\n\t<A href='?src=[UID()];temp=1'>No</A><br>" if(href_list["del_r2"]) if(src.active2) //src.active2 = null qdel(src.active2) if(href_list["d_rec"]) var/datum/data/record/R = locate(href_list["d_rec"]) var/datum/data/record/M = locate(href_list["d_rec"]) if(!( data_core.general.Find(R) )) src.temp = "Record Not Found!" return for(var/datum/data/record/E in data_core.medical) if((E.fields["name"] == R.fields["name"] || E.fields["id"] == R.fields["id"])) M = E else //Foreach continue //goto(2540) src.active1 = R src.active2 = M src.screen = 4 if(href_list["new"]) if((istype(src.active1, /datum/data/record) && !( istype(src.active2, /datum/data/record) ))) var/datum/data/record/R = new /datum/data/record( ) R.fields["name"] = src.active1.fields["name"] R.fields["id"] = src.active1.fields["id"] R.name = text("Medical Record #[]", R.fields["id"]) R.fields["b_type"] = "Unknown" R.fields["b_dna"] = "Unknown" R.fields["mi_dis"] = "None" R.fields["mi_dis_d"] = "No minor disabilities have been declared." R.fields["ma_dis"] = "None" R.fields["ma_dis_d"] = "No major disabilities have been diagnosed." R.fields["alg"] = "None" R.fields["alg_d"] = "No allergies have been detected in this patient." R.fields["cdi"] = "None" R.fields["cdi_d"] = "No diseases have been diagnosed at the moment." R.fields["notes"] = "No notes." data_core.medical += R src.active2 = R src.screen = 4 if(href_list["add_c"]) if(!( istype(src.active2, /datum/data/record) )) return var/a2 = src.active2 var/t1 = copytext(trim(sanitize(input("Add Comment:", "Med. records", null, null) as message)),1,MAX_MESSAGE_LEN) if((!( t1 ) || !( src.authenticated ) || usr.stat || usr.restrained() || (!in_range(src, usr) && (!istype(usr, /mob/living/silicon))) || src.active2 != a2)) return var/counter = 1 while(src.active2.fields[text("com_[]", counter)]) counter++ src.active2.fields[text("com_[counter]")] = text("Made by [authenticated] ([rank]) on [time2text(world.realtime, "DDD MMM DD hh:mm:ss")]<BR>[t1]") if(href_list["del_c"]) if((istype(src.active2, /datum/data/record) && src.active2.fields[text("com_[]", href_list["del_c"])])) src.active2.fields[text("com_[]", href_list["del_c"])] = "<B>Deleted</B>" if(href_list["search"]) var/t1 = input("Search String: (Name, DNA, or ID)", "Med. records", null, null) as text if((!( t1 ) || usr.stat || !( src.authenticated ) || usr.restrained() || ((!in_range(src, usr)) && (!istype(usr, /mob/living/silicon))))) return src.active1 = null src.active2 = null t1 = lowertext(t1) for(var/datum/data/record/R in data_core.medical) if((lowertext(R.fields["name"]) == t1 || t1 == lowertext(R.fields["id"]) || t1 == lowertext(R.fields["b_dna"]))) src.active2 = R else //Foreach continue //goto(3229) if(!( src.active2 )) src.temp = text("Could not locate record [].", t1) else for(var/datum/data/record/E in data_core.general) if((E.fields["name"] == src.active2.fields["name"] || E.fields["id"] == src.active2.fields["id"])) src.active1 = E else //Foreach continue //goto(3334) src.screen = 4 if(href_list["print_p"]) if(!( src.printing )) src.printing = 1 playsound(loc, "sound/goonstation/machines/printer_dotmatrix.ogg", 50, 1) sleep(50) var/obj/item/weapon/paper/P = new /obj/item/weapon/paper( src.loc ) P.info = "<CENTER><B>Medical Record</B></CENTER><BR>" if((istype(src.active1, /datum/data/record) && data_core.general.Find(src.active1))) P.info += text("Name: [] ID: []<BR>\nSex: []<BR>\nAge: []<BR>\nFingerprint: []<BR>\nPhysical Status: []<BR>\nMental Status: []<BR>", src.active1.fields["name"], src.active1.fields["id"], src.active1.fields["sex"], src.active1.fields["age"], src.active1.fields["fingerprint"], src.active1.fields["p_stat"], src.active1.fields["m_stat"]) else P.info += "<B>General Record Lost!</B><BR>" if((istype(src.active2, /datum/data/record) && data_core.medical.Find(src.active2))) P.info += text("<BR>\n<CENTER><B>Medical Data</B></CENTER><BR>\nBlood Type: []<BR>\nDNA: []<BR>\n<BR>\nMinor Disabilities: []<BR>\nDetails: []<BR>\n<BR>\nMajor Disabilities: []<BR>\nDetails: []<BR>\n<BR>\nAllergies: []<BR>\nDetails: []<BR>\n<BR>\nCurrent Diseases: [] (per disease info placed in log/comment section)<BR>\nDetails: []<BR>\n<BR>\nImportant Notes:<BR>\n\t[]<BR>\n<BR>\n<CENTER><B>Comments/Log</B></CENTER><BR>", src.active2.fields["b_type"], src.active2.fields["b_dna"], src.active2.fields["mi_dis"], src.active2.fields["mi_dis_d"], src.active2.fields["ma_dis"], src.active2.fields["ma_dis_d"], src.active2.fields["alg"], src.active2.fields["alg_d"], src.active2.fields["cdi"], src.active2.fields["cdi_d"], src.active2.fields["notes"]) var/counter = 1 while(src.active2.fields[text("com_[]", counter)]) P.info += text("[]<BR>", src.active2.fields[text("com_[]", counter)]) counter++ else P.info += "<B>Medical Record Lost!</B><BR>" P.info += "</TT>" P.name = "paper- 'Medical Record'" src.printing = null src.add_fingerprint(usr) src.updateUsrDialog() return /obj/machinery/computer/med_data/emp_act(severity) if(stat & (BROKEN|NOPOWER)) ..(severity) return for(var/datum/data/record/R in data_core.medical) if(prob(10/severity)) switch(rand(1,6)) if(1) R.fields["name"] = "[pick(pick(first_names_male), pick(first_names_female))] [pick(last_names)]" if(2) R.fields["sex"] = pick("Male", "Female") if(3) R.fields["age"] = rand(5, 85) if(4) R.fields["b_type"] = pick("A-", "B-", "AB-", "O-", "A+", "B+", "AB+", "O+") if(5) R.fields["p_stat"] = pick("*SSD*", "Active", "Physically Unfit", "Disabled") if(6) R.fields["m_stat"] = pick("*Insane*", "*Unstable*", "*Watch*", "Stable") continue else if(prob(1)) qdel(R) continue ..(severity) /obj/machinery/computer/med_data/laptop name = "medical laptop" desc = "Cheap Nanotrasen laptop." icon_state = "laptop" icon_keyboard = "laptop_key" icon_screen = "medlaptop"
DM
# Set the locations of things for this project # set(TRIBITS_PROJECT_ROOT "${CMAKE_CURRENT_LIST_DIR}/../..") set(TriBITS_TRIBITS_DIR "${CMAKE_CURRENT_LIST_DIR}/../../tribits") # # Include the TriBITS file to get other modules included # include("${CMAKE_CURRENT_LIST_DIR}/../../tribits/ctest_driver/TribitsCTestDriverCore.cmake") # # Define a caller for the TriBITS Project # macro(tribits_proj_ctest_driver) set_default(TriBITS_REPOSITORY_LOCATION_DEFAULT "https://github.com/TriBITSPub/TriBITS.git") set_default(TriBITS_REPOSITORY_LOCATION_NIGHTLY_DEFAULT "${TriBITS_REPOSITORY_LOCATION_DEFAULT}") print_var(TriBITS_REPOSITORY_LOCATION_DEFAULT) tribits_ctest_driver() endmacro()
CMake
name = "ddeabm" author = "Jacob Williams" copyright = "Copyright (c) 2014-2024, Jacob Williams" license = "BSD-3" description = "Modern Fortran Implementation of the DDEABM Adams-Bashforth Algorithm" homepage = "https://github.com/jacobwilliams/ddeabm" keywords = ["ODE", "Ordinary Differential Equations", "ODE solver", "Adams-Bashforth-Moulton", "root finding", "DEPAC", "SLATEC"] [dependencies] roots-fortran = { git = "https://github.com/jacobwilliams/roots-fortran", rev = "1.1.0" } [dev-dependencies] pyplot-fortran = { git = "https://github.com/jacobwilliams/pyplot-fortran", rev = "3.2.0" } [build] auto-executables = false auto-examples = false auto-tests = true [library] source-dir = "src" [install] library = true
TOML
\section{Conclusion and future work}\label{sec:conclusions} The maintenance of hydroelectric turbines is essential for hydropower plants fully operation, as it substantially increases the power plant potential. The maintenance of the hydraulic profile of turbine blades is a major concern for turbine efficiency, thus regular inspections, repairs and coating application for cavitation and abrasion protection should be done. The current hard coating operation is costly, as it requires turbine disassembling, thus this document aims: to analyze the constraints of the \textit{in situ} thermal spray coating process; to characterize the environment where the process is taking place; to make a detailed state of the art study of similar problems; and to design conceptual solutions. %Este documento teve como objetivo: fazer uma análise das restrições do processo %de revestimento por aspersão térmica; caracterizar o ambiente de trabalho onde % o processo será realizado; fazer um estudo detalhado do estado da arte que %visaram solucionar um problema semelhante ou possuíam tecnologias que %poderiam ser utilizadas como solução; apresentar soluções conceituais; e %fazer um estudo de viabilidade técnica para as soluções. The feasibility study for an \textit{in situ} coating application is promising and some possible solutions were investigated for each turbine access. All solutions run into some logistical and technical challenges, which will be detailed at the development of EMMA project. For future work, the mechanics, calibration, control, and user interface systems should be fully detailed. %O estudo de viabilidade de uma solução para revestimento \textit{in situ} se %mostrou promissor e foram apontadas algumas possíveis soluções considerando % cada acesso ao aro câmara da turbina. Todas as soluções esbarram em alguns desafios %logísticos e técnicos que serão abordados detalhadamente até o fim do projeto %EMMA. Os projetos de bases mecânicas para as diversas soluções serão abordados, %assim como suas instalações, manuseio e posicionamento. Além disso, toda a % parte de localização, calibração e mapeamento realizado pelo robô, seu controle e %interface de usuário ainda serão desenvolvidos.
TeX
// // Contact.swift // 5CLaundry_V2 // // Created by Ethan Hardacre on 5/19/18. // Copyright © 2018 Ethan Hardacre. All rights reserved. // import UIKit import MessageUI import Foundation class Contact: SubTemplateVC, MFMessageComposeViewControllerDelegate, MFMailComposeViewControllerDelegate { override func viewDidLoad() { super.viewDidLoad() super.initTitle(name: "Contact Us") // Do any additional setup after loading the view. var text_button = UIButton(frame: CGRect(x: 30, y: view.frame.height/2 - 25, width: view.frame.width - 60, height: 50)) var text_label = UILabel(frame: CGRect(x: 0, y: 0, width: text_button.frame.width, height: text_button.frame.height)) text_label.text = "Text Us" text_label.font = UIFont.boldSystemFont(ofSize: 20) text_label.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) text_label.textAlignment = .center text_button.addSubview(text_label) text_button.backgroundColor = #colorLiteral(red: 0.9882352941, green: 0.03529411765, blue: 0.03546316964, alpha: 1) text_button.layer.cornerRadius = 15 text_button.addTarget(self, action: #selector(sendText), for: .touchUpInside) self.view.addSubview(text_button) var call_button = UIButton(frame: CGRect(x: 30, y: text_button.frame.minY - 70, width: view.frame.width - 60, height: 50)) var call_label = UILabel(frame: CGRect(x: 0, y: 0, width: call_button.frame.width, height: call_button.frame.height)) call_label.text = "Call Us" call_label.font = UIFont.boldSystemFont(ofSize: 20) call_label.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) call_label.textAlignment = .center call_button.addSubview(call_label) call_button.backgroundColor = #colorLiteral(red: 0.9882352941, green: 0.03529411765, blue: 0.03546316964, alpha: 1) call_button.layer.cornerRadius = 15 call_button.addTarget(self, action: #selector(callNumber), for: .touchUpInside) self.view.addSubview(call_button) var email_button = UIButton(frame: CGRect(x: 30, y: text_button.frame.maxY + 20, width: view.frame.width - 60, height: 50)) var email_label = UILabel(frame: CGRect(x: 0, y: 0, width: email_button.frame.width, height: email_button.frame.height)) email_label.text = "Email Us" email_label.font = UIFont.boldSystemFont(ofSize: 20) email_label.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) email_label.textAlignment = .center email_button.addSubview(email_label) email_button.backgroundColor = #colorLiteral(red: 0.9882352941, green: 0.03529411765, blue: 0.03546316964, alpha: 1) email_button.layer.cornerRadius = 15 email_button.addTarget(self, action: #selector(sendEmail), for: .touchUpInside) self.view.addSubview(email_button) var find = UIButton(frame: CGRect(x: 30, y: view.frame.height - 100, width: view.frame.width - 60, height: 50)) var find_label = UILabel(frame: CGRect(x: 0, y: 0, width: find.frame.width, height: find.frame.height)) var looking = UILabel(frame: CGRect(x: 30, y: view.frame.height - 120, width: view.frame.width - 60, height: 20)) looking.textAlignment = .center looking.font = UIFont.boldSystemFont(ofSize: 13) looking.textColor = #colorLiteral(red: 0.9882352941, green: 0.03529411765, blue: 0.03546316964, alpha: 1) looking.text = "Looking for the 5C Laundry van?" view.addSubview(looking) find_label.text = "Find the Van" find_label.font = UIFont.boldSystemFont(ofSize: 20) find_label.textColor = #colorLiteral(red: 0.9882352941, green: 0.03529411765, blue: 0.03546316964, alpha: 1) find_label.textAlignment = .center find.addSubview(find_label) find.backgroundColor = #colorLiteral(red: 0.9998916984, green: 1, blue: 0.9998809695, alpha: 1) find.layer.cornerRadius = 15 find.layer.borderColor = #colorLiteral(red: 0.9882352941, green: 0.03529411765, blue: 0.03546316964, alpha: 1) find.layer.borderWidth = 2 find.addTarget(self, action: #selector(findVan), for: .touchUpInside) self.view.addSubview(find) } @objc func findVan(){ var par = parent as! Home3 self.view.removeFromSuperview() par.transitionTo(cls: "Information") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) { } @objc func callNumber() { if let phoneCallURL = URL(string: "tel://6196639274") { let application:UIApplication = UIApplication.shared if (application.canOpenURL(phoneCallURL)) { application.open(phoneCallURL, options: [:], completionHandler: nil) } } } @objc func sendText() { if (MFMessageComposeViewController.canSendText()) { let controller = MFMessageComposeViewController() controller.body = "" //Set phone number to current 5CLaundry manager controller.recipients = ["6196639274"] controller.messageComposeDelegate = self self.present(controller, animated: true, completion: nil) } } @objc func sendEmail() { let mailComposeViewController = configuredMailComposeViewController() if MFMailComposeViewController.canSendMail() { self.present(mailComposeViewController, animated: true, completion: nil) } else { self.showSendMailErrorAlert() } } func configuredMailComposeViewController() -> MFMailComposeViewController { let mailComposerVC = MFMailComposeViewController() mailComposerVC.mailComposeDelegate = self as? MFMailComposeViewControllerDelegate // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property mailComposerVC.setToRecipients(["info@5claundry.com"]) mailComposerVC.setSubject("Question/Concern") mailComposerVC.setMessageBody("5C Laundry, ", isHTML: false) return mailComposerVC } func showSendMailErrorAlert() { let alert = UIAlertController(title: "Oops!", message:"This feature is not available right now. Please visit our website.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in }) self.present(alert, animated: true){} } // MARK: MFMailComposeViewControllerDelegate func mailComposeController(_ controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?){ controller.dismiss(animated: true, completion: nil) } }
Swift
open Core.Std open Async.Std (** Provides access to instance metadata when run in an ec2 instance *) module type Fetcher = sig val fetch: String.t -> (String.t, Exn.t) Deferred.Result.t (** Fetch the metadata referred by the argument The argument is a path to the required metadata, excluding the root URI for the latest version. For example, the path "/iam/info". will be translated into a GET to "http://169.254.169.254/latest/iam/info" by the production Fetcher *) end module type Api = sig val get_availability_zone : Unit.t -> (String.t, Exn.t) Deferred.Result.t (** Return the availability zone of the running instance *) val get_region : Unit.t -> (String.t, Exn.t) Deferred.Result.t (** Return the region of the running instance *) val get_role : String.t -> (Ec2im_iam_role_t.desc, Exn.t) Deferred.Result.t (** Return the role description of the running instance *) val get_user_data : Unit.t -> (String.t, Exn.t) Deferred.Result.t (** Return the user data of the running instance, if there are any *) end (** This functor delegates all side effects to the Fetcher so that we can unit test this module in isolation. It has the same API as the main module, but you must provide an alternative fetcher that simulates the HTTP interface available in EC2 instances *) module Make (Fetcher : Fetcher) : Api (* Default Api using the production fetcher *) include Api
OCaml
// This file has been generated by the GUI designer. Do not modify. public partial class MainWindow { private global::Gtk.VBox vbox1; private global::Gtk.ScrolledWindow GtkScrolledWindow; private global::Gtk.TextView mainTextView; private global::Gtk.HBox hbox1; private global::Gtk.Button saveButton; private global::Gtk.Button restoreButton; private global::Gtk.Button quitButton; protected virtual void Build () { global::Stetic.Gui.Initialize (this); // Widget MainWindow this.Name = "MainWindow"; this.Title = global::Mono.Unix.Catalog.GetString ("Memento Editor"); this.WindowPosition = ((global::Gtk.WindowPosition)(4)); // Container child MainWindow.Gtk.Container+ContainerChild this.vbox1 = new global::Gtk.VBox (); this.vbox1.Name = "vbox1"; this.vbox1.Spacing = 6; // Container child vbox1.Gtk.Box+BoxChild this.GtkScrolledWindow = new global::Gtk.ScrolledWindow (); this.GtkScrolledWindow.Name = "GtkScrolledWindow"; this.GtkScrolledWindow.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child GtkScrolledWindow.Gtk.Container+ContainerChild this.mainTextView = new global::Gtk.TextView (); this.mainTextView.CanFocus = true; this.mainTextView.Name = "mainTextView"; this.GtkScrolledWindow.Add (this.mainTextView); this.vbox1.Add (this.GtkScrolledWindow); global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.GtkScrolledWindow])); w2.Position = 0; // Container child vbox1.Gtk.Box+BoxChild this.hbox1 = new global::Gtk.HBox (); this.hbox1.Name = "hbox1"; this.hbox1.Spacing = 6; // Container child hbox1.Gtk.Box+BoxChild this.saveButton = new global::Gtk.Button (); this.saveButton.CanFocus = true; this.saveButton.Name = "saveButton"; this.saveButton.UseUnderline = true; this.saveButton.Label = global::Mono.Unix.Catalog.GetString ("Save"); this.hbox1.Add (this.saveButton); global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.saveButton])); w3.Position = 0; w3.Expand = false; w3.Fill = false; // Container child hbox1.Gtk.Box+BoxChild this.restoreButton = new global::Gtk.Button (); this.restoreButton.CanFocus = true; this.restoreButton.Name = "restoreButton"; this.restoreButton.UseUnderline = true; this.restoreButton.Label = global::Mono.Unix.Catalog.GetString ("Restore"); this.hbox1.Add (this.restoreButton); global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.restoreButton])); w4.Position = 1; w4.Expand = false; w4.Fill = false; // Container child hbox1.Gtk.Box+BoxChild this.quitButton = new global::Gtk.Button (); this.quitButton.CanFocus = true; this.quitButton.Name = "quitButton"; this.quitButton.UseUnderline = true; this.quitButton.Label = global::Mono.Unix.Catalog.GetString ("Quit"); this.hbox1.Add (this.quitButton); global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.quitButton])); w5.Position = 2; w5.Expand = false; w5.Fill = false; this.vbox1.Add (this.hbox1); global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.hbox1])); w6.Position = 1; w6.Expand = false; w6.Fill = false; this.Add (this.vbox1); if ((this.Child != null)) { this.Child.ShowAll (); } this.DefaultWidth = 689; this.DefaultHeight = 579; this.Show (); this.DeleteEvent += new global::Gtk.DeleteEventHandler (this.OnDeleteEvent); this.saveButton.Clicked += new global::System.EventHandler (this.OnSaveButtonClicked); this.restoreButton.Clicked += new global::System.EventHandler (this.OnRestoreButtonClicked); this.quitButton.Clicked += new global::System.EventHandler (this.OnQuitButtonClicked); } }
C#
#!/bin/bash hps-mc-job run -d $PWD/scratch beam_gen job.json
Shell
UPDATE `creature` SET `position_z`=-6.03356 WHERE `guid`=46069 AND `id`=11741; -- Dredge Crusher UPDATE `creature` SET `position_z`=8.638660 WHERE `guid`=49069 AND `id`=11374; -- Hooktooth Frenzies UPDATE `creature_template` SET `flags_extra`=`flags_extra`|128 WHERE `entry` = 37231; -- Robe Beam Stalker UPDATE `creature_template` SET `flags_extra`=`flags_extra`|128 WHERE `entry` = 38008; -- Blood Orb Controller UPDATE `playercreateinfo_action` SET `action`=26297 WHERE `action` IN (20554,50621,26635,26296) AND `race`=8; -- Berserking - Troll racial
PLSQL
; ; Description: id ; Expect: generator == 'http://example.com/planet' ; [Planet] generator_uri: http://example.com/planet
INI
import os from IPython.lib import passwd c = get_config() c.NotebookApp.open_browser = False c.NotebookApp.ip = "0.0.0.0" c.NotebookApp.port = 8888 c.NotebookApp.notebook_dir = '/workspace' c.NotebookApp.allow_root = True if 'PASSWORD' in os.environ: c.NotebookApp.password = passwd(os.environ['PASSWORD']) del os.environ['PASSWORD']
Python
package MunkiDancer::LookForUpdates; use Dancer ':syntax'; use MunkiDancer::Common; use MunkiDancer::Parser; use LWP::Protocol::http; use WWW::Mechanize; use Exporter 'import'; our @EXPORT = qw( LookForUpdates ); # Prevent "Header line too long (9557; limit is 8192)" error for $mech->get push(@LWP::Protocol::http::EXTRA_SOCK_OPTS, MaxLineLength => 0); sub LookForUpdates { foreach my $id ( keys %catalog ) { my $latest_version = LatestVersion($id); next if $latest_version eq 'N/A'; if ( $catalog{$id}{version} ne $latest_version ) { $catalog{$id}{latest_version} = $latest_version; } } return 1; } sub LatestVersion { my ($id) = @_; return 'N/A' if LookForUpdateExcluded($id); return 'N/A' unless exists $catalog{$id}{update_url}; return 'N/A' unless $catalog{$id}{update_url} =~ m/macupdate/i; my $mech = WWW::Mechanize->new(); $mech->get( $catalog{$id}{update_url}, 'Accept-Encoding' => 'identity' ); my $html = $mech->content || ''; my $match_version_number = qr{ <span\sclass="mu_app_header_version">([^<]*)<\/span> }xi; (my $version) = $html =~ m/$match_version_number/; return 'N/A' unless $version; return $version; }
Perl
<?xml version="1.0"?> <?iotk version="1.2.0"?> <?iotk file_version="1.0"?> <?iotk binary="F"?> <?iotk qe_syntax="F"?> <Root> <GEOMETRY_INFO> <NUMBER_OF_TYPES type="integer" size="1"> 1 </NUMBER_OF_TYPES> <NUMBER_OF_ATOMS type="integer" size="1"> 2 </NUMBER_OF_ATOMS> <BRAVAIS_LATTICE_INDEX type="integer" size="1"> 5 </BRAVAIS_LATTICE_INDEX> <SPIN_COMPONENTS type="integer" size="1"> 1 </SPIN_COMPONENTS> <CELL_DIMENSIONS type="real" size="6"> 7.018435545048277E+000 0.000000000000000E+000 0.000000000000000E+000 4.848312789052549E-001 0.000000000000000E+000 0.000000000000000E+000 </CELL_DIMENSIONS> <AT type="real" size="9" columns="3"> 5.075276943649857E-001 -2.930212509627937E-001 8.102803131860233E-001 0.000000000000000E+000 5.860425019255089E-001 8.102803131860233E-001 -5.075276943649857E-001 -2.930212509627937E-001 8.102803131860233E-001 </AT> <BG type="real" size="9" columns="3"> 9.851679140890935E-001 -5.687869603964116E-001 4.113802691597569E-001 0.000000000000000E+000 1.137573920792823E+000 4.113802691598121E-001 -9.851679140890935E-001 -5.687869603964116E-001 4.113802691597569E-001 </BG> <UNIT_CELL_VOLUME_AU type="real" size="1"> 2.499576015624759E+002 </UNIT_CELL_VOLUME_AU> <TYPE_NAME.1 type="character" size="1" len="3"> Si </TYPE_NAME.1> <MASS.1 type="real" size="1"> 2.808600000000000E+001 </MASS.1> <ATOM.1 SPECIES="Si " INDEX="1" TAU="0.000000000000000E+000 -6.505213034913473E-019 3.422012213183033E-003"/> <ATOM.2 SPECIES="Si " INDEX="1" TAU="5.075276943649513E-001 -2.930212509627947E-001 1.991480660833371E-001"/> <NUMBER_OF_Q type="integer" size="1"> 3 </NUMBER_OF_Q> </GEOMETRY_INFO> <DYNAMICAL_MAT_.1> <Q_POINT type="real" size="3" columns="3"> 4.925839570445467E-001 -2.843934801982058E-001 -4.113802691597845E-001 </Q_POINT> <PHI.1.1 type="complex" size="9"> 3.392363068642791E-001, 0.000000000000000E+000 -3.225089057315789E-002, 0.000000000000000E+000 -4.814120860454353E-002, 0.000000000000000E+000 -3.225089057315791E-002, 0.000000000000000E+000 3.019961861563463E-001, 0.000000000000000E+000 2.779433974696080E-002, 0.000000000000000E+000 -4.814120860454350E-002, 0.000000000000000E+000 2.779433974696076E-002, 0.000000000000000E+000 3.110194070640565E-001, 0.000000000000000E+000 </PHI.1.1> <PHI.1.2 type="complex" size="9"> 1.183126130875925E-002, 2.526280142664296E-019 1.430511859543231E-001, 3.054512625745423E-018 -9.160820986475231E-002,-1.956072099557215E-018 1.430511859543231E-001, 3.054512625745422E-018 1.770125427460369E-001, 3.779675387701539E-018 5.289002462541138E-002, 1.129338753234035E-018 -9.160820986475236E-002,-1.956072099557216E-018 5.289002462541140E-002, 1.129338753234035E-018 -1.715406663962540E-001,-3.662836682133124E-018 </PHI.1.2> <PHI.2.1 type="complex" size="9"> 1.183126130875925E-002,-2.526280142664296E-019 1.430511859543231E-001,-3.054512625745423E-018 -9.160820986475231E-002, 1.956072099557215E-018 1.430511859543231E-001,-3.054512625745422E-018 1.770125427460369E-001,-3.779675387701539E-018 5.289002462541138E-002,-1.129338753234035E-018 -9.160820986475236E-002, 1.956072099557216E-018 5.289002462541140E-002,-1.129338753234035E-018 -1.715406663962540E-001, 3.662836682133124E-018 </PHI.2.1> <PHI.2.2 type="complex" size="9"> 3.392363068642791E-001, 0.000000000000000E+000 -3.225089057315789E-002, 0.000000000000000E+000 -4.814120860454353E-002, 0.000000000000000E+000 -3.225089057315791E-002, 0.000000000000000E+000 3.019961861563463E-001, 0.000000000000000E+000 2.779433974696080E-002, 0.000000000000000E+000 -4.814120860454350E-002, 0.000000000000000E+000 2.779433974696076E-002, 0.000000000000000E+000 3.110194070640565E-001, 0.000000000000000E+000 </PHI.2.2> </DYNAMICAL_MAT_.1> <DYNAMICAL_MAT_.2> <Q_POINT type="real" size="3" columns="3"> 4.925839570445467E-001 2.843934801982058E-001 4.113802691597845E-001 </Q_POINT> <PHI.1.1 type="complex" size="9"> 3.392363068642791E-001, 0.000000000000000E+000 3.225089057315787E-002, 0.000000000000000E+000 4.814120860454350E-002, 0.000000000000000E+000 3.225089057315790E-002, 0.000000000000000E+000 3.019961861563463E-001, 0.000000000000000E+000 2.779433974696080E-002, 0.000000000000000E+000 4.814120860454352E-002, 0.000000000000000E+000 2.779433974696076E-002, 0.000000000000000E+000 3.110194070640565E-001, 0.000000000000000E+000 </PHI.1.1> <PHI.1.2 type="complex" size="9"> -1.183126130875925E-002,-2.540509885304652E-015 1.430511859543231E-001, 3.071717736066315E-014 -9.160820986475231E-002,-1.967090039370210E-014 1.430511859543231E-001, 3.071717736066314E-014 -1.770125427460369E-001,-3.800965112115984E-014 -5.289002462541138E-002,-1.135699963750986E-014 -9.160820986475235E-002,-1.967090039370211E-014 -5.289002462541141E-002,-1.135699963750986E-014 1.715406663962540E-001, 3.683468290813454E-014 </PHI.1.2> <PHI.2.1 type="complex" size="9"> -1.183126130875925E-002, 2.540509885304652E-015 1.430511859543231E-001,-3.071717736066315E-014 -9.160820986475231E-002, 1.967090039370210E-014 1.430511859543231E-001,-3.071717736066314E-014 -1.770125427460369E-001, 3.800965112115984E-014 -5.289002462541138E-002, 1.135699963750986E-014 -9.160820986475235E-002, 1.967090039370211E-014 -5.289002462541141E-002, 1.135699963750986E-014 1.715406663962540E-001,-3.683468290813454E-014 </PHI.2.1> <PHI.2.2 type="complex" size="9"> 3.392363068642791E-001, 0.000000000000000E+000 3.225089057315787E-002, 0.000000000000000E+000 4.814120860454350E-002, 0.000000000000000E+000 3.225089057315790E-002, 0.000000000000000E+000 3.019961861563463E-001, 0.000000000000000E+000 2.779433974696080E-002, 0.000000000000000E+000 4.814120860454352E-002, 0.000000000000000E+000 2.779433974696076E-002, 0.000000000000000E+000 3.110194070640565E-001, 0.000000000000000E+000 </PHI.2.2> </DYNAMICAL_MAT_.2> <DYNAMICAL_MAT_.3> <Q_POINT type="real" size="3" columns="3"> 0.000000000000000E+000 -5.687869603964115E-001 4.113802691597569E-001 </Q_POINT> <PHI.1.1 type="complex" size="9"> 2.833761258022345E-001, 0.000000000000000E+000 0.000000000000000E+000, 0.000000000000000E+000 0.000000000000000E+000, 0.000000000000000E+000 -2.775557561562891E-017, 0.000000000000000E+000 3.578563672184089E-001, 0.000000000000000E+000 -5.558867949389040E-002, 0.000000000000000E+000 0.000000000000000E+000, 0.000000000000000E+000 -5.558867949389038E-002, 0.000000000000000E+000 3.110194070640511E-001, 0.000000000000000E+000 </PHI.1.1> <PHI.1.2 type="complex" size="9"> -2.596031834645904E-001, 9.769687896514822E-016 6.288372600415926E-018, 3.120006509907322E-032 -3.361026734705064E-018, 1.232595164407831E-032 -7.589415207398531E-018,-1.810374147724002E-032 7.075937940987383E-002,-2.662898980512066E-016 1.057800492508136E-001,-3.980837419119612E-016 -3.361026734705064E-018, 1.271113763295576E-032 1.057800492508136E-001,-3.980837419119613E-016 1.715406663962643E-001,-6.455617184217853E-016 </PHI.1.2> <PHI.2.1 type="complex" size="9"> -2.596031834645904E-001,-9.769687896514822E-016 6.288372600415926E-018,-3.120006509907322E-032 -3.361026734705064E-018,-1.232595164407831E-032 -7.589415207398531E-018, 1.810374147724002E-032 7.075937940987383E-002, 2.662898980512066E-016 1.057800492508136E-001, 3.980837419119612E-016 -3.361026734705064E-018,-1.271113763295576E-032 1.057800492508136E-001, 3.980837419119613E-016 1.715406663962643E-001, 6.455617184217853E-016 </PHI.2.1> <PHI.2.2 type="complex" size="9"> 2.833761258022345E-001, 0.000000000000000E+000 0.000000000000000E+000, 0.000000000000000E+000 0.000000000000000E+000, 0.000000000000000E+000 -2.775557561562891E-017, 0.000000000000000E+000 3.578563672184089E-001, 0.000000000000000E+000 -5.558867949389040E-002, 0.000000000000000E+000 0.000000000000000E+000, 0.000000000000000E+000 -5.558867949389038E-002, 0.000000000000000E+000 3.110194070640511E-001, 0.000000000000000E+000 </PHI.2.2> </DYNAMICAL_MAT_.3> <FREQUENCIES_THZ_CMM1> <OMEGA.1 type="real" size="2" columns="2"> 3.170344856334375E+000 1.057513213469291E+002 </OMEGA.1> <DISPLACEMENT.1 type="complex" size="6"> -3.535533905933233E-001, 0.000000000000000E+000 -6.123724356957657E-001, 0.000000000000000E+000 -1.947330597302324E-015, 0.000000000000000E+000 3.535533905933196E-001, 0.000000000000000E+000 6.123724356957683E-001, 0.000000000000000E+000 -5.120144910417563E-015, 0.000000000000000E+000 </DISPLACEMENT.1> <OMEGA.2 type="real" size="2" columns="2"> 3.892696944108023E+000 1.298463934042004E+002 </OMEGA.2> <DISPLACEMENT.2 type="complex" size="6"> -3.309223406044626E-001, 0.000000000000000E+000 1.910581024288383E-001, 0.000000000000000E+000 -5.949682394759869E-001, 0.000000000000000E+000 -3.309223406044671E-001, 0.000000000000000E+000 1.910581024288311E-001,-0.000000000000000E+000 -5.949682394759872E-001, 0.000000000000000E+000 </DISPLACEMENT.2> <OMEGA.3 type="real" size="2" columns="2"> 1.285305767766118E+001 4.287318554778712E+002 </OMEGA.3> <DISPLACEMENT.3 type="complex" size="6"> -5.152576098312437E-001, 0.000000000000000E+000 2.974841197377343E-001, 0.000000000000000E+000 3.821162048576837E-001, 0.000000000000000E+000 -5.152576098312650E-001, 0.000000000000000E+000 2.974841197377466E-001, 0.000000000000000E+000 3.821162048576975E-001, 0.000000000000000E+000 </DISPLACEMENT.3> <OMEGA.4 type="real" size="2" columns="2"> 1.298189907590252E+001 4.330295419207151E+002 </OMEGA.4> <DISPLACEMENT.4 type="complex" size="6"> 5.256006435762260E-001, 0.000000000000000E+000 -3.034556730550299E-001, 0.000000000000000E+000 -3.628479267723541E-001, 0.000000000000000E+000 -5.256006435762052E-001, 0.000000000000000E+000 3.034556730550182E-001, 0.000000000000000E+000 3.628479267723391E-001, 0.000000000000000E+000 </DISPLACEMENT.4> <OMEGA.5 type="real" size="2" columns="2"> 1.472111009357458E+001 4.910433768675587E+002 </OMEGA.5> <DISPLACEMENT.5 type="complex" size="6"> -3.142355222953542E-001, 0.000000000000000E+000 1.814239633861975E-001,-0.000000000000000E+000 -6.069113461099649E-001, 0.000000000000000E+000 3.142355222953550E-001, 0.000000000000000E+000 -1.814239633861960E-001, 0.000000000000000E+000 6.069113461099650E-001, 0.000000000000000E+000 </DISPLACEMENT.5> <OMEGA.6 type="real" size="2" columns="2"> 1.515153653305261E+001 5.054008574509439E+002 </OMEGA.6> <DISPLACEMENT.6 type="complex" size="6"> -3.535533905930555E-001, 0.000000000000000E+000 -6.123724356959210E-001, 0.000000000000000E+000 -1.486068224158069E-013, 0.000000000000000E+000 -3.535533905930547E-001, 0.000000000000000E+000 -6.123724356959206E-001, 0.000000000000000E+000 -1.467932250357595E-013, 0.000000000000000E+000 </DISPLACEMENT.6> </FREQUENCIES_THZ_CMM1> </Root>
XML
@echo off rem ------------------------------------------------------------- rem Yii command line script for Windows. rem This is the bootstrap script for running yiic on Windows. rem ------------------------------------------------------------- @setlocal set BIN_PATH=%~dp0 if "%PHP_COMMAND%" == "" set PHP_COMMAND=php.exe %PHP_COMMAND% "%BIN_PATH%yiic.php" %* @endlocal
Batchfile
SHELL=/bin/sh BENCHMARK=sp BENCHMARKU=SP include ../config/make.def OBJS = sp.o make_set.o initialize.o exact_solution.o exact_rhs.o \ set_constants.o adi.o define.o copy_faces.o rhs.o \ lhsx.o lhsy.o lhsz.o x_solve.o ninvr.o y_solve.o pinvr.o \ z_solve.o tzetar.o add.o txinvr.o error.o verify.o setup_mpi.o \ ${COMMON}/print_results.o ${COMMON}/timers.o pmpi.o include ../sys/make.common # npbparams.h is included by header.h # The following rule should do the trick but many make programs (not gmake) # will do the wrong thing and rebuild the world every time (because the # mod time on header.h is not changed. One solution would be to # touch header.h but this might cause confusion if someone has # accidentally deleted it. Instead, make the dependency on npbparams.h # explicit in all the lines below (even though dependence is indirect). # header.h: npbparams.h ${PROGRAM}: config ${OBJS} ${FLINK} ${FLINKFLAGS} -o ${PROGRAM} ${OBJS} ${FMPI_LIB} .f.o: ${FCOMPILE} $< sp.o: sp.f header.h npbparams.h mpinpb.h make_set.o: make_set.f header.h npbparams.h mpinpb.h initialize.o: initialize.f header.h npbparams.h exact_solution.o: exact_solution.f header.h npbparams.h exact_rhs.o: exact_rhs.f header.h npbparams.h set_constants.o: set_constants.f header.h npbparams.h adi.o: adi.f header.h npbparams.h define.o: define.f header.h npbparams.h copy_faces.o: copy_faces.f header.h npbparams.h mpinpb.h rhs.o: rhs.f header.h npbparams.h lhsx.o: lhsx.f header.h npbparams.h lhsy.o: lhsy.f header.h npbparams.h lhsz.o: lhsz.f header.h npbparams.h x_solve.o: x_solve.f header.h npbparams.h mpinpb.h ninvr.o: ninvr.f header.h npbparams.h y_solve.o: y_solve.f header.h npbparams.h mpinpb.h pinvr.o: pinvr.f header.h npbparams.h z_solve.o: z_solve.f header.h npbparams.h mpinpb.h tzetar.o: tzetar.f header.h npbparams.h add.o: add.f header.h npbparams.h txinvr.o: txinvr.f header.h npbparams.h error.o: error.f header.h npbparams.h mpinpb.h verify.o: verify.f header.h npbparams.h mpinpb.h setup_mpi.o: setup_mpi.f mpinpb.h npbparams.h pmpi.o: pmpi.c ${CCOMPILE} pmpi.c clean: - rm -f *.o *~ mputil* - rm -f npbparams.h core
Makefile
module iic_top( clk,rst_n,REG_WR,IDAT,addr, sw1,sw2,sw3,sw4, scl,sda, ackflag, // sda_link, outdata ); input clk,rst_n,REG_WR; input [7:0]IDAT; input [2:0]addr; input sw1,sw2,sw3,sw4; output [7:0]outdata; output [2:0]ackflag; inout sda; output scl; wire net_sda_link; wire net_clk,net_rst_n,net_reg_wr; wire [7:0]net_IDAT; wire [2:0]net_addr; wire net_sw1,net_sw2,net_sw3,net_sw4; wire [7:0]net_outdata; wire [2:0]net_ackflag; wire net_sda_i,net_sda_o,net_sda; wire net_scl; //insert top module iic iic_instance( .clk(net_clk),.rst_n(net_rst_n),.REG_WR(net_reg_wr), .IDAT(net_IDAT),.addr(net_addr), .sw1(net_sw1),.sw2(net_sw2),.sw3(net_sw3),.sw4(net_sw4), .scl(net_scl),.sda(net_sda),.ackflag(net_ackflag), .sda_link(net_sda_link),.outdata(net_outdata) ); //insert io pad pc3d01 clk_pad(.PAD(clk),.CIN(net_clk)); pc3d01 rst_n_pad(.PAD(rst_n),.CIN(net_rst_n)); pc3d01 REG_WR_pad(.PAD(REG_WR),.CIN(net_reg_wr)); pc3d01 IDAT_pad_0(.PAD(IDAT[0]),.CIN(net_IDAT[0])); pc3d01 IDAT_pad_1(.PAD(IDAT[1]),.CIN(net_IDAT[1])); pc3d01 IDAT_pad_2(.PAD(IDAT[2]),.CIN(net_IDAT[2])); pc3d01 IDAT_pad_3(.PAD(IDAT[3]),.CIN(net_IDAT[3])); pc3d01 IDAT_pad_4(.PAD(IDAT[4]),.CIN(net_IDAT[4])); pc3d01 IDAT_pad_5(.PAD(IDAT[5]),.CIN(net_IDAT[5])); pc3d01 IDAT_pad_6(.PAD(IDAT[6]),.CIN(net_IDAT[6])); pc3d01 IDAT_pad_7(.PAD(IDAT[7]),.CIN(net_IDAT[7])); pc3d01 addr_pad_0(.PAD(addr[0]),.CIN(net_addr[0])); pc3d01 addr_pad_1(.PAD(addr[1]),.CIN(net_addr[1])); pc3d01 addr_pad_2(.PAD(addr[2]),.CIN(net_addr[2])); pc3d01 sw1_pad(.PAD(sw1),.CIN(net_sw1)); pc3d01 sw2_pad(.PAD(sw2),.CIN(net_sw2)); pc3d01 sw3_pad(.PAD(sw3),.CIN(net_sw3)); pc3d01 sw4_pad(.PAD(sw4),.CIN(net_sw4)); pc3o05 outdata_pad_0(.I(net_outdata[0]),.PAD(outdata[0])); pc3o05 outdata_pad_1(.I(net_outdata[1]),.PAD(outdata[1])); pc3o05 outdata_pad_2(.I(net_outdata[2]),.PAD(outdata[2])); pc3o05 outdata_pad_3(.I(net_outdata[3]),.PAD(outdata[3])); pc3o05 outdata_pad_4(.I(net_outdata[4]),.PAD(outdata[4])); pc3o05 outdata_pad_5(.I(net_outdata[5]),.PAD(outdata[5])); pc3o05 outdata_pad_6(.I(net_outdata[6]),.PAD(outdata[6])); pc3o05 outdata_pad_7(.I(net_outdata[7]),.PAD(outdata[7])); pc3o05 ackflag_pad_0(.I(net_ackflag[0]),.PAD(ackflag[0])); pc3o05 ackflag_pad_1(.I(net_ackflag[1]),.PAD(ackflag[1])); pc3o05 ackflag_pad_2(.I(net_ackflag[2]),.PAD(ackflag[2])); pc3o05 scl_pad(.I(net_scl),.PAD(scl)); assign net_sda=net_sda_link?'bz:net_sda_i; assign net_sda_o=net_sda_link?net_sda:'bz; pc3b03 sda_pad(.I(net_sda_o),.OEN(net_sda_link),.CIN(net_sda_i),.PAD(sda)); endmodule module iic( clk, rst_n, REG_WR, IDAT, //数据端口 addr, sw1,sw2,sw3,sw4, //读写选择,低有效,不能同时置数 scl, sda, ackflag, sda_link,//用作仿真时候使用,表示sda状态位 outdata ); // DEVICE,// //被寻址器件地址 // WRITE_DATA0,// 单写的数据,连写时不必注意 // WRITE_DATA1,// //连写的数据 支持最大四个数据 // WRITE_DATA2, // // WRITE_DATA3, // // WRITE_DATA4, // // PAGEDATA_NUM, // 页读页写数据个数 // BYTE_ADDR,// //写入EEPROM的地址寄存器 // BYTE_WRADDR input REG_WR; input [7:0]IDAT; input [2:0]addr; input clk; // 1MHz input rst_n; //复位信号,低有效 input sw1,sw2,sw3,sw4; //按键,(1按下执行写入操作,2按下执行读操作,3按下执行连写操作,4按下执行连读操作) output scl; //时钟端口 output [2:0]ackflag;//后面显示接收到数据的标准 inout sda; //数据端口 output [7:0] outdata; //数码管显示的数据 //--------------------------------------------- //分频部分 reg[2:0] cnt; // cnt=0:scl上升沿,cnt=1:scl高电平中间,cnt=2:scl下降沿,cnt=3:scl低电平中间 reg[8:0] cnt_delay; //500循环计数,产生iic所需要的时钟 reg scl_r; //时钟脉冲寄存器 always @ (posedge clk or negedge rst_n) if(!rst_n) cnt_delay <= 9'd0; else if(cnt_delay == 9'd99) cnt_delay <= 9'd0; //计数到10us为scl的周期,即100KHz else cnt_delay <= cnt_delay+1'b1; //时钟计数 always @ (posedge clk or negedge rst_n) begin if(!rst_n) cnt <= 3'd5; else begin case (cnt_delay) 9'd25: cnt <= 3'd1; //cnt=1:scl高电平中间,用于数据采样 9'd52: cnt <= 3'd2; //cnt=2:scl下降沿后面点 9'd76: cnt <= 3'd3; //cnt=3:scl低电平中间,用于数据变化 9'd98: cnt <= 3'd0; //cnt=0:scl上升沿前面点 default: cnt <= 3'd5; endcase end end `define SCL_POS (cnt==3'd0) //cnt=0:scl上升沿前面点 `define SCL_HIG (cnt==3'd1) //cnt=1:scl高电平中间,用于数据采样 `define SCL_NEG (cnt==3'd2) //cnt=2:scl下降沿后面点 `define SCL_LOW (cnt==3'd3) //cnt=3:scl低电平中间,用于数据变化 always @ (posedge clk or negedge rst_n) if(!rst_n) scl_r <= 1'b0; else if(cnt_delay==9'd99) scl_r <= 1'b1; //scl信号上升沿 else if(cnt_delay==9'd49) scl_r <= 1'b0; //scl信号下降沿 assign scl = scl_r; //产生iic所需要的时钟 //--------------------------------------------- reg [6:0] DEVICE;// //被寻址器件地址(写操作) reg [7:0]DEVICE_WRITE; reg [7:0] WRITE_DATA0;// 8'b1000_1000 reg [7:0] WRITE_DATA1;// 8'b0010_0001 //写入的数据 reg [7:0] WRITE_DATA2; //8'b0100_0011 reg [7:0] WRITE_DATA3; //8'b0110_0101 reg [7:0] WRITE_DATA4; //8'b1000_0111 reg [7:0] BYTE_ADDR;// 8'b0000_0100 //写入的地址寄存器 reg [4:0] PAGEDATA_NUM; //页读页写数据个数 always @(posedge clk or negedge rst_n) begin if(!rst_n) begin DEVICE<=0; PAGEDATA_NUM<=0; WRITE_DATA0<=0; WRITE_DATA1<=0; WRITE_DATA2<=0; WRITE_DATA3<=0; WRITE_DATA4<=0; BYTE_ADDR<=0; end else begin if(REG_WR) begin case(addr) 3'b000: DEVICE<=IDAT[6:0]; 3'b001: BYTE_ADDR<=IDAT; 3'b010: PAGEDATA_NUM<=IDAT; 3'b011: WRITE_DATA0<=IDAT; 3'b100: WRITE_DATA1<=IDAT; 3'b101: WRITE_DATA2<=IDAT; 3'b110: WRITE_DATA3<=IDAT; 3'b111: WRITE_DATA4<=IDAT; endcase end end end reg[7:0] db_r; //在IIC上传送的数据寄存器 reg[7:0] read_data; //读出EEPROM的数据寄存器 reg[7:0] outdata_r; //输出数据贮存器 //--------------------------------------------- //读、写时序 parameter IDLE = 17'b0_0000_0000_0000_0001;//初始态 parameter START1 = 17'b0_0000_0000_0000_0010;//起始信号 parameter ADD1 = 17'b0_0000_0000_0000_0100;//写入器件地址 parameter ACK1 = 17'b0_0000_0000_0000_1000;//应答 parameter ADD2 = 17'b0_0000_0000_0001_0000;//写入字节地址 parameter ACK2 = 17'b0_0000_0000_0010_0000;//应答 parameter START2 = 17'b0_0000_0000_0100_0000;//读操作开始前的起始信号 parameter ADD3 = 17'b0_0000_0000_1000_0000;//写入器件地址 parameter ACK3 = 17'b0_0000_0001_0000_0000;//应答 parameter ACKR = 17'b1_0000_0000_0000_0000;//fpga给应答 parameter DATA = 17'b0_0000_0010_0000_0000;//字节读写 parameter PAGER = 17'b0_0000_0100_0000_0000;//页读 parameter PAGEW = 17'b0_0000_1000_0000_0000;//页写 parameter ACK4 = 17'b0_0001_0000_0000_0000;//应答 parameter HIGH = 17'b0_0010_0000_0000_0000;//高电平 parameter STOP1 = 17'b0_0100_0000_0000_0000;//停止位 parameter STOP2 = 17'b0_1000_0000_0000_0000;//延时同步 reg[16:0] cstate; //状态寄存器 reg sda_r; //输出数据寄存器 output reg sda_link; //输出数据sda信号inout方向控制位 reg[3:0] num; //读写的字节计数 reg[2:0] ackflag;//连读时的数据标志 reg[2:0] pagecnt;//连读连写时的数据计数器 reg[7:0] pagedata_r;//连读储存器 always @ (posedge clk or negedge rst_n) begin if(!rst_n) begin pagedata_r <= 8'd0; end else begin case(pagecnt) 3'd0: pagedata_r <= WRITE_DATA1; 3'd1: pagedata_r <= WRITE_DATA2; 3'd2: pagedata_r <= WRITE_DATA3; 3'd3: pagedata_r <= WRITE_DATA4; default:; endcase end end //---------------------------------------状态机---------------------------------------------// always@(posedge clk or negedge rst_n) begin if(!rst_n) begin cstate <= IDLE; sda_r <= 1'b1; sda_link <= 1'b0; num <= 4'd0; ackflag <= 3'd0; pagecnt <= 3'd0; read_data <= 8'b0000_0000; outdata_r <= 8'b0000_0000; DEVICE_WRITE <= 0; end else case (cstate) IDLE: begin sda_link <= 1'b1; //数据线sda为input sda_r <= 1'b1; read_data <= 8'b0000_0000; //ackflag <= 3'd0; if(!sw1 || !sw3) DEVICE_WRITE <= {DEVICE,1'b0}; if(!sw2 || !sw4) DEVICE_WRITE <= {DEVICE,1'b1}; if(!sw1 || !sw2 || !sw3 || !sw4) begin //SW1,SW2,SW3,SW4键有一个被按下 db_r <= DEVICE_WRITE; //送器件地址(写操作) cstate <= START1; end else cstate <= IDLE; //没有任何键被按下 end START1: begin if(`SCL_HIG) begin //scl为高电平期间 sda_link <= 1'b1; //数据线sda为output sda_r <= 1'b0; //拉低数据线sda,产生起始位信号 cstate <= ADD1; ackflag <= 1'b0; num <= 4'd0; //num计数清零 end else cstate <= START1; //等待scl高电平中间位置到来 end ADD1: begin if(`SCL_LOW) begin if(num == 4'd8) begin num <= 4'd0; //num计数清零 sda_r <= 1'b1; sda_link <= 1'b0; //sda置为高阻态(input) cstate <= ACK1; end else begin cstate <= ADD1; num <= num+1'b1; case (num) 4'd0: sda_r <= db_r[7]; 4'd1: sda_r <= db_r[6]; 4'd2: sda_r <= db_r[5]; 4'd3: sda_r <= db_r[4]; 4'd4: sda_r <= db_r[3]; 4'd5: sda_r <= db_r[2]; 4'd6: sda_r <= db_r[1]; 4'd7: sda_r <= db_r[0]; default: ; endcase end end else cstate <= ADD1; end ACK1: begin if(`SCL_NEG) begin cstate <= ADD2; //从机响应信号 db_r <= BYTE_ADDR; // 1地址 end else cstate <= ACK1; //等待从机响应 end ADD2: begin if(`SCL_LOW) begin if(num==4'd8) begin num <= 4'd0; //num计数清零 sda_r <= 1'b1; sda_link <= 1'b0; //sda置为高阻态(input) cstate <= ACK2; end else begin sda_link <= 1'b1; //sda作为output num <= num+1'b1; case (num) 4'd0: sda_r <= db_r[7]; 4'd1: sda_r <= db_r[6]; 4'd2: sda_r <= db_r[5]; 4'd3: sda_r <= db_r[4]; 4'd4: sda_r <= db_r[3]; 4'd5: sda_r <= db_r[2]; 4'd6: sda_r <= db_r[1]; 4'd7: sda_r <= db_r[0]; default: ; endcase cstate <= ADD2; end end else cstate <= ADD2; end ACK2: begin if(`SCL_NEG) begin //从机响应信号 if(!sw1) begin cstate <= DATA; //写操作 db_r <= WRITE_DATA0; //写入的数据1 end else if(!sw2) begin cstate <= DATA; //从机响应信号 sda_link <= 1'b0; end else if(!sw4) begin cstate <= PAGER; //从机响应信号 ackflag <= ackflag +1'd1; sda_link <= 1'b0; end else if(!sw3) begin //连写 cstate <= PAGEW; end else cstate <= ACK2; //等待从机响应 end end ACKR: begin sda_r <= 0; //主控制器应答 if(`SCL_NEG && !sw4) begin cstate <= PAGER; ackflag <= ackflag +1'd1; sda_link <= 1'b0; end else cstate <= ACKR; end DATA: begin if(!sw2) begin //读操作 if(num<=4'd7) begin cstate <= DATA; if(`SCL_HIG) begin num <= num+1'b1; case (num) 4'd0: read_data[7] <= sda; 4'd1: read_data[6] <= sda; 4'd2: read_data[5] <= sda; 4'd3: read_data[4] <= sda; 4'd4: read_data[3] <= sda; 4'd5: read_data[2] <= sda; 4'd6: read_data[1] <= sda; 4'd7: read_data[0] <= sda; default: ; endcase end end else if((`SCL_LOW) && (num==4'd8)) begin num <= 4'd0; //num计数清零 //cstate <= ACK4; sda_link <= 1'b1; //无应答 outdata_r <= read_data; ackflag <= 3'd1; //1个数 cstate <= HIGH; end else cstate <= DATA; end else if(!sw1) begin //写操作 sda_link <= 1'b1; if(num<=4'd7) begin cstate <= DATA; if(`SCL_LOW) begin sda_link <= 1'b1; //数据线sda作为output num <= num+1'b1; case (num) 4'd0: sda_r <= db_r[7]; 4'd1: sda_r <= db_r[6]; 4'd2: sda_r <= db_r[5]; 4'd3: sda_r <= db_r[4]; 4'd4: sda_r <= db_r[3]; 4'd5: sda_r <= db_r[2]; 4'd6: sda_r <= db_r[1]; 4'd7: sda_r <= db_r[0]; default: ; endcase end end else if((`SCL_LOW) && (num==4'd8)) begin num <= 4'd0; sda_r <= 1'b1; sda_link <= 1'b0; //sda置为高阻态 cstate <= ACK4; end else cstate <= DATA; end end PAGEW:begin sda_link <= 1'b1; //sda为输出 if(num<=4'd7) begin cstate <= PAGEW; if(`SCL_LOW) begin sda_link <= 1'b1; //数据线sda作为output num <= num+1'b1; case (num) 4'd0: sda_r <= pagedata_r[7]; 4'd1: sda_r <= pagedata_r[6]; 4'd2: sda_r <= pagedata_r[5]; 4'd3: sda_r <= pagedata_r[4]; 4'd4: sda_r <= pagedata_r[3]; 4'd5: sda_r <= pagedata_r[2]; 4'd6: sda_r <= pagedata_r[1]; 4'd7: sda_r <= pagedata_r[0]; default: ; endcase end end else if((`SCL_LOW) && (num==4'd8)&&(pagecnt < PAGEDATA_NUM-1'b1)) begin num <= 4'd0; pagecnt <= pagecnt +1'd1; sda_r <= 1'b1; sda_link <= 1'b0; //sda置为高阻态 cstate <= ACK2; end else if((`SCL_LOW) && (num==4'd8) && (pagecnt == PAGEDATA_NUM -1'b1)) begin num <= 4'd0; //pagecnt <= pagecnt +1'd1; pagecnt <= 1'd0; sda_r <= 1'b1; sda_link <= 1'b0; cstate <= ACK4; end else cstate <= PAGEW; end //end PAGER:begin if(num<=4'd7) begin cstate <= PAGER; if(`SCL_LOW) begin num <= num+1'b1; case (num) 4'd0: read_data[7] <= sda; 4'd1: read_data[6] <= sda; 4'd2: read_data[5] <= sda; 4'd3: read_data[4] <= sda; 4'd4: read_data[3] <= sda; 4'd5: read_data[2] <= sda; 4'd6: read_data[1] <= sda; 4'd7: read_data[0] <= sda; default: ; endcase end end else if((`SCL_LOW) && (num==4'd8)&& (pagecnt < PAGEDATA_NUM-1'b1)) begin num <= 4'd0; pagecnt <= pagecnt +1'd1; outdata_r <= read_data; //ackflag <= ackflag +1'd1; sda_r <= 1'b1; sda_link <= 1'b1; //主控制器应答 cstate <= ACKR; end else if((`SCL_LOW) && (num==4'd8) && (pagecnt == PAGEDATA_NUM -1'b1)) begin num <= 4'd0; //pagecnt <= pagecnt +1'd1; outdata_r <= read_data; ackflag <= ackflag +1'b1; pagecnt <= 1'd0; sda_r <= 1'b1; sda_link <= 1'b1; cstate <= HIGH; end else cstate <= PAGER; end //end ACK4: begin //写操作最后个应答 if(`SCL_NEG) begin cstate <= STOP1; end else cstate <= ACK4; end HIGH: begin if(`SCL_NEG)begin sda_r <= 1'd1; //ackflag <= ackflag +1'd1; cstate <= STOP1; end else cstate <= HIGH; end STOP1: begin if(`SCL_LOW) begin sda_link <= 1'b1; sda_r <= 1'b0; cstate <= STOP1; end else if(`SCL_HIG) begin sda_r <= 1'b1; //scl为高时,sda产生上升沿(结束信号) cstate <= IDLE; end else cstate <= STOP1; end default: cstate <= IDLE; endcase end assign sda = sda_link ? sda_r:1'bz; assign outdata = outdata_r; //--------------------------------------------------------- endmodule
Coq
\begin{tikzpicture} \begin{axis}[width=\marginparwidth+25pt,% tick label style={font=\scriptsize},axis y line=middle,axis x line=middle,name=myplot,axis on top,% %x=.37\marginparwidth, %y=.37\marginparwidth, xtick={1,2,3}, %minor x tick num=1,% % extra x ticks={.33}, % extra x tick labels={$1/3$}, ytick={1,2}, %minor y tick num=1,%extra y ticks={-5,-3,...,7},% ymin=-.5,ymax=1.5,% xmin=-.5,xmax=3.5% ] \filldraw (axis cs:2,0) circle (1.4pt) (axis cs: 1,1) circle (2pt) (axis cs: 3,1) circle (3.16pt) (axis cs: 2.375,0.875) circle (1pt) node [below ] {\scriptsize $(\overline{x},\overline{y})$}; \draw [very thick] (axis cs: 2,0) -- (axis cs:3,1) -- (axis cs:1,1) -- cycle; %\addplot [{\coloronefill},fill={\coloronefill},area style, smooth,domain=1:3,samples=15] {-(x-2)^2+3} -- \addplot [{\coloronefill},fill={\coloronefill},area style, smooth,domain=1:3,samples=15] {x/2} --cycle; %\addplot [{\colorone},thick,fill=white,area style, smooth,domain=0:360,samples=30] ({1+cos(x)},{sin(x)}); % %\addplot [{\colorone},thick,,area style, smooth,domain=0:360,samples=30] ({2+2*cos(x)},{2*sin(x)}); \end{axis} \node [right] at (myplot.right of origin) {\scriptsize $x$}; %\node [above] at (myplot.above origin) {\scriptsize $y$}; \end{tikzpicture}
TeX
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, unicode_literals, print_function """ Input sets for VASP GW calculations Single vasp GW work: Creates input and jobscripts from the input sets for a specific job """ __author__ = "Michiel van Setten" __copyright__ = " " __version__ = "0.9" __maintainer__ = "Michiel van Setten" __email__ = "mjvansetten@gmail.com" __date__ = "May 2014" import os import json import os.path import stat from monty.serialization import loadfn from pymatgen.io.vasp.inputs import Kpoints, Potcar from pymatgen.io.vasp.sets_deprecated import DictVaspInputSet from pymatgen.io.abinit.helpers import s_name MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) GWVaspInputSet = os.path.join(MODULE_DIR, "GWVaspInputSet.yaml") """ MPGWVaspInputSet.joson contains the standards for GW calculations. This set contains all parameters for the first sc dft calculation. The modifications for the subsequent sub calculations are made below. For many settings the number of cores on which the calculations will be run is needed, this number is assumed to be on the environment variable NPARGWCALC. """ class GWscDFTPrepVaspInputSet(DictVaspInputSet): """ Implementation of VaspInputSet overriding MaterialsProjectVaspInputSet for static calculations preparing for a GW calculation. """ TESTS = {} CONVS = {} def __init__(self, structure, spec, functional='PBE', sym_prec=0.01, **kwargs): """ Supports the same kwargs as :class:`JSONVaspInputSet`. """ super(GWscDFTPrepVaspInputSet, self).__init__( "MP Static Self consistent run for GW", loadfn(GWVaspInputSet), **kwargs) self.structure = structure self.tests = self.__class__.get_defaults_tests() self.convs = self.__class__.get_defaults_convs() self.functional = functional self.set_dens(spec) self.sym_prec = sym_prec # todo update the fromdict and todict ot include the new atributes @classmethod def get_defaults_tests(cls): return cls.TESTS.copy() @classmethod def get_defaults_convs(cls): return cls.CONVS.copy() def get_npar(self, structure): """ get 'optimally' useful number of parallelism """ npar = int(self.get_bands(structure) ** 2 * structure.volume / 200) npar = min(max(npar, 1), 52) return npar def set_test(self, test, value): """ Method to switch a specific test on """ all_tests = GWscDFTPrepVaspInputSet.get_defaults_tests() all_tests.update(GWDFTDiagVaspInputSet.get_defaults_tests()) all_tests.update(GWG0W0VaspInputSet.get_defaults_tests()) test_type = all_tests[test]['method'] npar = self.get_npar(self.structure) if test_type == 'incar_settings': self.incar_settings.update({test: value}) if test_type == 'set_nomega': nomega = npar * int(value / npar) self.incar_settings.update({"NOMEGA": int(nomega)}) if test_type == 'set_nbands': nbands = value * self.get_bands(self.structure) nbands = npar * int(nbands / npar + 1) self.incar_settings.update({"NBANDS": int(nbands)}) if test_type == 'kpoint_grid': pass def get_potcar(self, structure): """ Method for getting LDA potcars """ if self.sort_structure: structure = structure.get_sorted_structure() return Potcar(self.get_potcar_symbols(structure), functional=self.functional) def get_kpoints(self, structure): """ Writes out a KPOINTS file using the automated gamma grid method. VASP crashes GW calculations on none gamma centered meshes. """ if self.sort_structure: structure = structure.get_sorted_structure() dens = int(self.kpoints_settings['grid_density']) if dens == 1: return Kpoints.gamma_automatic() else: return Kpoints.automatic_gamma_density(structure, dens) def set_dens(self, spec): """ sets the grid_density to the value specified in spec """ self.kpoints_settings['grid_density'] = spec['kp_grid_dens'] if spec['kp_grid_dens'] < 100: self.incar_settings.update({'ISMEAR': 0}) def get_electrons(self, structure): """ Method for retrieving the number of valence electrons """ valence_list = {} potcar = self.get_potcar(structure) for pot_single in potcar: valence_list.update({pot_single.element: pot_single.nelectrons}) electrons = sum([valence_list[element.symbol] for element in structure.species]) return int(electrons) def get_bands(self, structure): """ Method for retrieving the standard number of bands """ bands = self.get_electrons(structure) / 2 + len(structure) return int(bands) def set_test_calc(self): """ absolute minimal setting for testing """ self.incar_settings.update({"PREC": "low", "ENCUT": 250}) self.kpoints_settings['grid_density'] = 1 def set_prec_high(self): self.incar_settings.update({"PREC": "Accurate", "ENCUT": 400}) class GWDFTDiagVaspInputSet(GWscDFTPrepVaspInputSet): """ Implementation of VaspInputSet overriding MaterialsProjectVaspInputSet for static non self-consistent exact diagonalization step preparing for a GW calculation. """ TESTS = {'NBANDS': {'test_range': (10, 20, 30), 'method': 'set_nbands', 'control': "gap"}} CONVS = {'NBANDS': {'test_range': (10, 20, 30, 40, 50, 60, 70), 'method': 'set_nbands', 'control': "gap"}} def __init__(self, structure, spec, functional='PBE', sym_prec=0.01, **kwargs): """ Supports the same kwargs as :class:`JSONVaspInputSet`. """ super(GWDFTDiagVaspInputSet, self).__init__( structure, spec, functional=functional, sym_prec=sym_prec, **kwargs) self.structure = structure self.tests = self.__class__.get_defaults_tests() self.convs = self.__class__.get_defaults_convs() self.functional = functional self.sym_prec = sym_prec self.set_dens(spec) npar = self.get_npar(self.structure) #single step exact diagonalization, output WAVEDER self.incar_settings.update({"ALGO": "Exact", "NELM": 1, "LOPTICS": "TRUE"}) # for large systems exact diagonalization consumes too much memory self.set_gw_bands(15) self.incar_settings.update({"NPAR": npar}) def set_gw_bands(self, factor=15): """ method to set the number of bands for GW """ gw_bands = self.get_bands(self.structure) gw_bands = self.get_npar(self.structure) * int((factor * gw_bands) / self.get_npar(self.structure) + 1) self.incar_settings.update({"NBANDS": gw_bands}) if gw_bands > 800: self.incar_settings.update({"ALGO": 'fast'}) def set_prec_high(self): super(GWDFTDiagVaspInputSet, self).set_prec_high() self.set_gw_bands(30) class GWG0W0VaspInputSet(GWDFTDiagVaspInputSet): """ Should go to Pymatgen vaspinputsets Implementation of VaspInputSet overriding MaterialsProjectVaspInputSet for static G0W0 calculation """ TESTS = {'ENCUTGW': {'test_range': (200, 300, 400), 'method': 'incar_settings', 'control': "gap"}, 'NOMEGA': {'test_range': (80, 100, 120), 'method': 'set_nomega', 'control': "gap"}} CONVS = {'ENCUTGW': {'test_range': (200, 400, 600, 800), 'method': 'incar_settings', 'control': "gap"}} def __init__(self, structure, spec, functional='PBE', sym_prec=0.01, **kwargs): """ Supports the same kwargs as :class:`JSONVaspInputSet`. """ super(GWG0W0VaspInputSet, self).__init__( structure, spec, functional=functional, sym_prec=sym_prec, **kwargs) self.structure = structure self.tests = self.__class__.get_defaults_tests() self.convs = self.__class__.get_defaults_convs() self.functional = functional self.sym_prec = sym_prec npar = self.get_npar(structure) # G0W0 calculation with reduced cutoff for the response function self.incar_settings.update({"ALGO": "GW0", "ENCUTGW": 250, "LWAVE": "FALSE", "NELM": 1}) self.set_dens(spec) self.nomega_max = 2 * self.get_kpoints(structure).kpts[0][0]**3 nomega = npar * int(self.nomega_max / npar) self.set_gw_bands(15) self.incar_settings.update({"NPAR": npar}) self.incar_settings.update({"NOMEGA": nomega}) self.tests = self.__class__.get_defaults_tests() def wannier_on(self): self.incar_settings.update({"LWANNIER90_RUN": ".TRUE."}) self.incar_settings.update({"LWRITE_MMN_AMN": ".TRUE."}) def spectral_off(self): """ Method to switch the use of the spectral decomposition of the response function of this may be used to reduce memory demands if the calculation crashes due to memory shortage """ self.incar_settings.update({"LSPECTRAL": ".False."}) def gw0_on(self, niter=4, gwbandsfac=4, qpsc=False): """ Method to switch to gw0 calculation with standard 4 iterations """ # set the number of iterations of GW0 self.incar_settings.update({"NELM": niter}) # set the number of bands to update in the iteration of G npar = self.get_npar(self.structure) nbandsgw = self.get_bands(self.structure)*gwbandsfac nbandsgw = npar * int(nbandsgw / npar) self.incar_settings.update({"NBANDSGW": nbandsgw}) # if set also updat the orbitals 'quasi particle self-consistency' if qpsc: self.incar_settings.update({"ALGO": "scGW0"}) # todo update tests .... def set_prec_high(self): super(GWG0W0VaspInputSet, self).set_prec_high() self.incar_settings.update({"ENCUTGW": 400, "NOMEGA": int(self.incar_settings["NOMEGA"]*1.5)}) self.incar_settings.update({"PRECFOCK": "accurate"}) class Wannier90InputSet(): """ class containing the input parameters for the wannier90.win file """ def __init__(self, spec): self.file_name = "wannier90.win" self.settings = {"bands_plot": "true", "num_wann": 2, "num_bands": 4} self.parameters = {"n_include_bands": 1} self.spec = spec def make_kpoint_path(self, structure, f): f.write("\nbegin kpoint_path\n") line = str(structure.vbm_l) + " " + str(structure.vbm[0]) + " " + str(structure.vbm[1]) + " " + str(structure.vbm[2]) line = line + " " + str(structure.cbm_l) + " " + str(structure.cbm[0]) + " " + str(structure.cbm[1]) + " " + str(structure.cbm[2]) f.write(line) f.write("\nend kpoint_path\n\n") pass def make_exclude_bands(self, structure, f): nocc = GWscDFTPrepVaspInputSet(structure, self.spec).get_electrons(structure) / 2 n1 = str(int(1)) n2 = str(int(nocc - self.parameters["n_include_bands"])) n3 = str(int(nocc + 1 + self.parameters["n_include_bands"])) n4 = str(int(GWG0W0VaspInputSet(structure, self.spec).incar_settings["NBANDS"])) line = "exclude_bands : " + n1 + "-" + n2 + ", " + n3 + "-" + n4 + "\n" f.write(line) #todo there is still a bug here... pass def write_file(self, structure, path): f = open(os.path.join(path, self.file_name), mode='w') f.write("bands_plot = ") f.write(self.settings["bands_plot"]) f.write("\n") self.make_kpoint_path(structure, f) f.write("num_wann = ") f.write(str(self.settings["num_wann"])) f.write("\n") f.write("num_bands = ") f.write(str(self.settings["num_bands"])) f.write("\n") self.make_exclude_bands(structure, f) f.close() class SingleVaspGWWork(): """ Create VASP input for a single standard G0W0 and GW0 calculation step the combination of job and option specifies what needs to be created """ def __init__(self, structure, job, spec, option=None, converged=False): self.structure = structure self.job = job self.spec = spec self.option = option self.converged = converged def create_input(self): """ create vasp input """ option_name = '' path_add = '' if self.spec['converge'] and self.converged: path_add = '.conv' if self.option is None: path = s_name(self.structure) else: path = os.path.join(s_name(self.structure) + path_add, str(self.option['test_prep'])+str(self.option['value_prep'])) if 'test' in self.option.keys(): option_name = '.'+str(self.option['test'])+str(self.option['value']) if self.job == 'prep': inpset = GWscDFTPrepVaspInputSet(self.structure, self.spec, functional=self.spec['functional']) if self.spec['converge'] and not self.converged: spec_tmp = self.spec.copy() spec_tmp.update({'kp_grid_dens': 2}) inpset = GWscDFTPrepVaspInputSet(self.structure, spec_tmp, functional=self.spec['functional']) inpset.incar_settings.update({"ENCUT": 800}) if self.spec['test'] or self.spec['converge']: if self.option['test_prep'] in GWscDFTPrepVaspInputSet.get_defaults_convs().keys() or self.option['test_prep'] in GWscDFTPrepVaspInputSet.get_defaults_tests().keys(): inpset.set_test(self.option['test_prep'], self.option['value_prep']) if self.spec["prec"] == "h": inpset.set_prec_high() inpset.write_input(self.structure, path) inpset = GWDFTDiagVaspInputSet(self.structure, self.spec, functional=self.spec['functional']) if self.spec["prec"] == "h": inpset.set_prec_high() if self.spec['converge'] and not self.converged: spec_tmp = self.spec.copy() spec_tmp.update({'kp_grid_dens': 2}) inpset = GWDFTDiagVaspInputSet(self.structure, spec_tmp, functional=self.spec['functional']) inpset.incar_settings.update({"ENCUT": 800}) if self.spec['test'] or self.spec['converge']: inpset.set_test(self.option['test_prep'], self.option['value_prep']) inpset.get_incar(self.structure).write_file(os.path.join(path, 'INCAR.DIAG')) if self.job == 'G0W0': inpset = GWG0W0VaspInputSet(self.structure, self.spec, functional=self.spec['functional']) if self.spec['converge'] and not self.converged: spec_tmp = self.spec.copy() spec_tmp.update({'kp_grid_dens': 2}) inpset = GWG0W0VaspInputSet(self.structure, spec_tmp, functional=self.spec['functional']) inpset.incar_settings.update({"ENCUT": 800}) if self.spec['test'] or self.spec['converge']: inpset.set_test(self.option['test_prep'], self.option['value_prep']) inpset.set_test(self.option['test'], self.option['value']) if self.spec["prec"] == "h": inpset.set_prec_high() if self.spec['kp_grid_dens'] > 20: #inpset.wannier_on() inpset.write_input(self.structure, os.path.join(path, 'G0W0'+option_name)) #w_inpset = Wannier90InputSet(self.spec) #w_inpset.write_file(self.structure, os.path.join(path, 'G0W0'+option_name)) else: inpset.write_input(self.structure, os.path.join(path, 'G0W0'+option_name)) if self.job == 'GW0': inpset = GWG0W0VaspInputSet(self.structure, self.spec, functional=self.spec['functional']) if self.spec['converge'] and not self.converged: spec_tmp = self.spec.copy() spec_tmp.update({'kp_grid_dens': 2}) inpset = GWG0W0VaspInputSet(self.structure, spec_tmp, functional=self.spec['functional']) inpset.incar_settings.update({"ENCUT": 800}) if self.spec['test'] or self.spec['converge']: inpset.set_test(self.option['test_prep'], self.option['value_prep']) inpset.set_test(self.option['test'], self.option['value']) if self.spec["prec"] == "h": inpset.set_prec_high() inpset.gw0_on() if self.spec['kp_grid_dens'] > 20: #inpset.wannier_on() inpset.write_input(self.structure, os.path.join(path, 'GW0'+option_name)) #w_inpset = Wannier90InputSet(self.spec) #w_inpset.write_file(self.structure, os.path.join(path, 'GW0'+option_name)) else: inpset.write_input(self.structure, os.path.join(path, 'GW0'+option_name)) if self.job == 'scGW0': inpset = GWG0W0VaspInputSet(self.structure, self.spec, functional=self.spec['functional']) if self.spec['converge'] and not self.converged: spec_tmp = self.spec.copy() spec_tmp.update({'kp_grid_dens': 2}) inpset = GWG0W0VaspInputSet(self.structure, spec_tmp, functional=self.spec['functional']) inpset.incar_settings.update({"ENCUT": 800}) if self.spec['test'] or self.spec['converge']: inpset.set_test(self.option['test_prep'], self.option['value_prep']) inpset.set_test(self.option['test'], self.option['value']) if self.spec["prec"] == "h": inpset.set_prec_high() inpset.gw0_on(qpsc=True) if self.spec['kp_grid_dens'] > 20: inpset.wannier_on() inpset.write_input(self.structure, os.path.join(path, 'scGW0'+option_name)) w_inpset = Wannier90InputSet(self.spec) w_inpset.write_file(self.structure, os.path.join(path, 'scGW0'+option_name)) else: inpset.write_input(self.structure, os.path.join(path, 'scGW0'+option_name)) def create_job_script(self, add_to_collection=True, mode='pbspro'): if mode == 'slurm': """ Create job script for ceci. """ npar = GWscDFTPrepVaspInputSet(self.structure, self.spec, functional=self.spec['functional']).get_npar(self.structure) if self.option is not None: option_prep_name = str(self.option['test_prep']) + str(self.option['value_prep']) if 'test' in self.option.keys(): option_name = str('.') + str(self.option['test']) + str(self.option['value']) else: option_prep_name = option_name = '' # npar = int(os.environ['NPARGWCALC']) header = ("#!/bin/bash \n" "## standard header for Ceci clusters ## \n" "#SBATCH --mail-user=michiel.vansetten@uclouvain.be \n" "#SBATCH --mail-type=ALL\n" "#SBATCH --time=2-24:0:0 \n" "#SBATCH --cpus-per-task=1 \n" "#SBATCH --mem-per-cpu=4000 \n") path_add = '' if self.spec['converge'] and self.converged: path_add = '.conv' if self.job == 'prep': path = os.path.join(s_name(self.structure) + path_add, option_prep_name) # create this job job_file = open(name=os.path.join(path, 'job'), mode='w') job_file.write(header) job_file.write('#SBATCH --job-name='+s_name(self.structure)+self.job+'\n') job_file.write('#SBATCH --ntasks='+str(npar)+'\n') job_file.write('module load vasp \n') job_file.write('mpirun vasp \n') job_file.write('cp OUTCAR OUTCAR.sc \n') job_file.write('cp INCAR.DIAG INCAR \n') job_file.write('mpirun vasp \n') job_file.write('cp OUTCAR OUTCAR.diag \n') job_file.close() os.chmod(os.path.join(path, 'job'), stat.S_IRWXU) if add_to_collection: job_file = open("job_collection", mode='a') job_file.write('cd ' + path + ' \n') job_file.write('sbatch job \n') job_file.write('cd .. \n') job_file.close() os.chmod("job_collection", stat.S_IRWXU) if self.job in ['G0W0', 'GW0', 'scGW0']: path = os.path.join(s_name(self.structure) + path_add, option_prep_name, self.job + option_name) # create this job job_file = open(name=path+'/job', mode='w') job_file.write(header) job_file.write('#SBATCH --job-name='+s_name(self.structure)+self.job+'\n') job_file.write('#SBATCH --ntasks='+str(npar)+'\n') job_file.write('module load vasp/5.2_par_wannier90 \n') job_file.write('cp ../CHGCAR ../WAVECAR ../WAVEDER . \n') job_file.write('mpirun vasp \n') job_file.write('rm W* \n') #job_file.write('workon pymatgen-GW; get_gap > gap; deactivate') #job_file.write('echo '+path+'`get_gap` >> ../../gaps.dat') job_file.close() os.chmod(path+'/job', stat.S_IRWXU) path = os.path.join(s_name(self.structure) + path_add, option_prep_name) # 'append submission of this job script to that of prep for this structure' if add_to_collection: job_file = open(name=os.path.join(path, 'job'), mode='a') job_file.write('cd ' + self.job + option_name + ' \n') job_file.write('sbatch job \n') job_file.write('cd .. \n') job_file.close() elif mode == 'pbspro': """ Create job script for pbse pro Zenobe. """ npar = GWscDFTPrepVaspInputSet(self.structure, self.spec, functional=self.spec['functional']).get_npar(self.structure) #npar = 96 if self.option is not None: option_prep_name = str(self.option['test_prep']) + str(self.option['value_prep']) if 'test' in self.option.keys(): option_name = str('.') + str(self.option['test']) + str(self.option['value']) else: option_prep_name = option_name = '' # npar = int(os.environ['NPARGWCALC']) header = str("#!/bin/bash \n" + "## standard header for zenobe ## \n" + "#!/bin/bash \n" + "#PBS -q main\n" + "#PBS -l walltime=24:0:00\n" + "#PBS -r y \n" + "#PBS -m abe\n" + "#PBS -M michiel.vansetten@uclouvain.be\n" + "#PBS -W group_list=naps\n" + "#PBS -l pvmem=1900mb\n") path_add = '' if self.spec['converge'] and self.converged: path_add = '.conv' if self.job == 'prep': path = os.path.join(s_name(self.structure) + path_add, option_prep_name) abs_path = os.path.abspath(path) # create this job job_file = open(name=os.path.join(path, 'job'), mode='w') job_file.write(header) job_file.write("#PBS -l select=%s:ncpus=1:vmem=1900mb:mpiprocs=1:ompthreads=1\n" % str(npar)) job_file.write('#PBS -o %s/queue.qout\n#PBS -e %s/queue.qerr\ncd %s\n' % (abs_path, abs_path, abs_path)) job_file.write('mpirun -n %s vasp \n' % str(npar)) job_file.write('cp OUTCAR OUTCAR.sc \n') job_file.write('cp INCAR.DIAG INCAR \n') job_file.write('mpirun -n %s vasp \n' % str(npar)) job_file.write('cp OUTCAR OUTCAR.diag \n') job_file.close() os.chmod(os.path.join(path, 'job'), stat.S_IRWXU) if add_to_collection: job_file = open("job_collection", mode='a') job_file.write('cd ' + path + ' \n') job_file.write('qsub job \n') job_file.write('cd ../.. \n') job_file.close() os.chmod("job_collection", stat.S_IRWXU) if self.job in ['G0W0', 'GW0', 'scGW0']: path = os.path.join(s_name(self.structure) + path_add, option_prep_name, self.job + option_name) abs_path = os.path.abspath(path) # create this job job_file = open(name=path+'/job', mode='w') job_file.write(header) job_file.write("#PBS -l select=%s:ncpus=1:vmem=1000mb:mpiprocs=1:ompthreads=1\n" % str(npar)) job_file.write('#PBS -o %s/queue.qout\n#PBS -e %s/queue.qerr\ncd %s\n' % (abs_path, abs_path, abs_path)) job_file.write('cp ../CHGCAR ../WAVECAR ../WAVEDER . \n') job_file.write('mpirun -n %s vasp \n' % str(npar)) job_file.write('rm W* \n') #job_file.write('workon pymatgen-GW; get_gap > gap; deactivate') #job_file.write('echo '+path+'`get_gap` >> ../../gaps.dat') job_file.close() os.chmod(path+'/job', stat.S_IRWXU) path = os.path.join(s_name(self.structure) + path_add, option_prep_name) # 'append submission of this job script to that of prep for this structure' if add_to_collection: job_file = open(name=os.path.join(path, 'job'), mode='a') job_file.write('cd ' + self.job + option_name + ' \n') job_file.write('qsub job \n') job_file.write('cd .. \n') job_file.close()
Python
using module ..\Include.psm1 $Path = ".\Bin\AMD-NiceHash-561\sgminer.exe" $Uri = "https://github.com/nicehash/sgminer/releases/download/5.6.1/sgminer-5.6.1-nicehash-51-windows-amd64.zip" $Commands = [PSCustomObject]@{ #"bitcore" = "" #Bitcore #"blake2s" = "" #Blake2s #"c11" = "" #C11 #"equihash" = " --gpu-threads 2 --worksize 256" #Equihash #"ethash" = " --gpu-threads 1 --worksize 192 --xintensity 1024" #Ethash "groestlcoin" = " --gpu-threads 2 --worksize 128 --intensity d" #Groestl #"hmq1725" = "" #HMQ1725 #"jha" = "" #JHA "maxcoin" = "" #Keccak "lyra2rev2" = " --gpu-threads 2 --worksize 128 --intensity d" #Lyra2RE2 #"lyra2z" = " --worksize 32 --intensity 18" #Lyra2z #"neoscrypt" = " --gpu-threads 1 --worksize 64 --intensity 15" #NeoScrypt #"skunk" = "" #Skunk #"timetravel" = "" #Timetravel #"tribus" = "" #Tribus #"x11evo" = "" #X11evo #"x17" = "" #X17 "yescrypt" = " --worksize 4 --rawintensity 256" #Yescrypt #"xevan-mod" = " --intensity 15" #Xevan } $Name = Get-Item $MyInvocation.MyCommand.Path | Select-Object -ExpandProperty BaseName $Commands | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name | Where-Object {$Pools.(Get-Algorithm $_).Protocol -eq "stratum+tcp" <#temp fix#>} | ForEach-Object { [PSCustomObject]@{ Type = "AMD" Path = $Path Arguments = "--api-listen -k $_ -o $($Pools.(Get-Algorithm $_).Protocol)://$($Pools.(Get-Algorithm $_).Host):$($Pools.(Get-Algorithm $_).Port) -u $($Pools.(Get-Algorithm $_).User) -p $($Pools.(Get-Algorithm $_).Pass)$($Commands.$_) --text-only --gpu-platform $([array]::IndexOf(([OpenCl.Platform]::GetPlatformIDs() | Select-Object -ExpandProperty Vendor), 'Advanced Micro Devices, Inc.'))" HashRates = [PSCustomObject]@{(Get-Algorithm $_) = $Stats."$($Name)_$(Get-Algorithm $_)_HashRate".Week} API = "Xgminer" Port = 4028 URI = $Uri } }
PowerShell
# Stage 1: Build the website FROM node:12.14.1-alpine AS build ARG PALANTIR_VERSION=0.10.3 # Install bins needed RUN apk add --no-cache \ curl \ python \ make \ g++ RUN mkdir /app; \ mkdir /app-src WORKDIR /app # Get the source and extract them RUN curl -o /app/palantir.tar.gz -fSL "https://github.com/CodeCorico/palantir/archive/v${PALANTIR_VERSION}.tar.gz"; \ tar zxvf palantir.tar.gz --strip-components=1; \ rm palantir.tar.gz; \ cp -R /app/* /app-src # Install the deps & build the website RUN npm ci; \ npm run build # Stage 2: Install the cli & server FROM node:12.14.1-alpine ENV SERVER_PORT=80 ENV SERVER_STATICS=/palantir ENV PALANTIR_FILE=/palantir/palantir.json RUN mkdir /app; \ mkdir /palantir WORKDIR /app # Add the docker entrypoints COPY ./docker-entrypoint.sh /usr/local/bin/ RUN chmod +x /usr/local/bin/docker-entrypoint.sh # Backwards compat RUN ln -s usr/local/bin/docker-entrypoint.sh / # Copy sources and dist from the build stage COPY --from=build /app-src /app COPY --from=build /app/dist /app/dist # Install the production deps and install the cli as global RUN npm ci --only=production; \ npm pack; \ npm i -g palantir-*.tgz; \ rm palantir-*.tgz EXPOSE 80 ENTRYPOINT ["docker-entrypoint.sh"] CMD ["npm", "start"]
Dockerfile
synchronization.action.start = Starta synkronisering synchronization.header.contentTitle = Inneh\u00e5llstitel synchronization.header.contentType = Inneh\u00e5llstyp synchronization.header.fileName = Filnamn synchronization.header.relativePath = Relativ s\u00f6kv\u00e4g synchronization.header.space = Utrymme synchronization.header.type = Typ synchronization.label.targetFile = V\u00e4lj m\u00e5lfil/-katalog: synchronization.message.confirm.create = Vill du verkligen skapa inneh\u00e5ll f\u00f6r den valda filen? synchronization.message.confirm.delete = Vill du verkligen ta bort det valda inneh\u00e5llet? synchronization.title = Synkronisera med filsystemet synchronization.title.content = Filer/mappar saknas f\u00f6r f\u00f6ljande inneh\u00e5llsobjekt: synchronization.title.files = Inneh\u00e5llsobjekt saknas f\u00f6r f\u00f6ljande filer/mappar: error.synchronization.common = Ett fel intr\u00e4ffade under synkronisering. error.synchronization.differentSpaces = Inneh\u00e5llet kan inte l\u00e4nkas.\nInneh\u00e5ll och fil/katalog ska vara i samma utrymme. error.synchronization.hierarchy = Du m\u00e5ste skapa inneh\u00e5ll f\u00f6r alla \u00f6verordnade kataloger f\u00f6rst. error.synchronization.incompatibleTypes = Inneh\u00e5llet kan inte l\u00e4nkas.\nInneh\u00e5llsfilen kan endast l\u00e4nkas med fil, inneh\u00e5llskatalogen med katalog. error.synchronization.save = Inneh\u00e5llsfilen/Inneh\u00e5llskatalogen kan inte sparas.\nKontrollera inparametrarna och f\u00f6rs\u00f6k igen.
INI
#!/usr/bin/env groovy def call(String hash, int truncate = 0) { sh "git log -n 1 --pretty=format:%s ${hash} > .git/commit-msg" String msg = readFile(".git/commit-msg").trim() if(truncate) { msg = msg.take(truncate) } return msg }
Groovy
/* * 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.tools.ant.taskdefs.optional.perforce; import java.io.OutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * heavily inspired from LogOutputStream * this stream class calls back the P4Handler on each line of stdout or stderr read */ public class P4OutputStream extends OutputStream { private P4Handler handler; private ByteArrayOutputStream buffer = new ByteArrayOutputStream(); private boolean skip = false; /** * creates a new P4OutputStream for a P4Handler * @param handler the handler which will process the streams */ public P4OutputStream(P4Handler handler) { this.handler = handler; } /** * Write the data to the buffer and flush the buffer, if a line * separator is detected. * * @param cc data to log (byte). * @throws IOException IOException if an I/O error occurs. In particular, * an <code>IOException</code> may be thrown if the * output stream has been closed. */ public void write(int cc) throws IOException { final byte c = (byte) cc; if ((c == '\n') || (c == '\r')) { if (!skip) { processBuffer(); } } else { buffer.write(cc); } skip = (c == '\r'); } /** * Converts the buffer to a string and sends it to <code>processLine</code> */ protected void processBuffer() { handler.process(buffer.toString()); buffer.reset(); } /** * Writes all remaining * @throws IOException if an I/O error occurs. */ public void close() throws IOException { if (buffer.size() > 0) { processBuffer(); } super.close(); } }
Java
/* * Created by SharpDevelop. * User: HAZAMA * Date: 2013/03/02 * Time: 14:28 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Diagnostics; using System.IO; using System.Text; using BVE5Language.Ast; namespace BVE5Language.Parser.Extension { /// <summary> /// The lexer for MathExpressionParser. /// </summary> /*internal class MathExpressionLexer { readonly TextReader reader; Token token = null, //current token la = null; //lookahead token int line_num = 1, column_num = 1; const char EOF = unchecked((char)-1); public Token Current{ get{return token;} } public int CurrentLine{ get{return token.Line;} } /// <summary> /// Initializes a new instance of the <see cref="BVE5Language.Parser.Extension.MathExpressionLexer"/> class. /// </summary> /// <remarks> /// It assumes that the source string doesn't contain any \r. /// Otherwise it fails to tokenize. /// </remarks> /// <param name='srcReader'> /// Source reader. /// </param> public MathExpressionLexer(TextReader srcReader) { if(srcReader == null) throw new ArgumentNullException("srcReader"); reader = srcReader; LookAheadToken(); } /// <summary> /// Checks whether the lexer hits the EOF. /// </summary> /// <returns> /// <c>true</c>, if EOF was encountered, <c>false</c> otherwise. /// </returns> public bool HitEOF() { return token == Token.EOF; } /// <summary> /// Tells the lexer to read the next token and to store it on the internal buffer. /// </summary> public void Advance() { if(la != null){ token = la; }else{ token = Token.EOF; return; } LookAheadToken(); } void LookAheadToken() { SkipWhitespace(); char ch = PeekChar(); switch(ch){ case EOF: la = null; break; case '(': case ')': case '=': case '+': case '-': case '*': case '/': case '$': case '{': case '}': GetChar(); la = new Token(line_num, column_num, ch.ToString(), TokenKind.SyntaxToken); ++column_num; break; case '-': GetChar(); la = GetNumber(true); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': la = GetNumber(false); break; default: throw new BVE5ParserException("Unknown token"); //la = GetId(); //break; } } Token GetNumber(bool isNegativeNumber) { char ch = PeekChar(); Debug.Assert(ch != EOF && char.IsDigit(ch), "Really meant a number?"); var sb = new StringBuilder(isNegativeNumber ? "-" : ""); bool found_dot = false; while(ch != EOF && char.IsDigit(ch) || ch == '.'){ if(ch == '.'){ if(found_dot) throw new BVE5ParserException(line_num, column_num, "A number literal can't have multiple dots in it!"); found_dot = true; } sb.Append(ch); GetChar(); ch = PeekChar(); } var res = AstNode.MakeLiteral(Convert.ToDouble(sb.ToString()), line_num, column_num); column_num += sb.Length; return res; } Token GetId() { char ch = PeekChar(); Debug.Assert(ch != EOF && !IsIdTerminator(ch), "Really meant an string or number?"); var sb = new StringBuilder(); while(ch != EOF && (!IsIdTerminator(ch))){ sb.Append(ch); GetChar(); ch = PeekChar(); } var tmp = new Token(line_num, column_num, sb.ToString(), TokenKind.Identifier); column_num += sb.Length; return tmp; } static bool IsIdTerminator(char c) { return c == '}' || c < (char)33; } void SkipWhitespace() { char ch = PeekChar(); while(char.IsWhiteSpace(ch)){ if(ch == '\n') break; else ++column_num; GetChar(); ch = PeekChar(); } } char GetChar() { return unchecked((char)reader.Read()); } char PeekChar() { return unchecked((char)reader.Peek()); } }*/ }
C#
import 'package:flutter/material.dart'; import 'package:flutter/services.dart' show rootBundle; import 'package:flutter_platform_utils/flutter_platform_utils.dart'; import 'package:vibration/vibration.dart'; import 'package:vibration_ohos/vibration_ohos.dart'; void main() => runApp(const VibratingApp()); class VibratingApp extends StatelessWidget { const VibratingApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Vibration Plugin example app'), ), body: Builder( builder: (BuildContext context) { return Center( child: Column( children: <Widget>[ ElevatedButton( child: const Text('Vibrate for default 500ms'), onPressed: () { Vibration.vibrate(); }, ), ElevatedButton( child: const Text('Vibrate for 1000ms'), onPressed: () { Vibration.vibrate(duration: 1000); }, ), if (!PlatformUtils.isOhos) ElevatedButton( child: const Text('Vibrate with pattern'), onPressed: () { const snackBar = SnackBar( content: Text( 'Pattern: wait 0.5s, vibrate 1s, wait 0.5s, vibrate 2s, wait 0.5s, vibrate 3s, wait 0.5s, vibrate 0.5s', ), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); Vibration.vibrate( pattern: [500, 1000, 500, 2000, 500, 3000, 500, 500], ); }, ), if (!PlatformUtils.isOhos) ElevatedButton( child: const Text('Vibrate with pattern and amplitude'), onPressed: () { const snackBar = SnackBar( content: Text( 'Pattern: wait 0.5s, vibrate 1s, wait 0.5s, vibrate 2s, wait 0.5s, vibrate 3s, wait 0.5s, vibrate 0.5s', ), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); Vibration.vibrate( pattern: [500, 1000, 500, 2000, 500, 3000, 500, 500], intensities: [0, 128, 0, 255, 0, 64, 0, 255], ); }, ), if (PlatformUtils.isOhos) ElevatedButton( child: const Text('Vibrate with VibratePreset'), onPressed: () { (VibrationPlatform.instance as VibrationOhos).vibrate( vibrateEffect: const VibratePreset(count: 100), vibrateAttribute: const VibrateAttribute( usage: 'alarm', ), ); }, ), // ohos only // TODO: not support for now if (PlatformUtils.isOhos) ElevatedButton( child: const Text('Vibrate with custom haptic_file'), onPressed: () { rootBundle.load('assets/haptic_file.json').then((data) { (VibrationPlatform.instance as VibrationOhos).vibrate( vibrateEffect: VibrateFromFile( hapticFd: HapticFileDescriptor( data: data.buffer.asUint8List(), ), ), vibrateAttribute: const VibrateAttribute( usage: 'alarm', ), ); }); }, ) ], ), ); }, ), ), ); } }
Dart
using Guts.Web; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); builder.Services.Configure<ClientSettings>(builder.Configuration.GetSection("Client")); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } //app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.MapControllerRoute( name: "default", pattern: "{controller}/{action=Index}/{id?}"); app.MapFallbackToFile("index.html"); app.Run();
C#